View.java revision 6dd005b48138708762bfade0081d031a2a4a3822
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.view; 18 19import android.content.ClipData; 20import android.content.Context; 21import android.content.res.Configuration; 22import android.content.res.Resources; 23import android.content.res.TypedArray; 24import android.graphics.Bitmap; 25import android.graphics.Camera; 26import android.graphics.Canvas; 27import android.graphics.Interpolator; 28import android.graphics.LinearGradient; 29import android.graphics.Matrix; 30import android.graphics.Paint; 31import android.graphics.PixelFormat; 32import android.graphics.Point; 33import android.graphics.PorterDuff; 34import android.graphics.PorterDuffXfermode; 35import android.graphics.Rect; 36import android.graphics.RectF; 37import android.graphics.Region; 38import android.graphics.Shader; 39import android.graphics.drawable.ColorDrawable; 40import android.graphics.drawable.Drawable; 41import android.os.Handler; 42import android.os.IBinder; 43import android.os.Message; 44import android.os.Parcel; 45import android.os.Parcelable; 46import android.os.RemoteException; 47import android.os.SystemClock; 48import android.util.AttributeSet; 49import android.util.FloatProperty; 50import android.util.LocaleUtil; 51import android.util.Log; 52import android.util.Pool; 53import android.util.Poolable; 54import android.util.PoolableManager; 55import android.util.Pools; 56import android.util.Property; 57import android.util.SparseArray; 58import android.util.TypedValue; 59import android.view.ContextMenu.ContextMenuInfo; 60import android.view.accessibility.AccessibilityEvent; 61import android.view.accessibility.AccessibilityEventSource; 62import android.view.accessibility.AccessibilityManager; 63import android.view.accessibility.AccessibilityNodeInfo; 64import android.view.animation.Animation; 65import android.view.animation.AnimationUtils; 66import android.view.inputmethod.EditorInfo; 67import android.view.inputmethod.InputConnection; 68import android.view.inputmethod.InputMethodManager; 69import android.widget.ScrollBarDrawable; 70 71import com.android.internal.R; 72import com.android.internal.util.Predicate; 73import com.android.internal.view.menu.MenuBuilder; 74 75import java.lang.ref.WeakReference; 76import java.lang.reflect.InvocationTargetException; 77import java.lang.reflect.Method; 78import java.util.ArrayList; 79import java.util.Arrays; 80import java.util.Locale; 81import java.util.WeakHashMap; 82import java.util.concurrent.CopyOnWriteArrayList; 83 84/** 85 * <p> 86 * This class represents the basic building block for user interface components. A View 87 * occupies a rectangular area on the screen and is responsible for drawing and 88 * event handling. View is the base class for <em>widgets</em>, which are 89 * used to create interactive UI components (buttons, text fields, etc.). The 90 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 91 * are invisible containers that hold other Views (or other ViewGroups) and define 92 * their layout properties. 93 * </p> 94 * 95 * <div class="special"> 96 * <p>For an introduction to using this class to develop your 97 * application's user interface, read the Developer Guide documentation on 98 * <strong><a href="{@docRoot}guide/topics/ui/index.html">User Interface</a></strong>. Special topics 99 * include: 100 * <br/><a href="{@docRoot}guide/topics/ui/declaring-layout.html">Declaring Layout</a> 101 * <br/><a href="{@docRoot}guide/topics/ui/menus.html">Creating Menus</a> 102 * <br/><a href="{@docRoot}guide/topics/ui/layout-objects.html">Common Layout Objects</a> 103 * <br/><a href="{@docRoot}guide/topics/ui/binding.html">Binding to Data with AdapterView</a> 104 * <br/><a href="{@docRoot}guide/topics/ui/ui-events.html">Handling UI Events</a> 105 * <br/><a href="{@docRoot}guide/topics/ui/themes.html">Applying Styles and Themes</a> 106 * <br/><a href="{@docRoot}guide/topics/ui/custom-components.html">Building Custom Components</a> 107 * <br/><a href="{@docRoot}guide/topics/ui/how-android-draws.html">How Android Draws Views</a>. 108 * </p> 109 * </div> 110 * 111 * <a name="Using"></a> 112 * <h3>Using Views</h3> 113 * <p> 114 * All of the views in a window are arranged in a single tree. You can add views 115 * either from code or by specifying a tree of views in one or more XML layout 116 * files. There are many specialized subclasses of views that act as controls or 117 * are capable of displaying text, images, or other content. 118 * </p> 119 * <p> 120 * Once you have created a tree of views, there are typically a few types of 121 * common operations you may wish to perform: 122 * <ul> 123 * <li><strong>Set properties:</strong> for example setting the text of a 124 * {@link android.widget.TextView}. The available properties and the methods 125 * that set them will vary among the different subclasses of views. Note that 126 * properties that are known at build time can be set in the XML layout 127 * files.</li> 128 * <li><strong>Set focus:</strong> The framework will handled moving focus in 129 * response to user input. To force focus to a specific view, call 130 * {@link #requestFocus}.</li> 131 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 132 * that will be notified when something interesting happens to the view. For 133 * example, all views will let you set a listener to be notified when the view 134 * gains or loses focus. You can register such a listener using 135 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 136 * Other view subclasses offer more specialized listeners. For example, a Button 137 * exposes a listener to notify clients when the button is clicked.</li> 138 * <li><strong>Set visibility:</strong> You can hide or show views using 139 * {@link #setVisibility(int)}.</li> 140 * </ul> 141 * </p> 142 * <p><em> 143 * Note: The Android framework is responsible for measuring, laying out and 144 * drawing views. You should not call methods that perform these actions on 145 * views yourself unless you are actually implementing a 146 * {@link android.view.ViewGroup}. 147 * </em></p> 148 * 149 * <a name="Lifecycle"></a> 150 * <h3>Implementing a Custom View</h3> 151 * 152 * <p> 153 * To implement a custom view, you will usually begin by providing overrides for 154 * some of the standard methods that the framework calls on all views. You do 155 * not need to override all of these methods. In fact, you can start by just 156 * overriding {@link #onDraw(android.graphics.Canvas)}. 157 * <table border="2" width="85%" align="center" cellpadding="5"> 158 * <thead> 159 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 160 * </thead> 161 * 162 * <tbody> 163 * <tr> 164 * <td rowspan="2">Creation</td> 165 * <td>Constructors</td> 166 * <td>There is a form of the constructor that are called when the view 167 * is created from code and a form that is called when the view is 168 * inflated from a layout file. The second form should parse and apply 169 * any attributes defined in the layout file. 170 * </td> 171 * </tr> 172 * <tr> 173 * <td><code>{@link #onFinishInflate()}</code></td> 174 * <td>Called after a view and all of its children has been inflated 175 * from XML.</td> 176 * </tr> 177 * 178 * <tr> 179 * <td rowspan="3">Layout</td> 180 * <td><code>{@link #onMeasure(int, int)}</code></td> 181 * <td>Called to determine the size requirements for this view and all 182 * of its children. 183 * </td> 184 * </tr> 185 * <tr> 186 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 187 * <td>Called when this view should assign a size and position to all 188 * of its children. 189 * </td> 190 * </tr> 191 * <tr> 192 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 193 * <td>Called when the size of this view has changed. 194 * </td> 195 * </tr> 196 * 197 * <tr> 198 * <td>Drawing</td> 199 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 200 * <td>Called when the view should render its content. 201 * </td> 202 * </tr> 203 * 204 * <tr> 205 * <td rowspan="4">Event processing</td> 206 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 207 * <td>Called when a new key event occurs. 208 * </td> 209 * </tr> 210 * <tr> 211 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 212 * <td>Called when a key up event occurs. 213 * </td> 214 * </tr> 215 * <tr> 216 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 217 * <td>Called when a trackball motion event occurs. 218 * </td> 219 * </tr> 220 * <tr> 221 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 222 * <td>Called when a touch screen motion event occurs. 223 * </td> 224 * </tr> 225 * 226 * <tr> 227 * <td rowspan="2">Focus</td> 228 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 229 * <td>Called when the view gains or loses focus. 230 * </td> 231 * </tr> 232 * 233 * <tr> 234 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 235 * <td>Called when the window containing the view gains or loses focus. 236 * </td> 237 * </tr> 238 * 239 * <tr> 240 * <td rowspan="3">Attaching</td> 241 * <td><code>{@link #onAttachedToWindow()}</code></td> 242 * <td>Called when the view is attached to a window. 243 * </td> 244 * </tr> 245 * 246 * <tr> 247 * <td><code>{@link #onDetachedFromWindow}</code></td> 248 * <td>Called when the view is detached from its window. 249 * </td> 250 * </tr> 251 * 252 * <tr> 253 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 254 * <td>Called when the visibility of the window containing the view 255 * has changed. 256 * </td> 257 * </tr> 258 * </tbody> 259 * 260 * </table> 261 * </p> 262 * 263 * <a name="IDs"></a> 264 * <h3>IDs</h3> 265 * Views may have an integer id associated with them. These ids are typically 266 * assigned in the layout XML files, and are used to find specific views within 267 * the view tree. A common pattern is to: 268 * <ul> 269 * <li>Define a Button in the layout file and assign it a unique ID. 270 * <pre> 271 * <Button 272 * android:id="@+id/my_button" 273 * android:layout_width="wrap_content" 274 * android:layout_height="wrap_content" 275 * android:text="@string/my_button_text"/> 276 * </pre></li> 277 * <li>From the onCreate method of an Activity, find the Button 278 * <pre class="prettyprint"> 279 * Button myButton = (Button) findViewById(R.id.my_button); 280 * </pre></li> 281 * </ul> 282 * <p> 283 * View IDs need not be unique throughout the tree, but it is good practice to 284 * ensure that they are at least unique within the part of the tree you are 285 * searching. 286 * </p> 287 * 288 * <a name="Position"></a> 289 * <h3>Position</h3> 290 * <p> 291 * The geometry of a view is that of a rectangle. A view has a location, 292 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 293 * two dimensions, expressed as a width and a height. The unit for location 294 * and dimensions is the pixel. 295 * </p> 296 * 297 * <p> 298 * It is possible to retrieve the location of a view by invoking the methods 299 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 300 * coordinate of the rectangle representing the view. The latter returns the 301 * top, or Y, coordinate of the rectangle representing the view. These methods 302 * both return the location of the view relative to its parent. For instance, 303 * when getLeft() returns 20, that means the view is located 20 pixels to the 304 * right of the left edge of its direct parent. 305 * </p> 306 * 307 * <p> 308 * In addition, several convenience methods are offered to avoid unnecessary 309 * computations, namely {@link #getRight()} and {@link #getBottom()}. 310 * These methods return the coordinates of the right and bottom edges of the 311 * rectangle representing the view. For instance, calling {@link #getRight()} 312 * is similar to the following computation: <code>getLeft() + getWidth()</code> 313 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 314 * </p> 315 * 316 * <a name="SizePaddingMargins"></a> 317 * <h3>Size, padding and margins</h3> 318 * <p> 319 * The size of a view is expressed with a width and a height. A view actually 320 * possess two pairs of width and height values. 321 * </p> 322 * 323 * <p> 324 * The first pair is known as <em>measured width</em> and 325 * <em>measured height</em>. These dimensions define how big a view wants to be 326 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 327 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 328 * and {@link #getMeasuredHeight()}. 329 * </p> 330 * 331 * <p> 332 * The second pair is simply known as <em>width</em> and <em>height</em>, or 333 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 334 * dimensions define the actual size of the view on screen, at drawing time and 335 * after layout. These values may, but do not have to, be different from the 336 * measured width and height. The width and height can be obtained by calling 337 * {@link #getWidth()} and {@link #getHeight()}. 338 * </p> 339 * 340 * <p> 341 * To measure its dimensions, a view takes into account its padding. The padding 342 * is expressed in pixels for the left, top, right and bottom parts of the view. 343 * Padding can be used to offset the content of the view by a specific amount of 344 * pixels. For instance, a left padding of 2 will push the view's content by 345 * 2 pixels to the right of the left edge. Padding can be set using the 346 * {@link #setPadding(int, int, int, int)} method and queried by calling 347 * {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 348 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}. 349 * </p> 350 * 351 * <p> 352 * Even though a view can define a padding, it does not provide any support for 353 * margins. However, view groups provide such a support. Refer to 354 * {@link android.view.ViewGroup} and 355 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 356 * </p> 357 * 358 * <a name="Layout"></a> 359 * <h3>Layout</h3> 360 * <p> 361 * Layout is a two pass process: a measure pass and a layout pass. The measuring 362 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 363 * of the view tree. Each view pushes dimension specifications down the tree 364 * during the recursion. At the end of the measure pass, every view has stored 365 * its measurements. The second pass happens in 366 * {@link #layout(int,int,int,int)} and is also top-down. During 367 * this pass each parent is responsible for positioning all of its children 368 * using the sizes computed in the measure pass. 369 * </p> 370 * 371 * <p> 372 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 373 * {@link #getMeasuredHeight()} values must be set, along with those for all of 374 * that view's descendants. A view's measured width and measured height values 375 * must respect the constraints imposed by the view's parents. This guarantees 376 * that at the end of the measure pass, all parents accept all of their 377 * children's measurements. A parent view may call measure() more than once on 378 * its children. For example, the parent may measure each child once with 379 * unspecified dimensions to find out how big they want to be, then call 380 * measure() on them again with actual numbers if the sum of all the children's 381 * unconstrained sizes is too big or too small. 382 * </p> 383 * 384 * <p> 385 * The measure pass uses two classes to communicate dimensions. The 386 * {@link MeasureSpec} class is used by views to tell their parents how they 387 * want to be measured and positioned. The base LayoutParams class just 388 * describes how big the view wants to be for both width and height. For each 389 * dimension, it can specify one of: 390 * <ul> 391 * <li> an exact number 392 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 393 * (minus padding) 394 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 395 * enclose its content (plus padding). 396 * </ul> 397 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 398 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 399 * an X and Y value. 400 * </p> 401 * 402 * <p> 403 * MeasureSpecs are used to push requirements down the tree from parent to 404 * child. A MeasureSpec can be in one of three modes: 405 * <ul> 406 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 407 * of a child view. For example, a LinearLayout may call measure() on its child 408 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 409 * tall the child view wants to be given a width of 240 pixels. 410 * <li>EXACTLY: This is used by the parent to impose an exact size on the 411 * child. The child must use this size, and guarantee that all of its 412 * descendants will fit within this size. 413 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 414 * child. The child must gurantee that it and all of its descendants will fit 415 * within this size. 416 * </ul> 417 * </p> 418 * 419 * <p> 420 * To intiate a layout, call {@link #requestLayout}. This method is typically 421 * called by a view on itself when it believes that is can no longer fit within 422 * its current bounds. 423 * </p> 424 * 425 * <a name="Drawing"></a> 426 * <h3>Drawing</h3> 427 * <p> 428 * Drawing is handled by walking the tree and rendering each view that 429 * intersects the the invalid region. Because the tree is traversed in-order, 430 * this means that parents will draw before (i.e., behind) their children, with 431 * siblings drawn in the order they appear in the tree. 432 * If you set a background drawable for a View, then the View will draw it for you 433 * before calling back to its <code>onDraw()</code> method. 434 * </p> 435 * 436 * <p> 437 * Note that the framework will not draw views that are not in the invalid region. 438 * </p> 439 * 440 * <p> 441 * To force a view to draw, call {@link #invalidate()}. 442 * </p> 443 * 444 * <a name="EventHandlingThreading"></a> 445 * <h3>Event Handling and Threading</h3> 446 * <p> 447 * The basic cycle of a view is as follows: 448 * <ol> 449 * <li>An event comes in and is dispatched to the appropriate view. The view 450 * handles the event and notifies any listeners.</li> 451 * <li>If in the course of processing the event, the view's bounds may need 452 * to be changed, the view will call {@link #requestLayout()}.</li> 453 * <li>Similarly, if in the course of processing the event the view's appearance 454 * may need to be changed, the view will call {@link #invalidate()}.</li> 455 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 456 * the framework will take care of measuring, laying out, and drawing the tree 457 * as appropriate.</li> 458 * </ol> 459 * </p> 460 * 461 * <p><em>Note: The entire view tree is single threaded. You must always be on 462 * the UI thread when calling any method on any view.</em> 463 * If you are doing work on other threads and want to update the state of a view 464 * from that thread, you should use a {@link Handler}. 465 * </p> 466 * 467 * <a name="FocusHandling"></a> 468 * <h3>Focus Handling</h3> 469 * <p> 470 * The framework will handle routine focus movement in response to user input. 471 * This includes changing the focus as views are removed or hidden, or as new 472 * views become available. Views indicate their willingness to take focus 473 * through the {@link #isFocusable} method. To change whether a view can take 474 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 475 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 476 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 477 * </p> 478 * <p> 479 * Focus movement is based on an algorithm which finds the nearest neighbor in a 480 * given direction. In rare cases, the default algorithm may not match the 481 * intended behavior of the developer. In these situations, you can provide 482 * explicit overrides by using these XML attributes in the layout file: 483 * <pre> 484 * nextFocusDown 485 * nextFocusLeft 486 * nextFocusRight 487 * nextFocusUp 488 * </pre> 489 * </p> 490 * 491 * 492 * <p> 493 * To get a particular view to take focus, call {@link #requestFocus()}. 494 * </p> 495 * 496 * <a name="TouchMode"></a> 497 * <h3>Touch Mode</h3> 498 * <p> 499 * When a user is navigating a user interface via directional keys such as a D-pad, it is 500 * necessary to give focus to actionable items such as buttons so the user can see 501 * what will take input. If the device has touch capabilities, however, and the user 502 * begins interacting with the interface by touching it, it is no longer necessary to 503 * always highlight, or give focus to, a particular view. This motivates a mode 504 * for interaction named 'touch mode'. 505 * </p> 506 * <p> 507 * For a touch capable device, once the user touches the screen, the device 508 * will enter touch mode. From this point onward, only views for which 509 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 510 * Other views that are touchable, like buttons, will not take focus when touched; they will 511 * only fire the on click listeners. 512 * </p> 513 * <p> 514 * Any time a user hits a directional key, such as a D-pad direction, the view device will 515 * exit touch mode, and find a view to take focus, so that the user may resume interacting 516 * with the user interface without touching the screen again. 517 * </p> 518 * <p> 519 * The touch mode state is maintained across {@link android.app.Activity}s. Call 520 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 521 * </p> 522 * 523 * <a name="Scrolling"></a> 524 * <h3>Scrolling</h3> 525 * <p> 526 * The framework provides basic support for views that wish to internally 527 * scroll their content. This includes keeping track of the X and Y scroll 528 * offset as well as mechanisms for drawing scrollbars. See 529 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 530 * {@link #awakenScrollBars()} for more details. 531 * </p> 532 * 533 * <a name="Tags"></a> 534 * <h3>Tags</h3> 535 * <p> 536 * Unlike IDs, tags are not used to identify views. Tags are essentially an 537 * extra piece of information that can be associated with a view. They are most 538 * often used as a convenience to store data related to views in the views 539 * themselves rather than by putting them in a separate structure. 540 * </p> 541 * 542 * <a name="Animation"></a> 543 * <h3>Animation</h3> 544 * <p> 545 * You can attach an {@link Animation} object to a view using 546 * {@link #setAnimation(Animation)} or 547 * {@link #startAnimation(Animation)}. The animation can alter the scale, 548 * rotation, translation and alpha of a view over time. If the animation is 549 * attached to a view that has children, the animation will affect the entire 550 * subtree rooted by that node. When an animation is started, the framework will 551 * take care of redrawing the appropriate views until the animation completes. 552 * </p> 553 * <p> 554 * Starting with Android 3.0, the preferred way of animating views is to use the 555 * {@link android.animation} package APIs. 556 * </p> 557 * 558 * <a name="Security"></a> 559 * <h3>Security</h3> 560 * <p> 561 * Sometimes it is essential that an application be able to verify that an action 562 * is being performed with the full knowledge and consent of the user, such as 563 * granting a permission request, making a purchase or clicking on an advertisement. 564 * Unfortunately, a malicious application could try to spoof the user into 565 * performing these actions, unaware, by concealing the intended purpose of the view. 566 * As a remedy, the framework offers a touch filtering mechanism that can be used to 567 * improve the security of views that provide access to sensitive functionality. 568 * </p><p> 569 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 570 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 571 * will discard touches that are received whenever the view's window is obscured by 572 * another visible window. As a result, the view will not receive touches whenever a 573 * toast, dialog or other window appears above the view's window. 574 * </p><p> 575 * For more fine-grained control over security, consider overriding the 576 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 577 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 578 * </p> 579 * 580 * @attr ref android.R.styleable#View_alpha 581 * @attr ref android.R.styleable#View_background 582 * @attr ref android.R.styleable#View_clickable 583 * @attr ref android.R.styleable#View_contentDescription 584 * @attr ref android.R.styleable#View_drawingCacheQuality 585 * @attr ref android.R.styleable#View_duplicateParentState 586 * @attr ref android.R.styleable#View_id 587 * @attr ref android.R.styleable#View_fadingEdge 588 * @attr ref android.R.styleable#View_fadingEdgeLength 589 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 590 * @attr ref android.R.styleable#View_fitsSystemWindows 591 * @attr ref android.R.styleable#View_isScrollContainer 592 * @attr ref android.R.styleable#View_focusable 593 * @attr ref android.R.styleable#View_focusableInTouchMode 594 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 595 * @attr ref android.R.styleable#View_keepScreenOn 596 * @attr ref android.R.styleable#View_layerType 597 * @attr ref android.R.styleable#View_longClickable 598 * @attr ref android.R.styleable#View_minHeight 599 * @attr ref android.R.styleable#View_minWidth 600 * @attr ref android.R.styleable#View_nextFocusDown 601 * @attr ref android.R.styleable#View_nextFocusLeft 602 * @attr ref android.R.styleable#View_nextFocusRight 603 * @attr ref android.R.styleable#View_nextFocusUp 604 * @attr ref android.R.styleable#View_onClick 605 * @attr ref android.R.styleable#View_padding 606 * @attr ref android.R.styleable#View_paddingBottom 607 * @attr ref android.R.styleable#View_paddingLeft 608 * @attr ref android.R.styleable#View_paddingRight 609 * @attr ref android.R.styleable#View_paddingTop 610 * @attr ref android.R.styleable#View_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 * @hide 2172 */ 2173 @ViewDebug.ExportedProperty(category = "padding") 2174 protected int mUserPaddingRight; 2175 2176 /** 2177 * Cache the paddingBottom set by the user to append to the scrollbar's size. 2178 * 2179 * @hide 2180 */ 2181 @ViewDebug.ExportedProperty(category = "padding") 2182 protected int mUserPaddingBottom; 2183 2184 /** 2185 * Cache the paddingLeft set by the user to append to the scrollbar's size. 2186 * 2187 * @hide 2188 */ 2189 @ViewDebug.ExportedProperty(category = "padding") 2190 protected int mUserPaddingLeft; 2191 2192 /** 2193 * Cache if the user padding is relative. 2194 * 2195 */ 2196 @ViewDebug.ExportedProperty(category = "padding") 2197 boolean mUserPaddingRelative; 2198 2199 /** 2200 * Cache the paddingStart set by the user to append to the scrollbar's size. 2201 * 2202 */ 2203 @ViewDebug.ExportedProperty(category = "padding") 2204 int mUserPaddingStart; 2205 2206 /** 2207 * Cache the paddingEnd set by the user to append to the scrollbar's size. 2208 * 2209 */ 2210 @ViewDebug.ExportedProperty(category = "padding") 2211 int mUserPaddingEnd; 2212 2213 /** 2214 * @hide 2215 */ 2216 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 2217 /** 2218 * @hide 2219 */ 2220 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 2221 2222 private Resources mResources = null; 2223 2224 private Drawable mBGDrawable; 2225 2226 private int mBackgroundResource; 2227 private boolean mBackgroundSizeChanged; 2228 2229 /** 2230 * Listener used to dispatch focus change events. 2231 * This field should be made private, so it is hidden from the SDK. 2232 * {@hide} 2233 */ 2234 protected OnFocusChangeListener mOnFocusChangeListener; 2235 2236 /** 2237 * Listeners for layout change events. 2238 */ 2239 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 2240 2241 /** 2242 * Listeners for attach events. 2243 */ 2244 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 2245 2246 /** 2247 * Listener used to dispatch click events. 2248 * This field should be made private, so it is hidden from the SDK. 2249 * {@hide} 2250 */ 2251 protected OnClickListener mOnClickListener; 2252 2253 /** 2254 * Listener used to dispatch long click events. 2255 * This field should be made private, so it is hidden from the SDK. 2256 * {@hide} 2257 */ 2258 protected OnLongClickListener mOnLongClickListener; 2259 2260 /** 2261 * Listener used to build the context menu. 2262 * This field should be made private, so it is hidden from the SDK. 2263 * {@hide} 2264 */ 2265 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 2266 2267 private OnKeyListener mOnKeyListener; 2268 2269 private OnTouchListener mOnTouchListener; 2270 2271 private OnHoverListener mOnHoverListener; 2272 2273 private OnGenericMotionListener mOnGenericMotionListener; 2274 2275 private OnDragListener mOnDragListener; 2276 2277 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 2278 2279 /** 2280 * The application environment this view lives in. 2281 * This field should be made private, so it is hidden from the SDK. 2282 * {@hide} 2283 */ 2284 protected Context mContext; 2285 2286 private ScrollabilityCache mScrollCache; 2287 2288 private int[] mDrawableState = null; 2289 2290 /** 2291 * Set to true when drawing cache is enabled and cannot be created. 2292 * 2293 * @hide 2294 */ 2295 public boolean mCachingFailed; 2296 2297 private Bitmap mDrawingCache; 2298 private Bitmap mUnscaledDrawingCache; 2299 private DisplayList mDisplayList; 2300 private HardwareLayer mHardwareLayer; 2301 2302 /** 2303 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 2304 * the user may specify which view to go to next. 2305 */ 2306 private int mNextFocusLeftId = View.NO_ID; 2307 2308 /** 2309 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 2310 * the user may specify which view to go to next. 2311 */ 2312 private int mNextFocusRightId = View.NO_ID; 2313 2314 /** 2315 * When this view has focus and the next focus is {@link #FOCUS_UP}, 2316 * the user may specify which view to go to next. 2317 */ 2318 private int mNextFocusUpId = View.NO_ID; 2319 2320 /** 2321 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 2322 * the user may specify which view to go to next. 2323 */ 2324 private int mNextFocusDownId = View.NO_ID; 2325 2326 /** 2327 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 2328 * the user may specify which view to go to next. 2329 */ 2330 int mNextFocusForwardId = View.NO_ID; 2331 2332 private CheckForLongPress mPendingCheckForLongPress; 2333 private CheckForTap mPendingCheckForTap = null; 2334 private PerformClick mPerformClick; 2335 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 2336 2337 private UnsetPressedState mUnsetPressedState; 2338 2339 /** 2340 * Whether the long press's action has been invoked. The tap's action is invoked on the 2341 * up event while a long press is invoked as soon as the long press duration is reached, so 2342 * a long press could be performed before the tap is checked, in which case the tap's action 2343 * should not be invoked. 2344 */ 2345 private boolean mHasPerformedLongPress; 2346 2347 /** 2348 * The minimum height of the view. We'll try our best to have the height 2349 * of this view to at least this amount. 2350 */ 2351 @ViewDebug.ExportedProperty(category = "measurement") 2352 private int mMinHeight; 2353 2354 /** 2355 * The minimum width of the view. We'll try our best to have the width 2356 * of this view to at least this amount. 2357 */ 2358 @ViewDebug.ExportedProperty(category = "measurement") 2359 private int mMinWidth; 2360 2361 /** 2362 * The delegate to handle touch events that are physically in this view 2363 * but should be handled by another view. 2364 */ 2365 private TouchDelegate mTouchDelegate = null; 2366 2367 /** 2368 * Solid color to use as a background when creating the drawing cache. Enables 2369 * the cache to use 16 bit bitmaps instead of 32 bit. 2370 */ 2371 private int mDrawingCacheBackgroundColor = 0; 2372 2373 /** 2374 * Special tree observer used when mAttachInfo is null. 2375 */ 2376 private ViewTreeObserver mFloatingTreeObserver; 2377 2378 /** 2379 * Cache the touch slop from the context that created the view. 2380 */ 2381 private int mTouchSlop; 2382 2383 /** 2384 * Object that handles automatic animation of view properties. 2385 */ 2386 private ViewPropertyAnimator mAnimator = null; 2387 2388 /** 2389 * Flag indicating that a drag can cross window boundaries. When 2390 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 2391 * with this flag set, all visible applications will be able to participate 2392 * in the drag operation and receive the dragged content. 2393 * 2394 * @hide 2395 */ 2396 public static final int DRAG_FLAG_GLOBAL = 1; 2397 2398 /** 2399 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 2400 */ 2401 private float mVerticalScrollFactor; 2402 2403 /** 2404 * Position of the vertical scroll bar. 2405 */ 2406 private int mVerticalScrollbarPosition; 2407 2408 /** 2409 * Position the scroll bar at the default position as determined by the system. 2410 */ 2411 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 2412 2413 /** 2414 * Position the scroll bar along the left edge. 2415 */ 2416 public static final int SCROLLBAR_POSITION_LEFT = 1; 2417 2418 /** 2419 * Position the scroll bar along the right edge. 2420 */ 2421 public static final int SCROLLBAR_POSITION_RIGHT = 2; 2422 2423 /** 2424 * Indicates that the view does not have a layer. 2425 * 2426 * @see #getLayerType() 2427 * @see #setLayerType(int, android.graphics.Paint) 2428 * @see #LAYER_TYPE_SOFTWARE 2429 * @see #LAYER_TYPE_HARDWARE 2430 */ 2431 public static final int LAYER_TYPE_NONE = 0; 2432 2433 /** 2434 * <p>Indicates that the view has a software layer. A software layer is backed 2435 * by a bitmap and causes the view to be rendered using Android's software 2436 * rendering pipeline, even if hardware acceleration is enabled.</p> 2437 * 2438 * <p>Software layers have various usages:</p> 2439 * <p>When the application is not using hardware acceleration, a software layer 2440 * is useful to apply a specific color filter and/or blending mode and/or 2441 * translucency to a view and all its children.</p> 2442 * <p>When the application is using hardware acceleration, a software layer 2443 * is useful to render drawing primitives not supported by the hardware 2444 * accelerated pipeline. It can also be used to cache a complex view tree 2445 * into a texture and reduce the complexity of drawing operations. For instance, 2446 * when animating a complex view tree with a translation, a software layer can 2447 * be used to render the view tree only once.</p> 2448 * <p>Software layers should be avoided when the affected view tree updates 2449 * often. Every update will require to re-render the software layer, which can 2450 * potentially be slow (particularly when hardware acceleration is turned on 2451 * since the layer will have to be uploaded into a hardware texture after every 2452 * update.)</p> 2453 * 2454 * @see #getLayerType() 2455 * @see #setLayerType(int, android.graphics.Paint) 2456 * @see #LAYER_TYPE_NONE 2457 * @see #LAYER_TYPE_HARDWARE 2458 */ 2459 public static final int LAYER_TYPE_SOFTWARE = 1; 2460 2461 /** 2462 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 2463 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 2464 * OpenGL hardware) and causes the view to be rendered using Android's hardware 2465 * rendering pipeline, but only if hardware acceleration is turned on for the 2466 * view hierarchy. When hardware acceleration is turned off, hardware layers 2467 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 2468 * 2469 * <p>A hardware layer is useful to apply a specific color filter and/or 2470 * blending mode and/or translucency to a view and all its children.</p> 2471 * <p>A hardware layer can be used to cache a complex view tree into a 2472 * texture and reduce the complexity of drawing operations. For instance, 2473 * when animating a complex view tree with a translation, a hardware layer can 2474 * be used to render the view tree only once.</p> 2475 * <p>A hardware layer can also be used to increase the rendering quality when 2476 * rotation transformations are applied on a view. It can also be used to 2477 * prevent potential clipping issues when applying 3D transforms on a view.</p> 2478 * 2479 * @see #getLayerType() 2480 * @see #setLayerType(int, android.graphics.Paint) 2481 * @see #LAYER_TYPE_NONE 2482 * @see #LAYER_TYPE_SOFTWARE 2483 */ 2484 public static final int LAYER_TYPE_HARDWARE = 2; 2485 2486 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 2487 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 2488 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 2489 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 2490 }) 2491 int mLayerType = LAYER_TYPE_NONE; 2492 Paint mLayerPaint; 2493 Rect mLocalDirtyRect; 2494 2495 /** 2496 * Set to true when the view is sending hover accessibility events because it 2497 * is the innermost hovered view. 2498 */ 2499 private boolean mSendingHoverAccessibilityEvents; 2500 2501 /** 2502 * Text direction is inherited thru {@link ViewGroup} 2503 * @hide 2504 */ 2505 public static final int TEXT_DIRECTION_INHERIT = 0; 2506 2507 /** 2508 * Text direction is using "first strong algorithm". The first strong directional character 2509 * determines the paragraph direction. If there is no strong directional character, the 2510 * paragraph direction is the view's resolved ayout direction. 2511 * 2512 * @hide 2513 */ 2514 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 2515 2516 /** 2517 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 2518 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 2519 * If there are neither, the paragraph direction is the view's resolved layout direction. 2520 * 2521 * @hide 2522 */ 2523 public static final int TEXT_DIRECTION_ANY_RTL = 2; 2524 2525 /** 2526 * Text direction is the same as the one held by a 60% majority of the characters. If there is 2527 * no majority then the paragraph direction is the resolved layout direction of the View. 2528 * 2529 * @hide 2530 */ 2531 public static final int TEXT_DIRECTION_CHAR_COUNT = 3; 2532 2533 /** 2534 * Text direction is forced to LTR. 2535 * 2536 * @hide 2537 */ 2538 public static final int TEXT_DIRECTION_LTR = 4; 2539 2540 /** 2541 * Text direction is forced to RTL. 2542 * 2543 * @hide 2544 */ 2545 public static final int TEXT_DIRECTION_RTL = 5; 2546 2547 /** 2548 * Default text direction is inherited 2549 */ 2550 protected static int DEFAULT_TEXT_DIRECTION = TEXT_DIRECTION_INHERIT; 2551 2552 /** 2553 * Default threshold for "char count" heuristic. 2554 */ 2555 protected static float DEFAULT_TEXT_DIRECTION_CHAR_COUNT_THRESHOLD = 0.6f; 2556 2557 /** 2558 * The text direction that has been defined by {@link #setTextDirection(int)}. 2559 * 2560 * {@hide} 2561 */ 2562 @ViewDebug.ExportedProperty(category = "text", mapping = { 2563 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 2564 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 2565 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 2566 @ViewDebug.IntToString(from = TEXT_DIRECTION_CHAR_COUNT, to = "CHAR_COUNT"), 2567 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 2568 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL") 2569 }) 2570 private int mTextDirection = DEFAULT_TEXT_DIRECTION; 2571 2572 /** 2573 * The resolved text direction. This needs resolution if the value is 2574 * TEXT_DIRECTION_INHERIT. The resolution matches mTextDirection if that is 2575 * not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds up the parent 2576 * chain of the view. 2577 * 2578 * {@hide} 2579 */ 2580 @ViewDebug.ExportedProperty(category = "text", mapping = { 2581 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 2582 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 2583 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 2584 @ViewDebug.IntToString(from = TEXT_DIRECTION_CHAR_COUNT, to = "CHAR_COUNT"), 2585 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 2586 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL") 2587 }) 2588 private int mResolvedTextDirection = TEXT_DIRECTION_INHERIT; 2589 2590 /** 2591 * Consistency verifier for debugging purposes. 2592 * @hide 2593 */ 2594 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 2595 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 2596 new InputEventConsistencyVerifier(this, 0) : null; 2597 2598 /** 2599 * Simple constructor to use when creating a view from code. 2600 * 2601 * @param context The Context the view is running in, through which it can 2602 * access the current theme, resources, etc. 2603 */ 2604 public View(Context context) { 2605 mContext = context; 2606 mResources = context != null ? context.getResources() : null; 2607 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED | LAYOUT_DIRECTION_INHERIT; 2608 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 2609 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 2610 mUserPaddingStart = -1; 2611 mUserPaddingEnd = -1; 2612 mUserPaddingRelative = false; 2613 } 2614 2615 /** 2616 * Constructor that is called when inflating a view from XML. This is called 2617 * when a view is being constructed from an XML file, supplying attributes 2618 * that were specified in the XML file. This version uses a default style of 2619 * 0, so the only attribute values applied are those in the Context's Theme 2620 * and the given AttributeSet. 2621 * 2622 * <p> 2623 * The method onFinishInflate() will be called after all children have been 2624 * added. 2625 * 2626 * @param context The Context the view is running in, through which it can 2627 * access the current theme, resources, etc. 2628 * @param attrs The attributes of the XML tag that is inflating the view. 2629 * @see #View(Context, AttributeSet, int) 2630 */ 2631 public View(Context context, AttributeSet attrs) { 2632 this(context, attrs, 0); 2633 } 2634 2635 /** 2636 * Perform inflation from XML and apply a class-specific base style. This 2637 * constructor of View allows subclasses to use their own base style when 2638 * they are inflating. For example, a Button class's constructor would call 2639 * this version of the super class constructor and supply 2640 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows 2641 * the theme's button style to modify all of the base view attributes (in 2642 * particular its background) as well as the Button class's attributes. 2643 * 2644 * @param context The Context the view is running in, through which it can 2645 * access the current theme, resources, etc. 2646 * @param attrs The attributes of the XML tag that is inflating the view. 2647 * @param defStyle The default style to apply to this view. If 0, no style 2648 * will be applied (beyond what is included in the theme). This may 2649 * either be an attribute resource, whose value will be retrieved 2650 * from the current theme, or an explicit style resource. 2651 * @see #View(Context, AttributeSet) 2652 */ 2653 public View(Context context, AttributeSet attrs, int defStyle) { 2654 this(context); 2655 2656 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View, 2657 defStyle, 0); 2658 2659 Drawable background = null; 2660 2661 int leftPadding = -1; 2662 int topPadding = -1; 2663 int rightPadding = -1; 2664 int bottomPadding = -1; 2665 int startPadding = -1; 2666 int endPadding = -1; 2667 2668 int padding = -1; 2669 2670 int viewFlagValues = 0; 2671 int viewFlagMasks = 0; 2672 2673 boolean setScrollContainer = false; 2674 2675 int x = 0; 2676 int y = 0; 2677 2678 float tx = 0; 2679 float ty = 0; 2680 float rotation = 0; 2681 float rotationX = 0; 2682 float rotationY = 0; 2683 float sx = 1f; 2684 float sy = 1f; 2685 boolean transformSet = false; 2686 2687 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 2688 2689 int overScrollMode = mOverScrollMode; 2690 final int N = a.getIndexCount(); 2691 for (int i = 0; i < N; i++) { 2692 int attr = a.getIndex(i); 2693 switch (attr) { 2694 case com.android.internal.R.styleable.View_background: 2695 background = a.getDrawable(attr); 2696 break; 2697 case com.android.internal.R.styleable.View_padding: 2698 padding = a.getDimensionPixelSize(attr, -1); 2699 break; 2700 case com.android.internal.R.styleable.View_paddingLeft: 2701 leftPadding = a.getDimensionPixelSize(attr, -1); 2702 break; 2703 case com.android.internal.R.styleable.View_paddingTop: 2704 topPadding = a.getDimensionPixelSize(attr, -1); 2705 break; 2706 case com.android.internal.R.styleable.View_paddingRight: 2707 rightPadding = a.getDimensionPixelSize(attr, -1); 2708 break; 2709 case com.android.internal.R.styleable.View_paddingBottom: 2710 bottomPadding = a.getDimensionPixelSize(attr, -1); 2711 break; 2712 case com.android.internal.R.styleable.View_paddingStart: 2713 startPadding = a.getDimensionPixelSize(attr, -1); 2714 break; 2715 case com.android.internal.R.styleable.View_paddingEnd: 2716 endPadding = a.getDimensionPixelSize(attr, -1); 2717 break; 2718 case com.android.internal.R.styleable.View_scrollX: 2719 x = a.getDimensionPixelOffset(attr, 0); 2720 break; 2721 case com.android.internal.R.styleable.View_scrollY: 2722 y = a.getDimensionPixelOffset(attr, 0); 2723 break; 2724 case com.android.internal.R.styleable.View_alpha: 2725 setAlpha(a.getFloat(attr, 1f)); 2726 break; 2727 case com.android.internal.R.styleable.View_transformPivotX: 2728 setPivotX(a.getDimensionPixelOffset(attr, 0)); 2729 break; 2730 case com.android.internal.R.styleable.View_transformPivotY: 2731 setPivotY(a.getDimensionPixelOffset(attr, 0)); 2732 break; 2733 case com.android.internal.R.styleable.View_translationX: 2734 tx = a.getDimensionPixelOffset(attr, 0); 2735 transformSet = true; 2736 break; 2737 case com.android.internal.R.styleable.View_translationY: 2738 ty = a.getDimensionPixelOffset(attr, 0); 2739 transformSet = true; 2740 break; 2741 case com.android.internal.R.styleable.View_rotation: 2742 rotation = a.getFloat(attr, 0); 2743 transformSet = true; 2744 break; 2745 case com.android.internal.R.styleable.View_rotationX: 2746 rotationX = a.getFloat(attr, 0); 2747 transformSet = true; 2748 break; 2749 case com.android.internal.R.styleable.View_rotationY: 2750 rotationY = a.getFloat(attr, 0); 2751 transformSet = true; 2752 break; 2753 case com.android.internal.R.styleable.View_scaleX: 2754 sx = a.getFloat(attr, 1f); 2755 transformSet = true; 2756 break; 2757 case com.android.internal.R.styleable.View_scaleY: 2758 sy = a.getFloat(attr, 1f); 2759 transformSet = true; 2760 break; 2761 case com.android.internal.R.styleable.View_id: 2762 mID = a.getResourceId(attr, NO_ID); 2763 break; 2764 case com.android.internal.R.styleable.View_tag: 2765 mTag = a.getText(attr); 2766 break; 2767 case com.android.internal.R.styleable.View_fitsSystemWindows: 2768 if (a.getBoolean(attr, false)) { 2769 viewFlagValues |= FITS_SYSTEM_WINDOWS; 2770 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 2771 } 2772 break; 2773 case com.android.internal.R.styleable.View_focusable: 2774 if (a.getBoolean(attr, false)) { 2775 viewFlagValues |= FOCUSABLE; 2776 viewFlagMasks |= FOCUSABLE_MASK; 2777 } 2778 break; 2779 case com.android.internal.R.styleable.View_focusableInTouchMode: 2780 if (a.getBoolean(attr, false)) { 2781 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 2782 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 2783 } 2784 break; 2785 case com.android.internal.R.styleable.View_clickable: 2786 if (a.getBoolean(attr, false)) { 2787 viewFlagValues |= CLICKABLE; 2788 viewFlagMasks |= CLICKABLE; 2789 } 2790 break; 2791 case com.android.internal.R.styleable.View_longClickable: 2792 if (a.getBoolean(attr, false)) { 2793 viewFlagValues |= LONG_CLICKABLE; 2794 viewFlagMasks |= LONG_CLICKABLE; 2795 } 2796 break; 2797 case com.android.internal.R.styleable.View_saveEnabled: 2798 if (!a.getBoolean(attr, true)) { 2799 viewFlagValues |= SAVE_DISABLED; 2800 viewFlagMasks |= SAVE_DISABLED_MASK; 2801 } 2802 break; 2803 case com.android.internal.R.styleable.View_duplicateParentState: 2804 if (a.getBoolean(attr, false)) { 2805 viewFlagValues |= DUPLICATE_PARENT_STATE; 2806 viewFlagMasks |= DUPLICATE_PARENT_STATE; 2807 } 2808 break; 2809 case com.android.internal.R.styleable.View_visibility: 2810 final int visibility = a.getInt(attr, 0); 2811 if (visibility != 0) { 2812 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 2813 viewFlagMasks |= VISIBILITY_MASK; 2814 } 2815 break; 2816 case com.android.internal.R.styleable.View_layoutDirection: 2817 // Clear any HORIZONTAL_DIRECTION flag already set 2818 viewFlagValues &= ~LAYOUT_DIRECTION_MASK; 2819 // Set the HORIZONTAL_DIRECTION flags depending on the value of the attribute 2820 final int layoutDirection = a.getInt(attr, -1); 2821 if (layoutDirection != -1) { 2822 viewFlagValues |= LAYOUT_DIRECTION_FLAGS[layoutDirection]; 2823 } else { 2824 // Set to default (LAYOUT_DIRECTION_INHERIT) 2825 viewFlagValues |= LAYOUT_DIRECTION_DEFAULT; 2826 } 2827 viewFlagMasks |= LAYOUT_DIRECTION_MASK; 2828 break; 2829 case com.android.internal.R.styleable.View_drawingCacheQuality: 2830 final int cacheQuality = a.getInt(attr, 0); 2831 if (cacheQuality != 0) { 2832 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 2833 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 2834 } 2835 break; 2836 case com.android.internal.R.styleable.View_contentDescription: 2837 mContentDescription = a.getString(attr); 2838 break; 2839 case com.android.internal.R.styleable.View_soundEffectsEnabled: 2840 if (!a.getBoolean(attr, true)) { 2841 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 2842 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 2843 } 2844 break; 2845 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 2846 if (!a.getBoolean(attr, true)) { 2847 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 2848 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 2849 } 2850 break; 2851 case R.styleable.View_scrollbars: 2852 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 2853 if (scrollbars != SCROLLBARS_NONE) { 2854 viewFlagValues |= scrollbars; 2855 viewFlagMasks |= SCROLLBARS_MASK; 2856 initializeScrollbars(a); 2857 } 2858 break; 2859 case R.styleable.View_fadingEdge: 2860 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 2861 if (fadingEdge != FADING_EDGE_NONE) { 2862 viewFlagValues |= fadingEdge; 2863 viewFlagMasks |= FADING_EDGE_MASK; 2864 initializeFadingEdge(a); 2865 } 2866 break; 2867 case R.styleable.View_scrollbarStyle: 2868 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 2869 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 2870 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 2871 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 2872 } 2873 break; 2874 case R.styleable.View_isScrollContainer: 2875 setScrollContainer = true; 2876 if (a.getBoolean(attr, false)) { 2877 setScrollContainer(true); 2878 } 2879 break; 2880 case com.android.internal.R.styleable.View_keepScreenOn: 2881 if (a.getBoolean(attr, false)) { 2882 viewFlagValues |= KEEP_SCREEN_ON; 2883 viewFlagMasks |= KEEP_SCREEN_ON; 2884 } 2885 break; 2886 case R.styleable.View_filterTouchesWhenObscured: 2887 if (a.getBoolean(attr, false)) { 2888 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 2889 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 2890 } 2891 break; 2892 case R.styleable.View_nextFocusLeft: 2893 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 2894 break; 2895 case R.styleable.View_nextFocusRight: 2896 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 2897 break; 2898 case R.styleable.View_nextFocusUp: 2899 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 2900 break; 2901 case R.styleable.View_nextFocusDown: 2902 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 2903 break; 2904 case R.styleable.View_nextFocusForward: 2905 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 2906 break; 2907 case R.styleable.View_minWidth: 2908 mMinWidth = a.getDimensionPixelSize(attr, 0); 2909 break; 2910 case R.styleable.View_minHeight: 2911 mMinHeight = a.getDimensionPixelSize(attr, 0); 2912 break; 2913 case R.styleable.View_onClick: 2914 if (context.isRestricted()) { 2915 throw new IllegalStateException("The android:onClick attribute cannot " 2916 + "be used within a restricted context"); 2917 } 2918 2919 final String handlerName = a.getString(attr); 2920 if (handlerName != null) { 2921 setOnClickListener(new OnClickListener() { 2922 private Method mHandler; 2923 2924 public void onClick(View v) { 2925 if (mHandler == null) { 2926 try { 2927 mHandler = getContext().getClass().getMethod(handlerName, 2928 View.class); 2929 } catch (NoSuchMethodException e) { 2930 int id = getId(); 2931 String idText = id == NO_ID ? "" : " with id '" 2932 + getContext().getResources().getResourceEntryName( 2933 id) + "'"; 2934 throw new IllegalStateException("Could not find a method " + 2935 handlerName + "(View) in the activity " 2936 + getContext().getClass() + " for onClick handler" 2937 + " on view " + View.this.getClass() + idText, e); 2938 } 2939 } 2940 2941 try { 2942 mHandler.invoke(getContext(), View.this); 2943 } catch (IllegalAccessException e) { 2944 throw new IllegalStateException("Could not execute non " 2945 + "public method of the activity", e); 2946 } catch (InvocationTargetException e) { 2947 throw new IllegalStateException("Could not execute " 2948 + "method of the activity", e); 2949 } 2950 } 2951 }); 2952 } 2953 break; 2954 case R.styleable.View_overScrollMode: 2955 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 2956 break; 2957 case R.styleable.View_verticalScrollbarPosition: 2958 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 2959 break; 2960 case R.styleable.View_layerType: 2961 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 2962 break; 2963 case R.styleable.View_textDirection: 2964 mTextDirection = a.getInt(attr, DEFAULT_TEXT_DIRECTION); 2965 break; 2966 } 2967 } 2968 2969 setOverScrollMode(overScrollMode); 2970 2971 if (background != null) { 2972 setBackgroundDrawable(background); 2973 } 2974 2975 mUserPaddingRelative = (startPadding >= 0 || endPadding >= 0); 2976 2977 // Cache user padding as we cannot fully resolve padding here (we dont have yet the resolved 2978 // layout direction). Those cached values will be used later during padding resolution. 2979 mUserPaddingStart = startPadding; 2980 mUserPaddingEnd = endPadding; 2981 2982 if (padding >= 0) { 2983 leftPadding = padding; 2984 topPadding = padding; 2985 rightPadding = padding; 2986 bottomPadding = padding; 2987 } 2988 2989 // If the user specified the padding (either with android:padding or 2990 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise 2991 // use the default padding or the padding from the background drawable 2992 // (stored at this point in mPadding*) 2993 setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft, 2994 topPadding >= 0 ? topPadding : mPaddingTop, 2995 rightPadding >= 0 ? rightPadding : mPaddingRight, 2996 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 2997 2998 if (viewFlagMasks != 0) { 2999 setFlags(viewFlagValues, viewFlagMasks); 3000 } 3001 3002 // Needs to be called after mViewFlags is set 3003 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3004 recomputePadding(); 3005 } 3006 3007 if (x != 0 || y != 0) { 3008 scrollTo(x, y); 3009 } 3010 3011 if (transformSet) { 3012 setTranslationX(tx); 3013 setTranslationY(ty); 3014 setRotation(rotation); 3015 setRotationX(rotationX); 3016 setRotationY(rotationY); 3017 setScaleX(sx); 3018 setScaleY(sy); 3019 } 3020 3021 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 3022 setScrollContainer(true); 3023 } 3024 3025 computeOpaqueFlags(); 3026 3027 a.recycle(); 3028 } 3029 3030 /** 3031 * Non-public constructor for use in testing 3032 */ 3033 View() { 3034 } 3035 3036 /** 3037 * <p> 3038 * Initializes the fading edges from a given set of styled attributes. This 3039 * method should be called by subclasses that need fading edges and when an 3040 * instance of these subclasses is created programmatically rather than 3041 * being inflated from XML. This method is automatically called when the XML 3042 * is inflated. 3043 * </p> 3044 * 3045 * @param a the styled attributes set to initialize the fading edges from 3046 */ 3047 protected void initializeFadingEdge(TypedArray a) { 3048 initScrollCache(); 3049 3050 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 3051 R.styleable.View_fadingEdgeLength, 3052 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 3053 } 3054 3055 /** 3056 * Returns the size of the vertical faded edges used to indicate that more 3057 * content in this view is visible. 3058 * 3059 * @return The size in pixels of the vertical faded edge or 0 if vertical 3060 * faded edges are not enabled for this view. 3061 * @attr ref android.R.styleable#View_fadingEdgeLength 3062 */ 3063 public int getVerticalFadingEdgeLength() { 3064 if (isVerticalFadingEdgeEnabled()) { 3065 ScrollabilityCache cache = mScrollCache; 3066 if (cache != null) { 3067 return cache.fadingEdgeLength; 3068 } 3069 } 3070 return 0; 3071 } 3072 3073 /** 3074 * Set the size of the faded edge used to indicate that more content in this 3075 * view is available. Will not change whether the fading edge is enabled; use 3076 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 3077 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 3078 * for the vertical or horizontal fading edges. 3079 * 3080 * @param length The size in pixels of the faded edge used to indicate that more 3081 * content in this view is visible. 3082 */ 3083 public void setFadingEdgeLength(int length) { 3084 initScrollCache(); 3085 mScrollCache.fadingEdgeLength = length; 3086 } 3087 3088 /** 3089 * Returns the size of the horizontal faded edges used to indicate that more 3090 * content in this view is visible. 3091 * 3092 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 3093 * faded edges are not enabled for this view. 3094 * @attr ref android.R.styleable#View_fadingEdgeLength 3095 */ 3096 public int getHorizontalFadingEdgeLength() { 3097 if (isHorizontalFadingEdgeEnabled()) { 3098 ScrollabilityCache cache = mScrollCache; 3099 if (cache != null) { 3100 return cache.fadingEdgeLength; 3101 } 3102 } 3103 return 0; 3104 } 3105 3106 /** 3107 * Returns the width of the vertical scrollbar. 3108 * 3109 * @return The width in pixels of the vertical scrollbar or 0 if there 3110 * is no vertical scrollbar. 3111 */ 3112 public int getVerticalScrollbarWidth() { 3113 ScrollabilityCache cache = mScrollCache; 3114 if (cache != null) { 3115 ScrollBarDrawable scrollBar = cache.scrollBar; 3116 if (scrollBar != null) { 3117 int size = scrollBar.getSize(true); 3118 if (size <= 0) { 3119 size = cache.scrollBarSize; 3120 } 3121 return size; 3122 } 3123 return 0; 3124 } 3125 return 0; 3126 } 3127 3128 /** 3129 * Returns the height of the horizontal scrollbar. 3130 * 3131 * @return The height in pixels of the horizontal scrollbar or 0 if 3132 * there is no horizontal scrollbar. 3133 */ 3134 protected int getHorizontalScrollbarHeight() { 3135 ScrollabilityCache cache = mScrollCache; 3136 if (cache != null) { 3137 ScrollBarDrawable scrollBar = cache.scrollBar; 3138 if (scrollBar != null) { 3139 int size = scrollBar.getSize(false); 3140 if (size <= 0) { 3141 size = cache.scrollBarSize; 3142 } 3143 return size; 3144 } 3145 return 0; 3146 } 3147 return 0; 3148 } 3149 3150 /** 3151 * <p> 3152 * Initializes the scrollbars from a given set of styled attributes. This 3153 * method should be called by subclasses that need scrollbars and when an 3154 * instance of these subclasses is created programmatically rather than 3155 * being inflated from XML. This method is automatically called when the XML 3156 * is inflated. 3157 * </p> 3158 * 3159 * @param a the styled attributes set to initialize the scrollbars from 3160 */ 3161 protected void initializeScrollbars(TypedArray a) { 3162 initScrollCache(); 3163 3164 final ScrollabilityCache scrollabilityCache = mScrollCache; 3165 3166 if (scrollabilityCache.scrollBar == null) { 3167 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 3168 } 3169 3170 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 3171 3172 if (!fadeScrollbars) { 3173 scrollabilityCache.state = ScrollabilityCache.ON; 3174 } 3175 scrollabilityCache.fadeScrollBars = fadeScrollbars; 3176 3177 3178 scrollabilityCache.scrollBarFadeDuration = a.getInt( 3179 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 3180 .getScrollBarFadeDuration()); 3181 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 3182 R.styleable.View_scrollbarDefaultDelayBeforeFade, 3183 ViewConfiguration.getScrollDefaultDelay()); 3184 3185 3186 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 3187 com.android.internal.R.styleable.View_scrollbarSize, 3188 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 3189 3190 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 3191 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 3192 3193 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 3194 if (thumb != null) { 3195 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 3196 } 3197 3198 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 3199 false); 3200 if (alwaysDraw) { 3201 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 3202 } 3203 3204 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 3205 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 3206 3207 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 3208 if (thumb != null) { 3209 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 3210 } 3211 3212 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 3213 false); 3214 if (alwaysDraw) { 3215 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 3216 } 3217 3218 // Re-apply user/background padding so that scrollbar(s) get added 3219 resolvePadding(); 3220 } 3221 3222 /** 3223 * <p> 3224 * Initalizes the scrollability cache if necessary. 3225 * </p> 3226 */ 3227 private void initScrollCache() { 3228 if (mScrollCache == null) { 3229 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 3230 } 3231 } 3232 3233 /** 3234 * Set the position of the vertical scroll bar. Should be one of 3235 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 3236 * {@link #SCROLLBAR_POSITION_RIGHT}. 3237 * 3238 * @param position Where the vertical scroll bar should be positioned. 3239 */ 3240 public void setVerticalScrollbarPosition(int position) { 3241 if (mVerticalScrollbarPosition != position) { 3242 mVerticalScrollbarPosition = position; 3243 computeOpaqueFlags(); 3244 resolvePadding(); 3245 } 3246 } 3247 3248 /** 3249 * @return The position where the vertical scroll bar will show, if applicable. 3250 * @see #setVerticalScrollbarPosition(int) 3251 */ 3252 public int getVerticalScrollbarPosition() { 3253 return mVerticalScrollbarPosition; 3254 } 3255 3256 /** 3257 * Register a callback to be invoked when focus of this view changed. 3258 * 3259 * @param l The callback that will run. 3260 */ 3261 public void setOnFocusChangeListener(OnFocusChangeListener l) { 3262 mOnFocusChangeListener = l; 3263 } 3264 3265 /** 3266 * Add a listener that will be called when the bounds of the view change due to 3267 * layout processing. 3268 * 3269 * @param listener The listener that will be called when layout bounds change. 3270 */ 3271 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 3272 if (mOnLayoutChangeListeners == null) { 3273 mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 3274 } 3275 mOnLayoutChangeListeners.add(listener); 3276 } 3277 3278 /** 3279 * Remove a listener for layout changes. 3280 * 3281 * @param listener The listener for layout bounds change. 3282 */ 3283 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 3284 if (mOnLayoutChangeListeners == null) { 3285 return; 3286 } 3287 mOnLayoutChangeListeners.remove(listener); 3288 } 3289 3290 /** 3291 * Add a listener for attach state changes. 3292 * 3293 * This listener will be called whenever this view is attached or detached 3294 * from a window. Remove the listener using 3295 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 3296 * 3297 * @param listener Listener to attach 3298 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 3299 */ 3300 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 3301 if (mOnAttachStateChangeListeners == null) { 3302 mOnAttachStateChangeListeners = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 3303 } 3304 mOnAttachStateChangeListeners.add(listener); 3305 } 3306 3307 /** 3308 * Remove a listener for attach state changes. The listener will receive no further 3309 * notification of window attach/detach events. 3310 * 3311 * @param listener Listener to remove 3312 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 3313 */ 3314 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 3315 if (mOnAttachStateChangeListeners == null) { 3316 return; 3317 } 3318 mOnAttachStateChangeListeners.remove(listener); 3319 } 3320 3321 /** 3322 * Returns the focus-change callback registered for this view. 3323 * 3324 * @return The callback, or null if one is not registered. 3325 */ 3326 public OnFocusChangeListener getOnFocusChangeListener() { 3327 return mOnFocusChangeListener; 3328 } 3329 3330 /** 3331 * Register a callback to be invoked when this view is clicked. If this view is not 3332 * clickable, it becomes clickable. 3333 * 3334 * @param l The callback that will run 3335 * 3336 * @see #setClickable(boolean) 3337 */ 3338 public void setOnClickListener(OnClickListener l) { 3339 if (!isClickable()) { 3340 setClickable(true); 3341 } 3342 mOnClickListener = l; 3343 } 3344 3345 /** 3346 * Register a callback to be invoked when this view is clicked and held. If this view is not 3347 * long clickable, it becomes long clickable. 3348 * 3349 * @param l The callback that will run 3350 * 3351 * @see #setLongClickable(boolean) 3352 */ 3353 public void setOnLongClickListener(OnLongClickListener l) { 3354 if (!isLongClickable()) { 3355 setLongClickable(true); 3356 } 3357 mOnLongClickListener = l; 3358 } 3359 3360 /** 3361 * Register a callback to be invoked when the context menu for this view is 3362 * being built. If this view is not long clickable, it becomes long clickable. 3363 * 3364 * @param l The callback that will run 3365 * 3366 */ 3367 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 3368 if (!isLongClickable()) { 3369 setLongClickable(true); 3370 } 3371 mOnCreateContextMenuListener = l; 3372 } 3373 3374 /** 3375 * Call this view's OnClickListener, if it is defined. 3376 * 3377 * @return True there was an assigned OnClickListener that was called, false 3378 * otherwise is returned. 3379 */ 3380 public boolean performClick() { 3381 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 3382 3383 if (mOnClickListener != null) { 3384 playSoundEffect(SoundEffectConstants.CLICK); 3385 mOnClickListener.onClick(this); 3386 return true; 3387 } 3388 3389 return false; 3390 } 3391 3392 /** 3393 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 3394 * OnLongClickListener did not consume the event. 3395 * 3396 * @return True if one of the above receivers consumed the event, false otherwise. 3397 */ 3398 public boolean performLongClick() { 3399 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 3400 3401 boolean handled = false; 3402 if (mOnLongClickListener != null) { 3403 handled = mOnLongClickListener.onLongClick(View.this); 3404 } 3405 if (!handled) { 3406 handled = showContextMenu(); 3407 } 3408 if (handled) { 3409 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 3410 } 3411 return handled; 3412 } 3413 3414 /** 3415 * Performs button-related actions during a touch down event. 3416 * 3417 * @param event The event. 3418 * @return True if the down was consumed. 3419 * 3420 * @hide 3421 */ 3422 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 3423 if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 3424 if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) { 3425 return true; 3426 } 3427 } 3428 return false; 3429 } 3430 3431 /** 3432 * Bring up the context menu for this view. 3433 * 3434 * @return Whether a context menu was displayed. 3435 */ 3436 public boolean showContextMenu() { 3437 return getParent().showContextMenuForChild(this); 3438 } 3439 3440 /** 3441 * Bring up the context menu for this view, referring to the item under the specified point. 3442 * 3443 * @param x The referenced x coordinate. 3444 * @param y The referenced y coordinate. 3445 * @param metaState The keyboard modifiers that were pressed. 3446 * @return Whether a context menu was displayed. 3447 * 3448 * @hide 3449 */ 3450 public boolean showContextMenu(float x, float y, int metaState) { 3451 return showContextMenu(); 3452 } 3453 3454 /** 3455 * Start an action mode. 3456 * 3457 * @param callback Callback that will control the lifecycle of the action mode 3458 * @return The new action mode if it is started, null otherwise 3459 * 3460 * @see ActionMode 3461 */ 3462 public ActionMode startActionMode(ActionMode.Callback callback) { 3463 return getParent().startActionModeForChild(this, callback); 3464 } 3465 3466 /** 3467 * Register a callback to be invoked when a key is pressed in this view. 3468 * @param l the key listener to attach to this view 3469 */ 3470 public void setOnKeyListener(OnKeyListener l) { 3471 mOnKeyListener = l; 3472 } 3473 3474 /** 3475 * Register a callback to be invoked when a touch event is sent to this view. 3476 * @param l the touch listener to attach to this view 3477 */ 3478 public void setOnTouchListener(OnTouchListener l) { 3479 mOnTouchListener = l; 3480 } 3481 3482 /** 3483 * Register a callback to be invoked when a generic motion event is sent to this view. 3484 * @param l the generic motion listener to attach to this view 3485 */ 3486 public void setOnGenericMotionListener(OnGenericMotionListener l) { 3487 mOnGenericMotionListener = l; 3488 } 3489 3490 /** 3491 * Register a callback to be invoked when a hover event is sent to this view. 3492 * @param l the hover listener to attach to this view 3493 */ 3494 public void setOnHoverListener(OnHoverListener l) { 3495 mOnHoverListener = l; 3496 } 3497 3498 /** 3499 * Register a drag event listener callback object for this View. The parameter is 3500 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 3501 * View, the system calls the 3502 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 3503 * @param l An implementation of {@link android.view.View.OnDragListener}. 3504 */ 3505 public void setOnDragListener(OnDragListener l) { 3506 mOnDragListener = l; 3507 } 3508 3509 /** 3510 * Give this view focus. This will cause 3511 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 3512 * 3513 * Note: this does not check whether this {@link View} should get focus, it just 3514 * gives it focus no matter what. It should only be called internally by framework 3515 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 3516 * 3517 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 3518 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 3519 * focus moved when requestFocus() is called. It may not always 3520 * apply, in which case use the default View.FOCUS_DOWN. 3521 * @param previouslyFocusedRect The rectangle of the view that had focus 3522 * prior in this View's coordinate system. 3523 */ 3524 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) { 3525 if (DBG) { 3526 System.out.println(this + " requestFocus()"); 3527 } 3528 3529 if ((mPrivateFlags & FOCUSED) == 0) { 3530 mPrivateFlags |= FOCUSED; 3531 3532 if (mParent != null) { 3533 mParent.requestChildFocus(this, this); 3534 } 3535 3536 onFocusChanged(true, direction, previouslyFocusedRect); 3537 refreshDrawableState(); 3538 } 3539 } 3540 3541 /** 3542 * Request that a rectangle of this view be visible on the screen, 3543 * scrolling if necessary just enough. 3544 * 3545 * <p>A View should call this if it maintains some notion of which part 3546 * of its content is interesting. For example, a text editing view 3547 * should call this when its cursor moves. 3548 * 3549 * @param rectangle The rectangle. 3550 * @return Whether any parent scrolled. 3551 */ 3552 public boolean requestRectangleOnScreen(Rect rectangle) { 3553 return requestRectangleOnScreen(rectangle, false); 3554 } 3555 3556 /** 3557 * Request that a rectangle of this view be visible on the screen, 3558 * scrolling if necessary just enough. 3559 * 3560 * <p>A View should call this if it maintains some notion of which part 3561 * of its content is interesting. For example, a text editing view 3562 * should call this when its cursor moves. 3563 * 3564 * <p>When <code>immediate</code> is set to true, scrolling will not be 3565 * animated. 3566 * 3567 * @param rectangle The rectangle. 3568 * @param immediate True to forbid animated scrolling, false otherwise 3569 * @return Whether any parent scrolled. 3570 */ 3571 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 3572 View child = this; 3573 ViewParent parent = mParent; 3574 boolean scrolled = false; 3575 while (parent != null) { 3576 scrolled |= parent.requestChildRectangleOnScreen(child, 3577 rectangle, immediate); 3578 3579 // offset rect so next call has the rectangle in the 3580 // coordinate system of its direct child. 3581 rectangle.offset(child.getLeft(), child.getTop()); 3582 rectangle.offset(-child.getScrollX(), -child.getScrollY()); 3583 3584 if (!(parent instanceof View)) { 3585 break; 3586 } 3587 3588 child = (View) parent; 3589 parent = child.getParent(); 3590 } 3591 return scrolled; 3592 } 3593 3594 /** 3595 * Called when this view wants to give up focus. This will cause 3596 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 3597 */ 3598 public void clearFocus() { 3599 if (DBG) { 3600 System.out.println(this + " clearFocus()"); 3601 } 3602 3603 if ((mPrivateFlags & FOCUSED) != 0) { 3604 mPrivateFlags &= ~FOCUSED; 3605 3606 if (mParent != null) { 3607 mParent.clearChildFocus(this); 3608 } 3609 3610 onFocusChanged(false, 0, null); 3611 refreshDrawableState(); 3612 } 3613 } 3614 3615 /** 3616 * Called to clear the focus of a view that is about to be removed. 3617 * Doesn't call clearChildFocus, which prevents this view from taking 3618 * focus again before it has been removed from the parent 3619 */ 3620 void clearFocusForRemoval() { 3621 if ((mPrivateFlags & FOCUSED) != 0) { 3622 mPrivateFlags &= ~FOCUSED; 3623 3624 onFocusChanged(false, 0, null); 3625 refreshDrawableState(); 3626 } 3627 } 3628 3629 /** 3630 * Called internally by the view system when a new view is getting focus. 3631 * This is what clears the old focus. 3632 */ 3633 void unFocus() { 3634 if (DBG) { 3635 System.out.println(this + " unFocus()"); 3636 } 3637 3638 if ((mPrivateFlags & FOCUSED) != 0) { 3639 mPrivateFlags &= ~FOCUSED; 3640 3641 onFocusChanged(false, 0, null); 3642 refreshDrawableState(); 3643 } 3644 } 3645 3646 /** 3647 * Returns true if this view has focus iteself, or is the ancestor of the 3648 * view that has focus. 3649 * 3650 * @return True if this view has or contains focus, false otherwise. 3651 */ 3652 @ViewDebug.ExportedProperty(category = "focus") 3653 public boolean hasFocus() { 3654 return (mPrivateFlags & FOCUSED) != 0; 3655 } 3656 3657 /** 3658 * Returns true if this view is focusable or if it contains a reachable View 3659 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 3660 * is a View whose parents do not block descendants focus. 3661 * 3662 * Only {@link #VISIBLE} views are considered focusable. 3663 * 3664 * @return True if the view is focusable or if the view contains a focusable 3665 * View, false otherwise. 3666 * 3667 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 3668 */ 3669 public boolean hasFocusable() { 3670 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 3671 } 3672 3673 /** 3674 * Called by the view system when the focus state of this view changes. 3675 * When the focus change event is caused by directional navigation, direction 3676 * and previouslyFocusedRect provide insight into where the focus is coming from. 3677 * When overriding, be sure to call up through to the super class so that 3678 * the standard focus handling will occur. 3679 * 3680 * @param gainFocus True if the View has focus; false otherwise. 3681 * @param direction The direction focus has moved when requestFocus() 3682 * is called to give this view focus. Values are 3683 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 3684 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 3685 * It may not always apply, in which case use the default. 3686 * @param previouslyFocusedRect The rectangle, in this view's coordinate 3687 * system, of the previously focused view. If applicable, this will be 3688 * passed in as finer grained information about where the focus is coming 3689 * from (in addition to direction). Will be <code>null</code> otherwise. 3690 */ 3691 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) { 3692 if (gainFocus) { 3693 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 3694 } 3695 3696 InputMethodManager imm = InputMethodManager.peekInstance(); 3697 if (!gainFocus) { 3698 if (isPressed()) { 3699 setPressed(false); 3700 } 3701 if (imm != null && mAttachInfo != null 3702 && mAttachInfo.mHasWindowFocus) { 3703 imm.focusOut(this); 3704 } 3705 onFocusLost(); 3706 } else if (imm != null && mAttachInfo != null 3707 && mAttachInfo.mHasWindowFocus) { 3708 imm.focusIn(this); 3709 } 3710 3711 invalidate(true); 3712 if (mOnFocusChangeListener != null) { 3713 mOnFocusChangeListener.onFocusChange(this, gainFocus); 3714 } 3715 3716 if (mAttachInfo != null) { 3717 mAttachInfo.mKeyDispatchState.reset(this); 3718 } 3719 } 3720 3721 /** 3722 * Sends an accessibility event of the given type. If accessiiblity is 3723 * not enabled this method has no effect. The default implementation calls 3724 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 3725 * to populate information about the event source (this View), then calls 3726 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 3727 * populate the text content of the event source including its descendants, 3728 * and last calls 3729 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 3730 * on its parent to resuest sending of the event to interested parties. 3731 * 3732 * @param eventType The type of the event to send. 3733 * 3734 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 3735 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 3736 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 3737 */ 3738 public void sendAccessibilityEvent(int eventType) { 3739 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 3740 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 3741 } 3742 } 3743 3744 /** 3745 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 3746 * takes as an argument an empty {@link AccessibilityEvent} and does not 3747 * perfrom a check whether accessibility is enabled. 3748 * 3749 * @param event The event to send. 3750 * 3751 * @see #sendAccessibilityEvent(int) 3752 */ 3753 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 3754 if (!isShown()) { 3755 return; 3756 } 3757 onInitializeAccessibilityEvent(event); 3758 dispatchPopulateAccessibilityEvent(event); 3759 // In the beginning we called #isShown(), so we know that getParent() is not null. 3760 getParent().requestSendAccessibilityEvent(this, event); 3761 } 3762 3763 /** 3764 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 3765 * to its children for adding their text content to the event. Note that the 3766 * event text is populated in a separate dispatch path since we add to the 3767 * event not only the text of the source but also the text of all its descendants. 3768 * </p> 3769 * A typical implementation will call 3770 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 3771 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 3772 * on each child. Override this method if custom population of the event text 3773 * content is required. 3774 * 3775 * @param event The event. 3776 * 3777 * @return True if the event population was completed. 3778 */ 3779 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 3780 onPopulateAccessibilityEvent(event); 3781 return false; 3782 } 3783 3784 /** 3785 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 3786 * giving a chance to this View to populate the accessibility event with its 3787 * text content. While the implementation is free to modify other event 3788 * attributes this should be performed in 3789 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 3790 * <p> 3791 * Example: Adding formatted date string to an accessibility event in addition 3792 * to the text added by the super implementation. 3793 * </p><p><pre><code> 3794 * public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 3795 * super.onPopulateAccessibilityEvent(event); 3796 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 3797 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 3798 * mCurrentDate.getTimeInMillis(), flags); 3799 * event.getText().add(selectedDateUtterance); 3800 * } 3801 * </code></pre></p> 3802 * 3803 * @param event The accessibility event which to populate. 3804 * 3805 * @see #sendAccessibilityEvent(int) 3806 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 3807 */ 3808 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 3809 } 3810 3811 /** 3812 * Initializes an {@link AccessibilityEvent} with information about the 3813 * the type of the event and this View which is the event source. In other 3814 * words, the source of an accessibility event is the view whose state 3815 * change triggered firing the event. 3816 * <p> 3817 * Example: Setting the password property of an event in addition 3818 * to properties set by the super implementation. 3819 * </p><p><pre><code> 3820 * public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 3821 * super.onInitializeAccessibilityEvent(event); 3822 * event.setPassword(true); 3823 * } 3824 * </code></pre></p> 3825 * @param event The event to initialeze. 3826 * 3827 * @see #sendAccessibilityEvent(int) 3828 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 3829 */ 3830 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 3831 event.setSource(this); 3832 event.setClassName(getClass().getName()); 3833 event.setPackageName(getContext().getPackageName()); 3834 event.setEnabled(isEnabled()); 3835 event.setContentDescription(mContentDescription); 3836 3837 final int eventType = event.getEventType(); 3838 switch (eventType) { 3839 case AccessibilityEvent.TYPE_VIEW_FOCUSED: { 3840 if (mAttachInfo != null) { 3841 ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList; 3842 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, 3843 FOCUSABLES_ALL); 3844 event.setItemCount(focusablesTempList.size()); 3845 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 3846 focusablesTempList.clear(); 3847 } 3848 } break; 3849 case AccessibilityEvent.TYPE_VIEW_SCROLLED: { 3850 event.setScrollX(mScrollX); 3851 event.setScrollY(mScrollY); 3852 event.setItemCount(getHeight()); 3853 } break; 3854 } 3855 } 3856 3857 /** 3858 * Returns an {@link AccessibilityNodeInfo} representing this view from the 3859 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 3860 * This method is responsible for obtaining an accessibility node info from a 3861 * pool of reusable instances and calling 3862 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 3863 * initialize the former. 3864 * <p> 3865 * Note: The client is responsible for recycling the obtained instance by calling 3866 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 3867 * </p> 3868 * @return A populated {@link AccessibilityNodeInfo}. 3869 * 3870 * @see AccessibilityNodeInfo 3871 */ 3872 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 3873 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 3874 onInitializeAccessibilityNodeInfo(info); 3875 return info; 3876 } 3877 3878 /** 3879 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 3880 * The base implementation sets: 3881 * <ul> 3882 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 3883 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 3884 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 3885 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 3886 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 3887 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 3888 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 3889 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 3890 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 3891 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 3892 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 3893 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 3894 * </ul> 3895 * <p> 3896 * Subclasses should override this method, call the super implementation, 3897 * and set additional attributes. 3898 * </p> 3899 * @param info The instance to initialize. 3900 */ 3901 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 3902 Rect bounds = mAttachInfo.mTmpInvalRect; 3903 getDrawingRect(bounds); 3904 info.setBoundsInParent(bounds); 3905 3906 int[] locationOnScreen = mAttachInfo.mInvalidateChildLocation; 3907 getLocationOnScreen(locationOnScreen); 3908 bounds.offset(locationOnScreen[0], locationOnScreen[1]); 3909 info.setBoundsInScreen(bounds); 3910 3911 ViewParent parent = getParent(); 3912 if (parent instanceof View) { 3913 View parentView = (View) parent; 3914 info.setParent(parentView); 3915 } 3916 3917 info.setPackageName(mContext.getPackageName()); 3918 info.setClassName(getClass().getName()); 3919 info.setContentDescription(getContentDescription()); 3920 3921 info.setEnabled(isEnabled()); 3922 info.setClickable(isClickable()); 3923 info.setFocusable(isFocusable()); 3924 info.setFocused(isFocused()); 3925 info.setSelected(isSelected()); 3926 info.setLongClickable(isLongClickable()); 3927 3928 // TODO: These make sense only if we are in an AdapterView but all 3929 // views can be selected. Maybe from accessiiblity perspective 3930 // we should report as selectable view in an AdapterView. 3931 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 3932 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 3933 3934 if (isFocusable()) { 3935 if (isFocused()) { 3936 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 3937 } else { 3938 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 3939 } 3940 } 3941 } 3942 3943 /** 3944 * Gets the unique identifier of this view on the screen for accessibility purposes. 3945 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 3946 * 3947 * @return The view accessibility id. 3948 * 3949 * @hide 3950 */ 3951 public int getAccessibilityViewId() { 3952 if (mAccessibilityViewId == NO_ID) { 3953 mAccessibilityViewId = sNextAccessibilityViewId++; 3954 } 3955 return mAccessibilityViewId; 3956 } 3957 3958 /** 3959 * Gets the unique identifier of the window in which this View reseides. 3960 * 3961 * @return The window accessibility id. 3962 * 3963 * @hide 3964 */ 3965 public int getAccessibilityWindowId() { 3966 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID; 3967 } 3968 3969 /** 3970 * Gets the {@link View} description. It briefly describes the view and is 3971 * primarily used for accessibility support. Set this property to enable 3972 * better accessibility support for your application. This is especially 3973 * true for views that do not have textual representation (For example, 3974 * ImageButton). 3975 * 3976 * @return The content descriptiopn. 3977 * 3978 * @attr ref android.R.styleable#View_contentDescription 3979 */ 3980 public CharSequence getContentDescription() { 3981 return mContentDescription; 3982 } 3983 3984 /** 3985 * Sets the {@link View} description. It briefly describes the view and is 3986 * primarily used for accessibility support. Set this property to enable 3987 * better accessibility support for your application. This is especially 3988 * true for views that do not have textual representation (For example, 3989 * ImageButton). 3990 * 3991 * @param contentDescription The content description. 3992 * 3993 * @attr ref android.R.styleable#View_contentDescription 3994 */ 3995 public void setContentDescription(CharSequence contentDescription) { 3996 mContentDescription = contentDescription; 3997 } 3998 3999 /** 4000 * Invoked whenever this view loses focus, either by losing window focus or by losing 4001 * focus within its window. This method can be used to clear any state tied to the 4002 * focus. For instance, if a button is held pressed with the trackball and the window 4003 * loses focus, this method can be used to cancel the press. 4004 * 4005 * Subclasses of View overriding this method should always call super.onFocusLost(). 4006 * 4007 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 4008 * @see #onWindowFocusChanged(boolean) 4009 * 4010 * @hide pending API council approval 4011 */ 4012 protected void onFocusLost() { 4013 resetPressedState(); 4014 } 4015 4016 private void resetPressedState() { 4017 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 4018 return; 4019 } 4020 4021 if (isPressed()) { 4022 setPressed(false); 4023 4024 if (!mHasPerformedLongPress) { 4025 removeLongPressCallback(); 4026 } 4027 } 4028 } 4029 4030 /** 4031 * Returns true if this view has focus 4032 * 4033 * @return True if this view has focus, false otherwise. 4034 */ 4035 @ViewDebug.ExportedProperty(category = "focus") 4036 public boolean isFocused() { 4037 return (mPrivateFlags & FOCUSED) != 0; 4038 } 4039 4040 /** 4041 * Find the view in the hierarchy rooted at this view that currently has 4042 * focus. 4043 * 4044 * @return The view that currently has focus, or null if no focused view can 4045 * be found. 4046 */ 4047 public View findFocus() { 4048 return (mPrivateFlags & FOCUSED) != 0 ? this : null; 4049 } 4050 4051 /** 4052 * Change whether this view is one of the set of scrollable containers in 4053 * its window. This will be used to determine whether the window can 4054 * resize or must pan when a soft input area is open -- scrollable 4055 * containers allow the window to use resize mode since the container 4056 * will appropriately shrink. 4057 */ 4058 public void setScrollContainer(boolean isScrollContainer) { 4059 if (isScrollContainer) { 4060 if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) { 4061 mAttachInfo.mScrollContainers.add(this); 4062 mPrivateFlags |= SCROLL_CONTAINER_ADDED; 4063 } 4064 mPrivateFlags |= SCROLL_CONTAINER; 4065 } else { 4066 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) { 4067 mAttachInfo.mScrollContainers.remove(this); 4068 } 4069 mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED); 4070 } 4071 } 4072 4073 /** 4074 * Returns the quality of the drawing cache. 4075 * 4076 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 4077 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 4078 * 4079 * @see #setDrawingCacheQuality(int) 4080 * @see #setDrawingCacheEnabled(boolean) 4081 * @see #isDrawingCacheEnabled() 4082 * 4083 * @attr ref android.R.styleable#View_drawingCacheQuality 4084 */ 4085 public int getDrawingCacheQuality() { 4086 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 4087 } 4088 4089 /** 4090 * Set the drawing cache quality of this view. This value is used only when the 4091 * drawing cache is enabled 4092 * 4093 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 4094 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 4095 * 4096 * @see #getDrawingCacheQuality() 4097 * @see #setDrawingCacheEnabled(boolean) 4098 * @see #isDrawingCacheEnabled() 4099 * 4100 * @attr ref android.R.styleable#View_drawingCacheQuality 4101 */ 4102 public void setDrawingCacheQuality(int quality) { 4103 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 4104 } 4105 4106 /** 4107 * Returns whether the screen should remain on, corresponding to the current 4108 * value of {@link #KEEP_SCREEN_ON}. 4109 * 4110 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 4111 * 4112 * @see #setKeepScreenOn(boolean) 4113 * 4114 * @attr ref android.R.styleable#View_keepScreenOn 4115 */ 4116 public boolean getKeepScreenOn() { 4117 return (mViewFlags & KEEP_SCREEN_ON) != 0; 4118 } 4119 4120 /** 4121 * Controls whether the screen should remain on, modifying the 4122 * value of {@link #KEEP_SCREEN_ON}. 4123 * 4124 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 4125 * 4126 * @see #getKeepScreenOn() 4127 * 4128 * @attr ref android.R.styleable#View_keepScreenOn 4129 */ 4130 public void setKeepScreenOn(boolean keepScreenOn) { 4131 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 4132 } 4133 4134 /** 4135 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 4136 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4137 * 4138 * @attr ref android.R.styleable#View_nextFocusLeft 4139 */ 4140 public int getNextFocusLeftId() { 4141 return mNextFocusLeftId; 4142 } 4143 4144 /** 4145 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 4146 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 4147 * decide automatically. 4148 * 4149 * @attr ref android.R.styleable#View_nextFocusLeft 4150 */ 4151 public void setNextFocusLeftId(int nextFocusLeftId) { 4152 mNextFocusLeftId = nextFocusLeftId; 4153 } 4154 4155 /** 4156 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 4157 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4158 * 4159 * @attr ref android.R.styleable#View_nextFocusRight 4160 */ 4161 public int getNextFocusRightId() { 4162 return mNextFocusRightId; 4163 } 4164 4165 /** 4166 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 4167 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 4168 * decide automatically. 4169 * 4170 * @attr ref android.R.styleable#View_nextFocusRight 4171 */ 4172 public void setNextFocusRightId(int nextFocusRightId) { 4173 mNextFocusRightId = nextFocusRightId; 4174 } 4175 4176 /** 4177 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 4178 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4179 * 4180 * @attr ref android.R.styleable#View_nextFocusUp 4181 */ 4182 public int getNextFocusUpId() { 4183 return mNextFocusUpId; 4184 } 4185 4186 /** 4187 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 4188 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 4189 * decide automatically. 4190 * 4191 * @attr ref android.R.styleable#View_nextFocusUp 4192 */ 4193 public void setNextFocusUpId(int nextFocusUpId) { 4194 mNextFocusUpId = nextFocusUpId; 4195 } 4196 4197 /** 4198 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 4199 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4200 * 4201 * @attr ref android.R.styleable#View_nextFocusDown 4202 */ 4203 public int getNextFocusDownId() { 4204 return mNextFocusDownId; 4205 } 4206 4207 /** 4208 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 4209 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 4210 * decide automatically. 4211 * 4212 * @attr ref android.R.styleable#View_nextFocusDown 4213 */ 4214 public void setNextFocusDownId(int nextFocusDownId) { 4215 mNextFocusDownId = nextFocusDownId; 4216 } 4217 4218 /** 4219 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 4220 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4221 * 4222 * @attr ref android.R.styleable#View_nextFocusForward 4223 */ 4224 public int getNextFocusForwardId() { 4225 return mNextFocusForwardId; 4226 } 4227 4228 /** 4229 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 4230 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 4231 * decide automatically. 4232 * 4233 * @attr ref android.R.styleable#View_nextFocusForward 4234 */ 4235 public void setNextFocusForwardId(int nextFocusForwardId) { 4236 mNextFocusForwardId = nextFocusForwardId; 4237 } 4238 4239 /** 4240 * Returns the visibility of this view and all of its ancestors 4241 * 4242 * @return True if this view and all of its ancestors are {@link #VISIBLE} 4243 */ 4244 public boolean isShown() { 4245 View current = this; 4246 //noinspection ConstantConditions 4247 do { 4248 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 4249 return false; 4250 } 4251 ViewParent parent = current.mParent; 4252 if (parent == null) { 4253 return false; // We are not attached to the view root 4254 } 4255 if (!(parent instanceof View)) { 4256 return true; 4257 } 4258 current = (View) parent; 4259 } while (current != null); 4260 4261 return false; 4262 } 4263 4264 /** 4265 * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag 4266 * is set 4267 * 4268 * @param insets Insets for system windows 4269 * 4270 * @return True if this view applied the insets, false otherwise 4271 */ 4272 protected boolean fitSystemWindows(Rect insets) { 4273 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 4274 mPaddingLeft = insets.left; 4275 mPaddingTop = insets.top; 4276 mPaddingRight = insets.right; 4277 mPaddingBottom = insets.bottom; 4278 requestLayout(); 4279 return true; 4280 } 4281 return false; 4282 } 4283 4284 /** 4285 * Returns the visibility status for this view. 4286 * 4287 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 4288 * @attr ref android.R.styleable#View_visibility 4289 */ 4290 @ViewDebug.ExportedProperty(mapping = { 4291 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 4292 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 4293 @ViewDebug.IntToString(from = GONE, to = "GONE") 4294 }) 4295 public int getVisibility() { 4296 return mViewFlags & VISIBILITY_MASK; 4297 } 4298 4299 /** 4300 * Set the enabled state of this view. 4301 * 4302 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 4303 * @attr ref android.R.styleable#View_visibility 4304 */ 4305 @RemotableViewMethod 4306 public void setVisibility(int visibility) { 4307 setFlags(visibility, VISIBILITY_MASK); 4308 if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false); 4309 } 4310 4311 /** 4312 * Returns the enabled status for this view. The interpretation of the 4313 * enabled state varies by subclass. 4314 * 4315 * @return True if this view is enabled, false otherwise. 4316 */ 4317 @ViewDebug.ExportedProperty 4318 public boolean isEnabled() { 4319 return (mViewFlags & ENABLED_MASK) == ENABLED; 4320 } 4321 4322 /** 4323 * Set the enabled state of this view. The interpretation of the enabled 4324 * state varies by subclass. 4325 * 4326 * @param enabled True if this view is enabled, false otherwise. 4327 */ 4328 @RemotableViewMethod 4329 public void setEnabled(boolean enabled) { 4330 if (enabled == isEnabled()) return; 4331 4332 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 4333 4334 /* 4335 * The View most likely has to change its appearance, so refresh 4336 * the drawable state. 4337 */ 4338 refreshDrawableState(); 4339 4340 // Invalidate too, since the default behavior for views is to be 4341 // be drawn at 50% alpha rather than to change the drawable. 4342 invalidate(true); 4343 } 4344 4345 /** 4346 * Set whether this view can receive the focus. 4347 * 4348 * Setting this to false will also ensure that this view is not focusable 4349 * in touch mode. 4350 * 4351 * @param focusable If true, this view can receive the focus. 4352 * 4353 * @see #setFocusableInTouchMode(boolean) 4354 * @attr ref android.R.styleable#View_focusable 4355 */ 4356 public void setFocusable(boolean focusable) { 4357 if (!focusable) { 4358 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 4359 } 4360 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 4361 } 4362 4363 /** 4364 * Set whether this view can receive focus while in touch mode. 4365 * 4366 * Setting this to true will also ensure that this view is focusable. 4367 * 4368 * @param focusableInTouchMode If true, this view can receive the focus while 4369 * in touch mode. 4370 * 4371 * @see #setFocusable(boolean) 4372 * @attr ref android.R.styleable#View_focusableInTouchMode 4373 */ 4374 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 4375 // Focusable in touch mode should always be set before the focusable flag 4376 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 4377 // which, in touch mode, will not successfully request focus on this view 4378 // because the focusable in touch mode flag is not set 4379 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 4380 if (focusableInTouchMode) { 4381 setFlags(FOCUSABLE, FOCUSABLE_MASK); 4382 } 4383 } 4384 4385 /** 4386 * Set whether this view should have sound effects enabled for events such as 4387 * clicking and touching. 4388 * 4389 * <p>You may wish to disable sound effects for a view if you already play sounds, 4390 * for instance, a dial key that plays dtmf tones. 4391 * 4392 * @param soundEffectsEnabled whether sound effects are enabled for this view. 4393 * @see #isSoundEffectsEnabled() 4394 * @see #playSoundEffect(int) 4395 * @attr ref android.R.styleable#View_soundEffectsEnabled 4396 */ 4397 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 4398 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 4399 } 4400 4401 /** 4402 * @return whether this view should have sound effects enabled for events such as 4403 * clicking and touching. 4404 * 4405 * @see #setSoundEffectsEnabled(boolean) 4406 * @see #playSoundEffect(int) 4407 * @attr ref android.R.styleable#View_soundEffectsEnabled 4408 */ 4409 @ViewDebug.ExportedProperty 4410 public boolean isSoundEffectsEnabled() { 4411 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 4412 } 4413 4414 /** 4415 * Set whether this view should have haptic feedback for events such as 4416 * long presses. 4417 * 4418 * <p>You may wish to disable haptic feedback if your view already controls 4419 * its own haptic feedback. 4420 * 4421 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 4422 * @see #isHapticFeedbackEnabled() 4423 * @see #performHapticFeedback(int) 4424 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 4425 */ 4426 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 4427 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 4428 } 4429 4430 /** 4431 * @return whether this view should have haptic feedback enabled for events 4432 * long presses. 4433 * 4434 * @see #setHapticFeedbackEnabled(boolean) 4435 * @see #performHapticFeedback(int) 4436 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 4437 */ 4438 @ViewDebug.ExportedProperty 4439 public boolean isHapticFeedbackEnabled() { 4440 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 4441 } 4442 4443 /** 4444 * Returns the layout direction for this view. 4445 * 4446 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 4447 * {@link #LAYOUT_DIRECTION_RTL}, 4448 * {@link #LAYOUT_DIRECTION_INHERIT} or 4449 * {@link #LAYOUT_DIRECTION_LOCALE}. 4450 * @attr ref android.R.styleable#View_layoutDirection 4451 * 4452 * @hide 4453 */ 4454 @ViewDebug.ExportedProperty(category = "layout", mapping = { 4455 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 4456 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 4457 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 4458 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 4459 }) 4460 public int getLayoutDirection() { 4461 return mViewFlags & LAYOUT_DIRECTION_MASK; 4462 } 4463 4464 /** 4465 * Set the layout direction for this view. This will propagate a reset of layout direction 4466 * resolution to the view's children and resolve layout direction for this view. 4467 * 4468 * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR}, 4469 * {@link #LAYOUT_DIRECTION_RTL}, 4470 * {@link #LAYOUT_DIRECTION_INHERIT} or 4471 * {@link #LAYOUT_DIRECTION_LOCALE}. 4472 * 4473 * @attr ref android.R.styleable#View_layoutDirection 4474 * 4475 * @hide 4476 */ 4477 @RemotableViewMethod 4478 public void setLayoutDirection(int layoutDirection) { 4479 if (getLayoutDirection() != layoutDirection) { 4480 resetResolvedLayoutDirection(); 4481 // Setting the flag will also request a layout. 4482 setFlags(layoutDirection, LAYOUT_DIRECTION_MASK); 4483 } 4484 } 4485 4486 /** 4487 * Returns the resolved layout direction for this view. 4488 * 4489 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 4490 * {@link #LAYOUT_DIRECTION_LTR} id the layout direction is not RTL. 4491 * 4492 * @hide 4493 */ 4494 @ViewDebug.ExportedProperty(category = "layout", mapping = { 4495 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 4496 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 4497 }) 4498 public int getResolvedLayoutDirection() { 4499 resolveLayoutDirectionIfNeeded(); 4500 return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ? 4501 LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 4502 } 4503 4504 /** 4505 * <p>Indicates whether or not this view's layout is right-to-left. This is resolved from 4506 * layout attribute and/or the inherited value from the parent.</p> 4507 * 4508 * @return true if the layout is right-to-left. 4509 * 4510 * @hide 4511 */ 4512 @ViewDebug.ExportedProperty(category = "layout") 4513 public boolean isLayoutRtl() { 4514 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL); 4515 } 4516 4517 /** 4518 * If this view doesn't do any drawing on its own, set this flag to 4519 * allow further optimizations. By default, this flag is not set on 4520 * View, but could be set on some View subclasses such as ViewGroup. 4521 * 4522 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 4523 * you should clear this flag. 4524 * 4525 * @param willNotDraw whether or not this View draw on its own 4526 */ 4527 public void setWillNotDraw(boolean willNotDraw) { 4528 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 4529 } 4530 4531 /** 4532 * Returns whether or not this View draws on its own. 4533 * 4534 * @return true if this view has nothing to draw, false otherwise 4535 */ 4536 @ViewDebug.ExportedProperty(category = "drawing") 4537 public boolean willNotDraw() { 4538 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 4539 } 4540 4541 /** 4542 * When a View's drawing cache is enabled, drawing is redirected to an 4543 * offscreen bitmap. Some views, like an ImageView, must be able to 4544 * bypass this mechanism if they already draw a single bitmap, to avoid 4545 * unnecessary usage of the memory. 4546 * 4547 * @param willNotCacheDrawing true if this view does not cache its 4548 * drawing, false otherwise 4549 */ 4550 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 4551 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 4552 } 4553 4554 /** 4555 * Returns whether or not this View can cache its drawing or not. 4556 * 4557 * @return true if this view does not cache its drawing, false otherwise 4558 */ 4559 @ViewDebug.ExportedProperty(category = "drawing") 4560 public boolean willNotCacheDrawing() { 4561 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 4562 } 4563 4564 /** 4565 * Indicates whether this view reacts to click events or not. 4566 * 4567 * @return true if the view is clickable, false otherwise 4568 * 4569 * @see #setClickable(boolean) 4570 * @attr ref android.R.styleable#View_clickable 4571 */ 4572 @ViewDebug.ExportedProperty 4573 public boolean isClickable() { 4574 return (mViewFlags & CLICKABLE) == CLICKABLE; 4575 } 4576 4577 /** 4578 * Enables or disables click events for this view. When a view 4579 * is clickable it will change its state to "pressed" on every click. 4580 * Subclasses should set the view clickable to visually react to 4581 * user's clicks. 4582 * 4583 * @param clickable true to make the view clickable, false otherwise 4584 * 4585 * @see #isClickable() 4586 * @attr ref android.R.styleable#View_clickable 4587 */ 4588 public void setClickable(boolean clickable) { 4589 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 4590 } 4591 4592 /** 4593 * Indicates whether this view reacts to long click events or not. 4594 * 4595 * @return true if the view is long clickable, false otherwise 4596 * 4597 * @see #setLongClickable(boolean) 4598 * @attr ref android.R.styleable#View_longClickable 4599 */ 4600 public boolean isLongClickable() { 4601 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 4602 } 4603 4604 /** 4605 * Enables or disables long click events for this view. When a view is long 4606 * clickable it reacts to the user holding down the button for a longer 4607 * duration than a tap. This event can either launch the listener or a 4608 * context menu. 4609 * 4610 * @param longClickable true to make the view long clickable, false otherwise 4611 * @see #isLongClickable() 4612 * @attr ref android.R.styleable#View_longClickable 4613 */ 4614 public void setLongClickable(boolean longClickable) { 4615 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 4616 } 4617 4618 /** 4619 * Sets the pressed state for this view. 4620 * 4621 * @see #isClickable() 4622 * @see #setClickable(boolean) 4623 * 4624 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 4625 * the View's internal state from a previously set "pressed" state. 4626 */ 4627 public void setPressed(boolean pressed) { 4628 if (pressed) { 4629 mPrivateFlags |= PRESSED; 4630 } else { 4631 mPrivateFlags &= ~PRESSED; 4632 } 4633 refreshDrawableState(); 4634 dispatchSetPressed(pressed); 4635 } 4636 4637 /** 4638 * Dispatch setPressed to all of this View's children. 4639 * 4640 * @see #setPressed(boolean) 4641 * 4642 * @param pressed The new pressed state 4643 */ 4644 protected void dispatchSetPressed(boolean pressed) { 4645 } 4646 4647 /** 4648 * Indicates whether the view is currently in pressed state. Unless 4649 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 4650 * the pressed state. 4651 * 4652 * @see #setPressed(boolean) 4653 * @see #isClickable() 4654 * @see #setClickable(boolean) 4655 * 4656 * @return true if the view is currently pressed, false otherwise 4657 */ 4658 public boolean isPressed() { 4659 return (mPrivateFlags & PRESSED) == PRESSED; 4660 } 4661 4662 /** 4663 * Indicates whether this view will save its state (that is, 4664 * whether its {@link #onSaveInstanceState} method will be called). 4665 * 4666 * @return Returns true if the view state saving is enabled, else false. 4667 * 4668 * @see #setSaveEnabled(boolean) 4669 * @attr ref android.R.styleable#View_saveEnabled 4670 */ 4671 public boolean isSaveEnabled() { 4672 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 4673 } 4674 4675 /** 4676 * Controls whether the saving of this view's state is 4677 * enabled (that is, whether its {@link #onSaveInstanceState} method 4678 * will be called). Note that even if freezing is enabled, the 4679 * view still must have an id assigned to it (via {@link #setId(int)}) 4680 * for its state to be saved. This flag can only disable the 4681 * saving of this view; any child views may still have their state saved. 4682 * 4683 * @param enabled Set to false to <em>disable</em> state saving, or true 4684 * (the default) to allow it. 4685 * 4686 * @see #isSaveEnabled() 4687 * @see #setId(int) 4688 * @see #onSaveInstanceState() 4689 * @attr ref android.R.styleable#View_saveEnabled 4690 */ 4691 public void setSaveEnabled(boolean enabled) { 4692 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 4693 } 4694 4695 /** 4696 * Gets whether the framework should discard touches when the view's 4697 * window is obscured by another visible window. 4698 * Refer to the {@link View} security documentation for more details. 4699 * 4700 * @return True if touch filtering is enabled. 4701 * 4702 * @see #setFilterTouchesWhenObscured(boolean) 4703 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 4704 */ 4705 @ViewDebug.ExportedProperty 4706 public boolean getFilterTouchesWhenObscured() { 4707 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 4708 } 4709 4710 /** 4711 * Sets whether the framework should discard touches when the view's 4712 * window is obscured by another visible window. 4713 * Refer to the {@link View} security documentation for more details. 4714 * 4715 * @param enabled True if touch filtering should be enabled. 4716 * 4717 * @see #getFilterTouchesWhenObscured 4718 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 4719 */ 4720 public void setFilterTouchesWhenObscured(boolean enabled) { 4721 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED, 4722 FILTER_TOUCHES_WHEN_OBSCURED); 4723 } 4724 4725 /** 4726 * Indicates whether the entire hierarchy under this view will save its 4727 * state when a state saving traversal occurs from its parent. The default 4728 * is true; if false, these views will not be saved unless 4729 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 4730 * 4731 * @return Returns true if the view state saving from parent is enabled, else false. 4732 * 4733 * @see #setSaveFromParentEnabled(boolean) 4734 */ 4735 public boolean isSaveFromParentEnabled() { 4736 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 4737 } 4738 4739 /** 4740 * Controls whether the entire hierarchy under this view will save its 4741 * state when a state saving traversal occurs from its parent. The default 4742 * is true; if false, these views will not be saved unless 4743 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 4744 * 4745 * @param enabled Set to false to <em>disable</em> state saving, or true 4746 * (the default) to allow it. 4747 * 4748 * @see #isSaveFromParentEnabled() 4749 * @see #setId(int) 4750 * @see #onSaveInstanceState() 4751 */ 4752 public void setSaveFromParentEnabled(boolean enabled) { 4753 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 4754 } 4755 4756 4757 /** 4758 * Returns whether this View is able to take focus. 4759 * 4760 * @return True if this view can take focus, or false otherwise. 4761 * @attr ref android.R.styleable#View_focusable 4762 */ 4763 @ViewDebug.ExportedProperty(category = "focus") 4764 public final boolean isFocusable() { 4765 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 4766 } 4767 4768 /** 4769 * When a view is focusable, it may not want to take focus when in touch mode. 4770 * For example, a button would like focus when the user is navigating via a D-pad 4771 * so that the user can click on it, but once the user starts touching the screen, 4772 * the button shouldn't take focus 4773 * @return Whether the view is focusable in touch mode. 4774 * @attr ref android.R.styleable#View_focusableInTouchMode 4775 */ 4776 @ViewDebug.ExportedProperty 4777 public final boolean isFocusableInTouchMode() { 4778 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 4779 } 4780 4781 /** 4782 * Find the nearest view in the specified direction that can take focus. 4783 * This does not actually give focus to that view. 4784 * 4785 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 4786 * 4787 * @return The nearest focusable in the specified direction, or null if none 4788 * can be found. 4789 */ 4790 public View focusSearch(int direction) { 4791 if (mParent != null) { 4792 return mParent.focusSearch(this, direction); 4793 } else { 4794 return null; 4795 } 4796 } 4797 4798 /** 4799 * This method is the last chance for the focused view and its ancestors to 4800 * respond to an arrow key. This is called when the focused view did not 4801 * consume the key internally, nor could the view system find a new view in 4802 * the requested direction to give focus to. 4803 * 4804 * @param focused The currently focused view. 4805 * @param direction The direction focus wants to move. One of FOCUS_UP, 4806 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 4807 * @return True if the this view consumed this unhandled move. 4808 */ 4809 public boolean dispatchUnhandledMove(View focused, int direction) { 4810 return false; 4811 } 4812 4813 /** 4814 * If a user manually specified the next view id for a particular direction, 4815 * use the root to look up the view. 4816 * @param root The root view of the hierarchy containing this view. 4817 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 4818 * or FOCUS_BACKWARD. 4819 * @return The user specified next view, or null if there is none. 4820 */ 4821 View findUserSetNextFocus(View root, int direction) { 4822 switch (direction) { 4823 case FOCUS_LEFT: 4824 if (mNextFocusLeftId == View.NO_ID) return null; 4825 return findViewShouldExist(root, mNextFocusLeftId); 4826 case FOCUS_RIGHT: 4827 if (mNextFocusRightId == View.NO_ID) return null; 4828 return findViewShouldExist(root, mNextFocusRightId); 4829 case FOCUS_UP: 4830 if (mNextFocusUpId == View.NO_ID) return null; 4831 return findViewShouldExist(root, mNextFocusUpId); 4832 case FOCUS_DOWN: 4833 if (mNextFocusDownId == View.NO_ID) return null; 4834 return findViewShouldExist(root, mNextFocusDownId); 4835 case FOCUS_FORWARD: 4836 if (mNextFocusForwardId == View.NO_ID) return null; 4837 return findViewShouldExist(root, mNextFocusForwardId); 4838 case FOCUS_BACKWARD: { 4839 final int id = mID; 4840 return root.findViewByPredicate(new Predicate<View>() { 4841 @Override 4842 public boolean apply(View t) { 4843 return t.mNextFocusForwardId == id; 4844 } 4845 }); 4846 } 4847 } 4848 return null; 4849 } 4850 4851 private static View findViewShouldExist(View root, int childViewId) { 4852 View result = root.findViewById(childViewId); 4853 if (result == null) { 4854 Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified " 4855 + "by user for id " + childViewId); 4856 } 4857 return result; 4858 } 4859 4860 /** 4861 * Find and return all focusable views that are descendants of this view, 4862 * possibly including this view if it is focusable itself. 4863 * 4864 * @param direction The direction of the focus 4865 * @return A list of focusable views 4866 */ 4867 public ArrayList<View> getFocusables(int direction) { 4868 ArrayList<View> result = new ArrayList<View>(24); 4869 addFocusables(result, direction); 4870 return result; 4871 } 4872 4873 /** 4874 * Add any focusable views that are descendants of this view (possibly 4875 * including this view if it is focusable itself) to views. If we are in touch mode, 4876 * only add views that are also focusable in touch mode. 4877 * 4878 * @param views Focusable views found so far 4879 * @param direction The direction of the focus 4880 */ 4881 public void addFocusables(ArrayList<View> views, int direction) { 4882 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 4883 } 4884 4885 /** 4886 * Adds any focusable views that are descendants of this view (possibly 4887 * including this view if it is focusable itself) to views. This method 4888 * adds all focusable views regardless if we are in touch mode or 4889 * only views focusable in touch mode if we are in touch mode depending on 4890 * the focusable mode paramater. 4891 * 4892 * @param views Focusable views found so far or null if all we are interested is 4893 * the number of focusables. 4894 * @param direction The direction of the focus. 4895 * @param focusableMode The type of focusables to be added. 4896 * 4897 * @see #FOCUSABLES_ALL 4898 * @see #FOCUSABLES_TOUCH_MODE 4899 */ 4900 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { 4901 if (!isFocusable()) { 4902 return; 4903 } 4904 4905 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE && 4906 isInTouchMode() && !isFocusableInTouchMode()) { 4907 return; 4908 } 4909 4910 if (views != null) { 4911 views.add(this); 4912 } 4913 } 4914 4915 /** 4916 * Finds the Views that contain given text. The containment is case insensitive. 4917 * As View's text is considered any text content that View renders. 4918 * 4919 * @param outViews The output list of matching Views. 4920 * @param text The text to match against. 4921 */ 4922 public void findViewsWithText(ArrayList<View> outViews, CharSequence text) { 4923 } 4924 4925 /** 4926 * Find and return all touchable views that are descendants of this view, 4927 * possibly including this view if it is touchable itself. 4928 * 4929 * @return A list of touchable views 4930 */ 4931 public ArrayList<View> getTouchables() { 4932 ArrayList<View> result = new ArrayList<View>(); 4933 addTouchables(result); 4934 return result; 4935 } 4936 4937 /** 4938 * Add any touchable views that are descendants of this view (possibly 4939 * including this view if it is touchable itself) to views. 4940 * 4941 * @param views Touchable views found so far 4942 */ 4943 public void addTouchables(ArrayList<View> views) { 4944 final int viewFlags = mViewFlags; 4945 4946 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 4947 && (viewFlags & ENABLED_MASK) == ENABLED) { 4948 views.add(this); 4949 } 4950 } 4951 4952 /** 4953 * Call this to try to give focus to a specific view or to one of its 4954 * descendants. 4955 * 4956 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 4957 * false), or if it is focusable and it is not focusable in touch mode 4958 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 4959 * 4960 * See also {@link #focusSearch(int)}, which is what you call to say that you 4961 * have focus, and you want your parent to look for the next one. 4962 * 4963 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 4964 * {@link #FOCUS_DOWN} and <code>null</code>. 4965 * 4966 * @return Whether this view or one of its descendants actually took focus. 4967 */ 4968 public final boolean requestFocus() { 4969 return requestFocus(View.FOCUS_DOWN); 4970 } 4971 4972 4973 /** 4974 * Call this to try to give focus to a specific view or to one of its 4975 * descendants and give it a hint about what direction focus is heading. 4976 * 4977 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 4978 * false), or if it is focusable and it is not focusable in touch mode 4979 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 4980 * 4981 * See also {@link #focusSearch(int)}, which is what you call to say that you 4982 * have focus, and you want your parent to look for the next one. 4983 * 4984 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 4985 * <code>null</code> set for the previously focused rectangle. 4986 * 4987 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 4988 * @return Whether this view or one of its descendants actually took focus. 4989 */ 4990 public final boolean requestFocus(int direction) { 4991 return requestFocus(direction, null); 4992 } 4993 4994 /** 4995 * Call this to try to give focus to a specific view or to one of its descendants 4996 * and give it hints about the direction and a specific rectangle that the focus 4997 * is coming from. The rectangle can help give larger views a finer grained hint 4998 * about where focus is coming from, and therefore, where to show selection, or 4999 * forward focus change internally. 5000 * 5001 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 5002 * false), or if it is focusable and it is not focusable in touch mode 5003 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 5004 * 5005 * A View will not take focus if it is not visible. 5006 * 5007 * A View will not take focus if one of its parents has 5008 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 5009 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 5010 * 5011 * See also {@link #focusSearch(int)}, which is what you call to say that you 5012 * have focus, and you want your parent to look for the next one. 5013 * 5014 * You may wish to override this method if your custom {@link View} has an internal 5015 * {@link View} that it wishes to forward the request to. 5016 * 5017 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 5018 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 5019 * to give a finer grained hint about where focus is coming from. May be null 5020 * if there is no hint. 5021 * @return Whether this view or one of its descendants actually took focus. 5022 */ 5023 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 5024 // need to be focusable 5025 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 5026 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 5027 return false; 5028 } 5029 5030 // need to be focusable in touch mode if in touch mode 5031 if (isInTouchMode() && 5032 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 5033 return false; 5034 } 5035 5036 // need to not have any parents blocking us 5037 if (hasAncestorThatBlocksDescendantFocus()) { 5038 return false; 5039 } 5040 5041 handleFocusGainInternal(direction, previouslyFocusedRect); 5042 return true; 5043 } 5044 5045 /** Gets the ViewAncestor, or null if not attached. */ 5046 /*package*/ ViewRootImpl getViewRootImpl() { 5047 View root = getRootView(); 5048 return root != null ? (ViewRootImpl)root.getParent() : null; 5049 } 5050 5051 /** 5052 * Call this to try to give focus to a specific view or to one of its descendants. This is a 5053 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 5054 * touch mode to request focus when they are touched. 5055 * 5056 * @return Whether this view or one of its descendants actually took focus. 5057 * 5058 * @see #isInTouchMode() 5059 * 5060 */ 5061 public final boolean requestFocusFromTouch() { 5062 // Leave touch mode if we need to 5063 if (isInTouchMode()) { 5064 ViewRootImpl viewRoot = getViewRootImpl(); 5065 if (viewRoot != null) { 5066 viewRoot.ensureTouchMode(false); 5067 } 5068 } 5069 return requestFocus(View.FOCUS_DOWN); 5070 } 5071 5072 /** 5073 * @return Whether any ancestor of this view blocks descendant focus. 5074 */ 5075 private boolean hasAncestorThatBlocksDescendantFocus() { 5076 ViewParent ancestor = mParent; 5077 while (ancestor instanceof ViewGroup) { 5078 final ViewGroup vgAncestor = (ViewGroup) ancestor; 5079 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) { 5080 return true; 5081 } else { 5082 ancestor = vgAncestor.getParent(); 5083 } 5084 } 5085 return false; 5086 } 5087 5088 /** 5089 * @hide 5090 */ 5091 public void dispatchStartTemporaryDetach() { 5092 onStartTemporaryDetach(); 5093 } 5094 5095 /** 5096 * This is called when a container is going to temporarily detach a child, with 5097 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 5098 * It will either be followed by {@link #onFinishTemporaryDetach()} or 5099 * {@link #onDetachedFromWindow()} when the container is done. 5100 */ 5101 public void onStartTemporaryDetach() { 5102 removeUnsetPressCallback(); 5103 mPrivateFlags |= CANCEL_NEXT_UP_EVENT; 5104 } 5105 5106 /** 5107 * @hide 5108 */ 5109 public void dispatchFinishTemporaryDetach() { 5110 onFinishTemporaryDetach(); 5111 } 5112 5113 /** 5114 * Called after {@link #onStartTemporaryDetach} when the container is done 5115 * changing the view. 5116 */ 5117 public void onFinishTemporaryDetach() { 5118 } 5119 5120 /** 5121 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 5122 * for this view's window. Returns null if the view is not currently attached 5123 * to the window. Normally you will not need to use this directly, but 5124 * just use the standard high-level event callbacks like 5125 * {@link #onKeyDown(int, KeyEvent)}. 5126 */ 5127 public KeyEvent.DispatcherState getKeyDispatcherState() { 5128 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 5129 } 5130 5131 /** 5132 * Dispatch a key event before it is processed by any input method 5133 * associated with the view hierarchy. This can be used to intercept 5134 * key events in special situations before the IME consumes them; a 5135 * typical example would be handling the BACK key to update the application's 5136 * UI instead of allowing the IME to see it and close itself. 5137 * 5138 * @param event The key event to be dispatched. 5139 * @return True if the event was handled, false otherwise. 5140 */ 5141 public boolean dispatchKeyEventPreIme(KeyEvent event) { 5142 return onKeyPreIme(event.getKeyCode(), event); 5143 } 5144 5145 /** 5146 * Dispatch a key event to the next view on the focus path. This path runs 5147 * from the top of the view tree down to the currently focused view. If this 5148 * view has focus, it will dispatch to itself. Otherwise it will dispatch 5149 * the next node down the focus path. This method also fires any key 5150 * listeners. 5151 * 5152 * @param event The key event to be dispatched. 5153 * @return True if the event was handled, false otherwise. 5154 */ 5155 public boolean dispatchKeyEvent(KeyEvent event) { 5156 if (mInputEventConsistencyVerifier != null) { 5157 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 5158 } 5159 5160 // Give any attached key listener a first crack at the event. 5161 //noinspection SimplifiableIfStatement 5162 if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 5163 && mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 5164 return true; 5165 } 5166 5167 if (event.dispatch(this, mAttachInfo != null 5168 ? mAttachInfo.mKeyDispatchState : null, this)) { 5169 return true; 5170 } 5171 5172 if (mInputEventConsistencyVerifier != null) { 5173 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5174 } 5175 return false; 5176 } 5177 5178 /** 5179 * Dispatches a key shortcut event. 5180 * 5181 * @param event The key event to be dispatched. 5182 * @return True if the event was handled by the view, false otherwise. 5183 */ 5184 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 5185 return onKeyShortcut(event.getKeyCode(), event); 5186 } 5187 5188 /** 5189 * Pass the touch screen motion event down to the target view, or this 5190 * view if it is the target. 5191 * 5192 * @param event The motion event to be dispatched. 5193 * @return True if the event was handled by the view, false otherwise. 5194 */ 5195 public boolean dispatchTouchEvent(MotionEvent event) { 5196 if (mInputEventConsistencyVerifier != null) { 5197 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 5198 } 5199 5200 if (onFilterTouchEventForSecurity(event)) { 5201 //noinspection SimplifiableIfStatement 5202 if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED && 5203 mOnTouchListener.onTouch(this, event)) { 5204 return true; 5205 } 5206 5207 if (onTouchEvent(event)) { 5208 return true; 5209 } 5210 } 5211 5212 if (mInputEventConsistencyVerifier != null) { 5213 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5214 } 5215 return false; 5216 } 5217 5218 /** 5219 * Filter the touch event to apply security policies. 5220 * 5221 * @param event The motion event to be filtered. 5222 * @return True if the event should be dispatched, false if the event should be dropped. 5223 * 5224 * @see #getFilterTouchesWhenObscured 5225 */ 5226 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 5227 //noinspection RedundantIfStatement 5228 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 5229 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 5230 // Window is obscured, drop this touch. 5231 return false; 5232 } 5233 return true; 5234 } 5235 5236 /** 5237 * Pass a trackball motion event down to the focused view. 5238 * 5239 * @param event The motion event to be dispatched. 5240 * @return True if the event was handled by the view, false otherwise. 5241 */ 5242 public boolean dispatchTrackballEvent(MotionEvent event) { 5243 if (mInputEventConsistencyVerifier != null) { 5244 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 5245 } 5246 5247 return onTrackballEvent(event); 5248 } 5249 5250 /** 5251 * Dispatch a generic motion event. 5252 * <p> 5253 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 5254 * are delivered to the view under the pointer. All other generic motion events are 5255 * delivered to the focused view. Hover events are handled specially and are delivered 5256 * to {@link #onHoverEvent(MotionEvent)}. 5257 * </p> 5258 * 5259 * @param event The motion event to be dispatched. 5260 * @return True if the event was handled by the view, false otherwise. 5261 */ 5262 public boolean dispatchGenericMotionEvent(MotionEvent event) { 5263 if (mInputEventConsistencyVerifier != null) { 5264 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 5265 } 5266 5267 final int source = event.getSource(); 5268 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 5269 final int action = event.getAction(); 5270 if (action == MotionEvent.ACTION_HOVER_ENTER 5271 || action == MotionEvent.ACTION_HOVER_MOVE 5272 || action == MotionEvent.ACTION_HOVER_EXIT) { 5273 if (dispatchHoverEvent(event)) { 5274 // For compatibility with existing applications that handled HOVER_MOVE 5275 // events in onGenericMotionEvent, dispatch the event there. The 5276 // onHoverEvent method did not exist at the time. 5277 if (action == MotionEvent.ACTION_HOVER_MOVE) { 5278 dispatchGenericMotionEventInternal(event); 5279 } 5280 return true; 5281 } 5282 } else if (dispatchGenericPointerEvent(event)) { 5283 return true; 5284 } 5285 } else if (dispatchGenericFocusedEvent(event)) { 5286 return true; 5287 } 5288 5289 if (dispatchGenericMotionEventInternal(event)) { 5290 return true; 5291 } 5292 5293 if (mInputEventConsistencyVerifier != null) { 5294 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5295 } 5296 return false; 5297 } 5298 5299 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 5300 //noinspection SimplifiableIfStatement 5301 if (mOnGenericMotionListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 5302 && mOnGenericMotionListener.onGenericMotion(this, event)) { 5303 return true; 5304 } 5305 5306 if (onGenericMotionEvent(event)) { 5307 return true; 5308 } 5309 5310 if (mInputEventConsistencyVerifier != null) { 5311 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5312 } 5313 return false; 5314 } 5315 5316 /** 5317 * Dispatch a hover event. 5318 * <p> 5319 * Do not call this method directly. 5320 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 5321 * </p> 5322 * 5323 * @param event The motion event to be dispatched. 5324 * @return True if the event was handled by the view, false otherwise. 5325 */ 5326 protected boolean dispatchHoverEvent(MotionEvent event) { 5327 switch (event.getAction()) { 5328 case MotionEvent.ACTION_HOVER_ENTER: 5329 if (!hasHoveredChild() && !mSendingHoverAccessibilityEvents) { 5330 mSendingHoverAccessibilityEvents = true; 5331 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 5332 } 5333 break; 5334 case MotionEvent.ACTION_HOVER_EXIT: 5335 if (mSendingHoverAccessibilityEvents) { 5336 mSendingHoverAccessibilityEvents = false; 5337 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 5338 } 5339 break; 5340 } 5341 5342 //noinspection SimplifiableIfStatement 5343 if (mOnHoverListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 5344 && mOnHoverListener.onHover(this, event)) { 5345 return true; 5346 } 5347 5348 return onHoverEvent(event); 5349 } 5350 5351 /** 5352 * Returns true if the view has a child to which it has recently sent 5353 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 5354 * it does not have a hovered child, then it must be the innermost hovered view. 5355 * @hide 5356 */ 5357 protected boolean hasHoveredChild() { 5358 return false; 5359 } 5360 5361 /** 5362 * Dispatch a generic motion event to the view under the first pointer. 5363 * <p> 5364 * Do not call this method directly. 5365 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 5366 * </p> 5367 * 5368 * @param event The motion event to be dispatched. 5369 * @return True if the event was handled by the view, false otherwise. 5370 */ 5371 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 5372 return false; 5373 } 5374 5375 /** 5376 * Dispatch a generic motion event to the currently focused view. 5377 * <p> 5378 * Do not call this method directly. 5379 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 5380 * </p> 5381 * 5382 * @param event The motion event to be dispatched. 5383 * @return True if the event was handled by the view, false otherwise. 5384 */ 5385 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 5386 return false; 5387 } 5388 5389 /** 5390 * Dispatch a pointer event. 5391 * <p> 5392 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 5393 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 5394 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 5395 * and should not be expected to handle other pointing device features. 5396 * </p> 5397 * 5398 * @param event The motion event to be dispatched. 5399 * @return True if the event was handled by the view, false otherwise. 5400 * @hide 5401 */ 5402 public final boolean dispatchPointerEvent(MotionEvent event) { 5403 if (event.isTouchEvent()) { 5404 return dispatchTouchEvent(event); 5405 } else { 5406 return dispatchGenericMotionEvent(event); 5407 } 5408 } 5409 5410 /** 5411 * Called when the window containing this view gains or loses window focus. 5412 * ViewGroups should override to route to their children. 5413 * 5414 * @param hasFocus True if the window containing this view now has focus, 5415 * false otherwise. 5416 */ 5417 public void dispatchWindowFocusChanged(boolean hasFocus) { 5418 onWindowFocusChanged(hasFocus); 5419 } 5420 5421 /** 5422 * Called when the window containing this view gains or loses focus. Note 5423 * that this is separate from view focus: to receive key events, both 5424 * your view and its window must have focus. If a window is displayed 5425 * on top of yours that takes input focus, then your own window will lose 5426 * focus but the view focus will remain unchanged. 5427 * 5428 * @param hasWindowFocus True if the window containing this view now has 5429 * focus, false otherwise. 5430 */ 5431 public void onWindowFocusChanged(boolean hasWindowFocus) { 5432 InputMethodManager imm = InputMethodManager.peekInstance(); 5433 if (!hasWindowFocus) { 5434 if (isPressed()) { 5435 setPressed(false); 5436 } 5437 if (imm != null && (mPrivateFlags & FOCUSED) != 0) { 5438 imm.focusOut(this); 5439 } 5440 removeLongPressCallback(); 5441 removeTapCallback(); 5442 onFocusLost(); 5443 } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) { 5444 imm.focusIn(this); 5445 } 5446 refreshDrawableState(); 5447 } 5448 5449 /** 5450 * Returns true if this view is in a window that currently has window focus. 5451 * Note that this is not the same as the view itself having focus. 5452 * 5453 * @return True if this view is in a window that currently has window focus. 5454 */ 5455 public boolean hasWindowFocus() { 5456 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 5457 } 5458 5459 /** 5460 * Dispatch a view visibility change down the view hierarchy. 5461 * ViewGroups should override to route to their children. 5462 * @param changedView The view whose visibility changed. Could be 'this' or 5463 * an ancestor view. 5464 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 5465 * {@link #INVISIBLE} or {@link #GONE}. 5466 */ 5467 protected void dispatchVisibilityChanged(View changedView, int visibility) { 5468 onVisibilityChanged(changedView, visibility); 5469 } 5470 5471 /** 5472 * Called when the visibility of the view or an ancestor of the view is changed. 5473 * @param changedView The view whose visibility changed. Could be 'this' or 5474 * an ancestor view. 5475 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 5476 * {@link #INVISIBLE} or {@link #GONE}. 5477 */ 5478 protected void onVisibilityChanged(View changedView, int visibility) { 5479 if (visibility == VISIBLE) { 5480 if (mAttachInfo != null) { 5481 initialAwakenScrollBars(); 5482 } else { 5483 mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH; 5484 } 5485 } 5486 } 5487 5488 /** 5489 * Dispatch a hint about whether this view is displayed. For instance, when 5490 * a View moves out of the screen, it might receives a display hint indicating 5491 * the view is not displayed. Applications should not <em>rely</em> on this hint 5492 * as there is no guarantee that they will receive one. 5493 * 5494 * @param hint A hint about whether or not this view is displayed: 5495 * {@link #VISIBLE} or {@link #INVISIBLE}. 5496 */ 5497 public void dispatchDisplayHint(int hint) { 5498 onDisplayHint(hint); 5499 } 5500 5501 /** 5502 * Gives this view a hint about whether is displayed or not. For instance, when 5503 * a View moves out of the screen, it might receives a display hint indicating 5504 * the view is not displayed. Applications should not <em>rely</em> on this hint 5505 * as there is no guarantee that they will receive one. 5506 * 5507 * @param hint A hint about whether or not this view is displayed: 5508 * {@link #VISIBLE} or {@link #INVISIBLE}. 5509 */ 5510 protected void onDisplayHint(int hint) { 5511 } 5512 5513 /** 5514 * Dispatch a window visibility change down the view hierarchy. 5515 * ViewGroups should override to route to their children. 5516 * 5517 * @param visibility The new visibility of the window. 5518 * 5519 * @see #onWindowVisibilityChanged(int) 5520 */ 5521 public void dispatchWindowVisibilityChanged(int visibility) { 5522 onWindowVisibilityChanged(visibility); 5523 } 5524 5525 /** 5526 * Called when the window containing has change its visibility 5527 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 5528 * that this tells you whether or not your window is being made visible 5529 * to the window manager; this does <em>not</em> tell you whether or not 5530 * your window is obscured by other windows on the screen, even if it 5531 * is itself visible. 5532 * 5533 * @param visibility The new visibility of the window. 5534 */ 5535 protected void onWindowVisibilityChanged(int visibility) { 5536 if (visibility == VISIBLE) { 5537 initialAwakenScrollBars(); 5538 } 5539 } 5540 5541 /** 5542 * Returns the current visibility of the window this view is attached to 5543 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 5544 * 5545 * @return Returns the current visibility of the view's window. 5546 */ 5547 public int getWindowVisibility() { 5548 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 5549 } 5550 5551 /** 5552 * Retrieve the overall visible display size in which the window this view is 5553 * attached to has been positioned in. This takes into account screen 5554 * decorations above the window, for both cases where the window itself 5555 * is being position inside of them or the window is being placed under 5556 * then and covered insets are used for the window to position its content 5557 * inside. In effect, this tells you the available area where content can 5558 * be placed and remain visible to users. 5559 * 5560 * <p>This function requires an IPC back to the window manager to retrieve 5561 * the requested information, so should not be used in performance critical 5562 * code like drawing. 5563 * 5564 * @param outRect Filled in with the visible display frame. If the view 5565 * is not attached to a window, this is simply the raw display size. 5566 */ 5567 public void getWindowVisibleDisplayFrame(Rect outRect) { 5568 if (mAttachInfo != null) { 5569 try { 5570 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 5571 } catch (RemoteException e) { 5572 return; 5573 } 5574 // XXX This is really broken, and probably all needs to be done 5575 // in the window manager, and we need to know more about whether 5576 // we want the area behind or in front of the IME. 5577 final Rect insets = mAttachInfo.mVisibleInsets; 5578 outRect.left += insets.left; 5579 outRect.top += insets.top; 5580 outRect.right -= insets.right; 5581 outRect.bottom -= insets.bottom; 5582 return; 5583 } 5584 Display d = WindowManagerImpl.getDefault().getDefaultDisplay(); 5585 d.getRectSize(outRect); 5586 } 5587 5588 /** 5589 * Dispatch a notification about a resource configuration change down 5590 * the view hierarchy. 5591 * ViewGroups should override to route to their children. 5592 * 5593 * @param newConfig The new resource configuration. 5594 * 5595 * @see #onConfigurationChanged(android.content.res.Configuration) 5596 */ 5597 public void dispatchConfigurationChanged(Configuration newConfig) { 5598 onConfigurationChanged(newConfig); 5599 } 5600 5601 /** 5602 * Called when the current configuration of the resources being used 5603 * by the application have changed. You can use this to decide when 5604 * to reload resources that can changed based on orientation and other 5605 * configuration characterstics. You only need to use this if you are 5606 * not relying on the normal {@link android.app.Activity} mechanism of 5607 * recreating the activity instance upon a configuration change. 5608 * 5609 * @param newConfig The new resource configuration. 5610 */ 5611 protected void onConfigurationChanged(Configuration newConfig) { 5612 } 5613 5614 /** 5615 * Private function to aggregate all per-view attributes in to the view 5616 * root. 5617 */ 5618 void dispatchCollectViewAttributes(int visibility) { 5619 performCollectViewAttributes(visibility); 5620 } 5621 5622 void performCollectViewAttributes(int visibility) { 5623 if ((visibility & VISIBILITY_MASK) == VISIBLE && mAttachInfo != null) { 5624 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 5625 mAttachInfo.mKeepScreenOn = true; 5626 } 5627 mAttachInfo.mSystemUiVisibility |= mSystemUiVisibility; 5628 if (mOnSystemUiVisibilityChangeListener != null) { 5629 mAttachInfo.mHasSystemUiListeners = true; 5630 } 5631 } 5632 } 5633 5634 void needGlobalAttributesUpdate(boolean force) { 5635 final AttachInfo ai = mAttachInfo; 5636 if (ai != null) { 5637 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 5638 || ai.mHasSystemUiListeners) { 5639 ai.mRecomputeGlobalAttributes = true; 5640 } 5641 } 5642 } 5643 5644 /** 5645 * Returns whether the device is currently in touch mode. Touch mode is entered 5646 * once the user begins interacting with the device by touch, and affects various 5647 * things like whether focus is always visible to the user. 5648 * 5649 * @return Whether the device is in touch mode. 5650 */ 5651 @ViewDebug.ExportedProperty 5652 public boolean isInTouchMode() { 5653 if (mAttachInfo != null) { 5654 return mAttachInfo.mInTouchMode; 5655 } else { 5656 return ViewRootImpl.isInTouchMode(); 5657 } 5658 } 5659 5660 /** 5661 * Returns the context the view is running in, through which it can 5662 * access the current theme, resources, etc. 5663 * 5664 * @return The view's Context. 5665 */ 5666 @ViewDebug.CapturedViewProperty 5667 public final Context getContext() { 5668 return mContext; 5669 } 5670 5671 /** 5672 * Handle a key event before it is processed by any input method 5673 * associated with the view hierarchy. This can be used to intercept 5674 * key events in special situations before the IME consumes them; a 5675 * typical example would be handling the BACK key to update the application's 5676 * UI instead of allowing the IME to see it and close itself. 5677 * 5678 * @param keyCode The value in event.getKeyCode(). 5679 * @param event Description of the key event. 5680 * @return If you handled the event, return true. If you want to allow the 5681 * event to be handled by the next receiver, return false. 5682 */ 5683 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 5684 return false; 5685 } 5686 5687 /** 5688 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 5689 * KeyEvent.Callback.onKeyDown()}: perform press of the view 5690 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 5691 * is released, if the view is enabled and clickable. 5692 * 5693 * @param keyCode A key code that represents the button pressed, from 5694 * {@link android.view.KeyEvent}. 5695 * @param event The KeyEvent object that defines the button action. 5696 */ 5697 public boolean onKeyDown(int keyCode, KeyEvent event) { 5698 boolean result = false; 5699 5700 switch (keyCode) { 5701 case KeyEvent.KEYCODE_DPAD_CENTER: 5702 case KeyEvent.KEYCODE_ENTER: { 5703 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 5704 return true; 5705 } 5706 // Long clickable items don't necessarily have to be clickable 5707 if (((mViewFlags & CLICKABLE) == CLICKABLE || 5708 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 5709 (event.getRepeatCount() == 0)) { 5710 setPressed(true); 5711 checkForLongClick(0); 5712 return true; 5713 } 5714 break; 5715 } 5716 } 5717 return result; 5718 } 5719 5720 /** 5721 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 5722 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 5723 * the event). 5724 */ 5725 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 5726 return false; 5727 } 5728 5729 /** 5730 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 5731 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 5732 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 5733 * {@link KeyEvent#KEYCODE_ENTER} is released. 5734 * 5735 * @param keyCode A key code that represents the button pressed, from 5736 * {@link android.view.KeyEvent}. 5737 * @param event The KeyEvent object that defines the button action. 5738 */ 5739 public boolean onKeyUp(int keyCode, KeyEvent event) { 5740 boolean result = false; 5741 5742 switch (keyCode) { 5743 case KeyEvent.KEYCODE_DPAD_CENTER: 5744 case KeyEvent.KEYCODE_ENTER: { 5745 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 5746 return true; 5747 } 5748 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 5749 setPressed(false); 5750 5751 if (!mHasPerformedLongPress) { 5752 // This is a tap, so remove the longpress check 5753 removeLongPressCallback(); 5754 5755 result = performClick(); 5756 } 5757 } 5758 break; 5759 } 5760 } 5761 return result; 5762 } 5763 5764 /** 5765 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 5766 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 5767 * the event). 5768 * 5769 * @param keyCode A key code that represents the button pressed, from 5770 * {@link android.view.KeyEvent}. 5771 * @param repeatCount The number of times the action was made. 5772 * @param event The KeyEvent object that defines the button action. 5773 */ 5774 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 5775 return false; 5776 } 5777 5778 /** 5779 * Called on the focused view when a key shortcut event is not handled. 5780 * Override this method to implement local key shortcuts for the View. 5781 * Key shortcuts can also be implemented by setting the 5782 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 5783 * 5784 * @param keyCode The value in event.getKeyCode(). 5785 * @param event Description of the key event. 5786 * @return If you handled the event, return true. If you want to allow the 5787 * event to be handled by the next receiver, return false. 5788 */ 5789 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 5790 return false; 5791 } 5792 5793 /** 5794 * Check whether the called view is a text editor, in which case it 5795 * would make sense to automatically display a soft input window for 5796 * it. Subclasses should override this if they implement 5797 * {@link #onCreateInputConnection(EditorInfo)} to return true if 5798 * a call on that method would return a non-null InputConnection, and 5799 * they are really a first-class editor that the user would normally 5800 * start typing on when the go into a window containing your view. 5801 * 5802 * <p>The default implementation always returns false. This does 5803 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 5804 * will not be called or the user can not otherwise perform edits on your 5805 * view; it is just a hint to the system that this is not the primary 5806 * purpose of this view. 5807 * 5808 * @return Returns true if this view is a text editor, else false. 5809 */ 5810 public boolean onCheckIsTextEditor() { 5811 return false; 5812 } 5813 5814 /** 5815 * Create a new InputConnection for an InputMethod to interact 5816 * with the view. The default implementation returns null, since it doesn't 5817 * support input methods. You can override this to implement such support. 5818 * This is only needed for views that take focus and text input. 5819 * 5820 * <p>When implementing this, you probably also want to implement 5821 * {@link #onCheckIsTextEditor()} to indicate you will return a 5822 * non-null InputConnection. 5823 * 5824 * @param outAttrs Fill in with attribute information about the connection. 5825 */ 5826 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 5827 return null; 5828 } 5829 5830 /** 5831 * Called by the {@link android.view.inputmethod.InputMethodManager} 5832 * when a view who is not the current 5833 * input connection target is trying to make a call on the manager. The 5834 * default implementation returns false; you can override this to return 5835 * true for certain views if you are performing InputConnection proxying 5836 * to them. 5837 * @param view The View that is making the InputMethodManager call. 5838 * @return Return true to allow the call, false to reject. 5839 */ 5840 public boolean checkInputConnectionProxy(View view) { 5841 return false; 5842 } 5843 5844 /** 5845 * Show the context menu for this view. It is not safe to hold on to the 5846 * menu after returning from this method. 5847 * 5848 * You should normally not overload this method. Overload 5849 * {@link #onCreateContextMenu(ContextMenu)} or define an 5850 * {@link OnCreateContextMenuListener} to add items to the context menu. 5851 * 5852 * @param menu The context menu to populate 5853 */ 5854 public void createContextMenu(ContextMenu menu) { 5855 ContextMenuInfo menuInfo = getContextMenuInfo(); 5856 5857 // Sets the current menu info so all items added to menu will have 5858 // my extra info set. 5859 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 5860 5861 onCreateContextMenu(menu); 5862 if (mOnCreateContextMenuListener != null) { 5863 mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 5864 } 5865 5866 // Clear the extra information so subsequent items that aren't mine don't 5867 // have my extra info. 5868 ((MenuBuilder)menu).setCurrentMenuInfo(null); 5869 5870 if (mParent != null) { 5871 mParent.createContextMenu(menu); 5872 } 5873 } 5874 5875 /** 5876 * Views should implement this if they have extra information to associate 5877 * with the context menu. The return result is supplied as a parameter to 5878 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 5879 * callback. 5880 * 5881 * @return Extra information about the item for which the context menu 5882 * should be shown. This information will vary across different 5883 * subclasses of View. 5884 */ 5885 protected ContextMenuInfo getContextMenuInfo() { 5886 return null; 5887 } 5888 5889 /** 5890 * Views should implement this if the view itself is going to add items to 5891 * the context menu. 5892 * 5893 * @param menu the context menu to populate 5894 */ 5895 protected void onCreateContextMenu(ContextMenu menu) { 5896 } 5897 5898 /** 5899 * Implement this method to handle trackball motion events. The 5900 * <em>relative</em> movement of the trackball since the last event 5901 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 5902 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 5903 * that a movement of 1 corresponds to the user pressing one DPAD key (so 5904 * they will often be fractional values, representing the more fine-grained 5905 * movement information available from a trackball). 5906 * 5907 * @param event The motion event. 5908 * @return True if the event was handled, false otherwise. 5909 */ 5910 public boolean onTrackballEvent(MotionEvent event) { 5911 return false; 5912 } 5913 5914 /** 5915 * Implement this method to handle generic motion events. 5916 * <p> 5917 * Generic motion events describe joystick movements, mouse hovers, track pad 5918 * touches, scroll wheel movements and other input events. The 5919 * {@link MotionEvent#getSource() source} of the motion event specifies 5920 * the class of input that was received. Implementations of this method 5921 * must examine the bits in the source before processing the event. 5922 * The following code example shows how this is done. 5923 * </p><p> 5924 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 5925 * are delivered to the view under the pointer. All other generic motion events are 5926 * delivered to the focused view. 5927 * </p> 5928 * <code> 5929 * public boolean onGenericMotionEvent(MotionEvent event) { 5930 * if ((event.getSource() & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) { 5931 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 5932 * // process the joystick movement... 5933 * return true; 5934 * } 5935 * } 5936 * if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) { 5937 * switch (event.getAction()) { 5938 * case MotionEvent.ACTION_HOVER_MOVE: 5939 * // process the mouse hover movement... 5940 * return true; 5941 * case MotionEvent.ACTION_SCROLL: 5942 * // process the scroll wheel movement... 5943 * return true; 5944 * } 5945 * } 5946 * return super.onGenericMotionEvent(event); 5947 * } 5948 * </code> 5949 * 5950 * @param event The generic motion event being processed. 5951 * @return True if the event was handled, false otherwise. 5952 */ 5953 public boolean onGenericMotionEvent(MotionEvent event) { 5954 return false; 5955 } 5956 5957 /** 5958 * Implement this method to handle hover events. 5959 * <p> 5960 * This method is called whenever a pointer is hovering into, over, or out of the 5961 * bounds of a view and the view is not currently being touched. 5962 * Hover events are represented as pointer events with action 5963 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 5964 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 5965 * </p> 5966 * <ul> 5967 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 5968 * when the pointer enters the bounds of the view.</li> 5969 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 5970 * when the pointer has already entered the bounds of the view and has moved.</li> 5971 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 5972 * when the pointer has exited the bounds of the view or when the pointer is 5973 * about to go down due to a button click, tap, or similar user action that 5974 * causes the view to be touched.</li> 5975 * </ul> 5976 * <p> 5977 * The view should implement this method to return true to indicate that it is 5978 * handling the hover event, such as by changing its drawable state. 5979 * </p><p> 5980 * The default implementation calls {@link #setHovered} to update the hovered state 5981 * of the view when a hover enter or hover exit event is received, if the view 5982 * is enabled and is clickable. 5983 * </p> 5984 * 5985 * @param event The motion event that describes the hover. 5986 * @return True if the view handled the hover event. 5987 * 5988 * @see #isHovered 5989 * @see #setHovered 5990 * @see #onHoverChanged 5991 */ 5992 public boolean onHoverEvent(MotionEvent event) { 5993 if (isHoverable()) { 5994 switch (event.getAction()) { 5995 case MotionEvent.ACTION_HOVER_ENTER: 5996 setHovered(true); 5997 break; 5998 case MotionEvent.ACTION_HOVER_EXIT: 5999 setHovered(false); 6000 break; 6001 } 6002 return true; 6003 } 6004 return false; 6005 } 6006 6007 /** 6008 * Returns true if the view should handle {@link #onHoverEvent} 6009 * by calling {@link #setHovered} to change its hovered state. 6010 * 6011 * @return True if the view is hoverable. 6012 */ 6013 private boolean isHoverable() { 6014 final int viewFlags = mViewFlags; 6015 //noinspection SimplifiableIfStatement 6016 if ((viewFlags & ENABLED_MASK) == DISABLED) { 6017 return false; 6018 } 6019 6020 return (viewFlags & CLICKABLE) == CLICKABLE 6021 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 6022 } 6023 6024 /** 6025 * Returns true if the view is currently hovered. 6026 * 6027 * @return True if the view is currently hovered. 6028 * 6029 * @see #setHovered 6030 * @see #onHoverChanged 6031 */ 6032 @ViewDebug.ExportedProperty 6033 public boolean isHovered() { 6034 return (mPrivateFlags & HOVERED) != 0; 6035 } 6036 6037 /** 6038 * Sets whether the view is currently hovered. 6039 * <p> 6040 * Calling this method also changes the drawable state of the view. This 6041 * enables the view to react to hover by using different drawable resources 6042 * to change its appearance. 6043 * </p><p> 6044 * The {@link #onHoverChanged} method is called when the hovered state changes. 6045 * </p> 6046 * 6047 * @param hovered True if the view is hovered. 6048 * 6049 * @see #isHovered 6050 * @see #onHoverChanged 6051 */ 6052 public void setHovered(boolean hovered) { 6053 if (hovered) { 6054 if ((mPrivateFlags & HOVERED) == 0) { 6055 mPrivateFlags |= HOVERED; 6056 refreshDrawableState(); 6057 onHoverChanged(true); 6058 } 6059 } else { 6060 if ((mPrivateFlags & HOVERED) != 0) { 6061 mPrivateFlags &= ~HOVERED; 6062 refreshDrawableState(); 6063 onHoverChanged(false); 6064 } 6065 } 6066 } 6067 6068 /** 6069 * Implement this method to handle hover state changes. 6070 * <p> 6071 * This method is called whenever the hover state changes as a result of a 6072 * call to {@link #setHovered}. 6073 * </p> 6074 * 6075 * @param hovered The current hover state, as returned by {@link #isHovered}. 6076 * 6077 * @see #isHovered 6078 * @see #setHovered 6079 */ 6080 public void onHoverChanged(boolean hovered) { 6081 } 6082 6083 /** 6084 * Implement this method to handle touch screen motion events. 6085 * 6086 * @param event The motion event. 6087 * @return True if the event was handled, false otherwise. 6088 */ 6089 public boolean onTouchEvent(MotionEvent event) { 6090 final int viewFlags = mViewFlags; 6091 6092 if ((viewFlags & ENABLED_MASK) == DISABLED) { 6093 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) { 6094 mPrivateFlags &= ~PRESSED; 6095 refreshDrawableState(); 6096 } 6097 // A disabled view that is clickable still consumes the touch 6098 // events, it just doesn't respond to them. 6099 return (((viewFlags & CLICKABLE) == CLICKABLE || 6100 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 6101 } 6102 6103 if (mTouchDelegate != null) { 6104 if (mTouchDelegate.onTouchEvent(event)) { 6105 return true; 6106 } 6107 } 6108 6109 if (((viewFlags & CLICKABLE) == CLICKABLE || 6110 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 6111 switch (event.getAction()) { 6112 case MotionEvent.ACTION_UP: 6113 boolean prepressed = (mPrivateFlags & PREPRESSED) != 0; 6114 if ((mPrivateFlags & PRESSED) != 0 || prepressed) { 6115 // take focus if we don't have it already and we should in 6116 // touch mode. 6117 boolean focusTaken = false; 6118 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 6119 focusTaken = requestFocus(); 6120 } 6121 6122 if (prepressed) { 6123 // The button is being released before we actually 6124 // showed it as pressed. Make it show the pressed 6125 // state now (before scheduling the click) to ensure 6126 // the user sees it. 6127 mPrivateFlags |= PRESSED; 6128 refreshDrawableState(); 6129 } 6130 6131 if (!mHasPerformedLongPress) { 6132 // This is a tap, so remove the longpress check 6133 removeLongPressCallback(); 6134 6135 // Only perform take click actions if we were in the pressed state 6136 if (!focusTaken) { 6137 // Use a Runnable and post this rather than calling 6138 // performClick directly. This lets other visual state 6139 // of the view update before click actions start. 6140 if (mPerformClick == null) { 6141 mPerformClick = new PerformClick(); 6142 } 6143 if (!post(mPerformClick)) { 6144 performClick(); 6145 } 6146 } 6147 } 6148 6149 if (mUnsetPressedState == null) { 6150 mUnsetPressedState = new UnsetPressedState(); 6151 } 6152 6153 if (prepressed) { 6154 postDelayed(mUnsetPressedState, 6155 ViewConfiguration.getPressedStateDuration()); 6156 } else if (!post(mUnsetPressedState)) { 6157 // If the post failed, unpress right now 6158 mUnsetPressedState.run(); 6159 } 6160 removeTapCallback(); 6161 } 6162 break; 6163 6164 case MotionEvent.ACTION_DOWN: 6165 mHasPerformedLongPress = false; 6166 6167 if (performButtonActionOnTouchDown(event)) { 6168 break; 6169 } 6170 6171 // Walk up the hierarchy to determine if we're inside a scrolling container. 6172 boolean isInScrollingContainer = false; 6173 ViewParent p = getParent(); 6174 while (p != null && p instanceof ViewGroup) { 6175 if (((ViewGroup) p).shouldDelayChildPressedState()) { 6176 isInScrollingContainer = true; 6177 break; 6178 } 6179 p = p.getParent(); 6180 } 6181 6182 // For views inside a scrolling container, delay the pressed feedback for 6183 // a short period in case this is a scroll. 6184 if (isInScrollingContainer) { 6185 mPrivateFlags |= PREPRESSED; 6186 if (mPendingCheckForTap == null) { 6187 mPendingCheckForTap = new CheckForTap(); 6188 } 6189 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 6190 } else { 6191 // Not inside a scrolling container, so show the feedback right away 6192 mPrivateFlags |= PRESSED; 6193 refreshDrawableState(); 6194 checkForLongClick(0); 6195 } 6196 break; 6197 6198 case MotionEvent.ACTION_CANCEL: 6199 mPrivateFlags &= ~PRESSED; 6200 refreshDrawableState(); 6201 removeTapCallback(); 6202 break; 6203 6204 case MotionEvent.ACTION_MOVE: 6205 final int x = (int) event.getX(); 6206 final int y = (int) event.getY(); 6207 6208 // Be lenient about moving outside of buttons 6209 if (!pointInView(x, y, mTouchSlop)) { 6210 // Outside button 6211 removeTapCallback(); 6212 if ((mPrivateFlags & PRESSED) != 0) { 6213 // Remove any future long press/tap checks 6214 removeLongPressCallback(); 6215 6216 // Need to switch from pressed to not pressed 6217 mPrivateFlags &= ~PRESSED; 6218 refreshDrawableState(); 6219 } 6220 } 6221 break; 6222 } 6223 return true; 6224 } 6225 6226 return false; 6227 } 6228 6229 /** 6230 * Remove the longpress detection timer. 6231 */ 6232 private void removeLongPressCallback() { 6233 if (mPendingCheckForLongPress != null) { 6234 removeCallbacks(mPendingCheckForLongPress); 6235 } 6236 } 6237 6238 /** 6239 * Remove the pending click action 6240 */ 6241 private void removePerformClickCallback() { 6242 if (mPerformClick != null) { 6243 removeCallbacks(mPerformClick); 6244 } 6245 } 6246 6247 /** 6248 * Remove the prepress detection timer. 6249 */ 6250 private void removeUnsetPressCallback() { 6251 if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) { 6252 setPressed(false); 6253 removeCallbacks(mUnsetPressedState); 6254 } 6255 } 6256 6257 /** 6258 * Remove the tap detection timer. 6259 */ 6260 private void removeTapCallback() { 6261 if (mPendingCheckForTap != null) { 6262 mPrivateFlags &= ~PREPRESSED; 6263 removeCallbacks(mPendingCheckForTap); 6264 } 6265 } 6266 6267 /** 6268 * Cancels a pending long press. Your subclass can use this if you 6269 * want the context menu to come up if the user presses and holds 6270 * at the same place, but you don't want it to come up if they press 6271 * and then move around enough to cause scrolling. 6272 */ 6273 public void cancelLongPress() { 6274 removeLongPressCallback(); 6275 6276 /* 6277 * The prepressed state handled by the tap callback is a display 6278 * construct, but the tap callback will post a long press callback 6279 * less its own timeout. Remove it here. 6280 */ 6281 removeTapCallback(); 6282 } 6283 6284 /** 6285 * Remove the pending callback for sending a 6286 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 6287 */ 6288 private void removeSendViewScrolledAccessibilityEventCallback() { 6289 if (mSendViewScrolledAccessibilityEvent != null) { 6290 removeCallbacks(mSendViewScrolledAccessibilityEvent); 6291 } 6292 } 6293 6294 /** 6295 * Sets the TouchDelegate for this View. 6296 */ 6297 public void setTouchDelegate(TouchDelegate delegate) { 6298 mTouchDelegate = delegate; 6299 } 6300 6301 /** 6302 * Gets the TouchDelegate for this View. 6303 */ 6304 public TouchDelegate getTouchDelegate() { 6305 return mTouchDelegate; 6306 } 6307 6308 /** 6309 * Set flags controlling behavior of this view. 6310 * 6311 * @param flags Constant indicating the value which should be set 6312 * @param mask Constant indicating the bit range that should be changed 6313 */ 6314 void setFlags(int flags, int mask) { 6315 int old = mViewFlags; 6316 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 6317 6318 int changed = mViewFlags ^ old; 6319 if (changed == 0) { 6320 return; 6321 } 6322 int privateFlags = mPrivateFlags; 6323 6324 /* Check if the FOCUSABLE bit has changed */ 6325 if (((changed & FOCUSABLE_MASK) != 0) && 6326 ((privateFlags & HAS_BOUNDS) !=0)) { 6327 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 6328 && ((privateFlags & FOCUSED) != 0)) { 6329 /* Give up focus if we are no longer focusable */ 6330 clearFocus(); 6331 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 6332 && ((privateFlags & FOCUSED) == 0)) { 6333 /* 6334 * Tell the view system that we are now available to take focus 6335 * if no one else already has it. 6336 */ 6337 if (mParent != null) mParent.focusableViewAvailable(this); 6338 } 6339 } 6340 6341 if ((flags & VISIBILITY_MASK) == VISIBLE) { 6342 if ((changed & VISIBILITY_MASK) != 0) { 6343 /* 6344 * If this view is becoming visible, set the DRAWN flag so that 6345 * the next invalidate() will not be skipped. 6346 */ 6347 mPrivateFlags |= DRAWN; 6348 6349 needGlobalAttributesUpdate(true); 6350 6351 // a view becoming visible is worth notifying the parent 6352 // about in case nothing has focus. even if this specific view 6353 // isn't focusable, it may contain something that is, so let 6354 // the root view try to give this focus if nothing else does. 6355 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 6356 mParent.focusableViewAvailable(this); 6357 } 6358 } 6359 } 6360 6361 /* Check if the GONE bit has changed */ 6362 if ((changed & GONE) != 0) { 6363 needGlobalAttributesUpdate(false); 6364 requestLayout(); 6365 invalidate(true); 6366 6367 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 6368 if (hasFocus()) clearFocus(); 6369 destroyDrawingCache(); 6370 } 6371 if (mAttachInfo != null) { 6372 mAttachInfo.mViewVisibilityChanged = true; 6373 } 6374 } 6375 6376 /* Check if the VISIBLE bit has changed */ 6377 if ((changed & INVISIBLE) != 0) { 6378 needGlobalAttributesUpdate(false); 6379 /* 6380 * If this view is becoming invisible, set the DRAWN flag so that 6381 * the next invalidate() will not be skipped. 6382 */ 6383 mPrivateFlags |= DRAWN; 6384 6385 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) { 6386 // root view becoming invisible shouldn't clear focus 6387 if (getRootView() != this) { 6388 clearFocus(); 6389 } 6390 } 6391 if (mAttachInfo != null) { 6392 mAttachInfo.mViewVisibilityChanged = true; 6393 } 6394 } 6395 6396 if ((changed & VISIBILITY_MASK) != 0) { 6397 if (mParent instanceof ViewGroup) { 6398 ((ViewGroup) mParent).onChildVisibilityChanged(this, (flags & VISIBILITY_MASK)); 6399 ((View) mParent).invalidate(true); 6400 } 6401 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK)); 6402 } 6403 6404 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 6405 destroyDrawingCache(); 6406 } 6407 6408 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 6409 destroyDrawingCache(); 6410 mPrivateFlags &= ~DRAWING_CACHE_VALID; 6411 invalidateParentCaches(); 6412 } 6413 6414 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 6415 destroyDrawingCache(); 6416 mPrivateFlags &= ~DRAWING_CACHE_VALID; 6417 } 6418 6419 if ((changed & DRAW_MASK) != 0) { 6420 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 6421 if (mBGDrawable != null) { 6422 mPrivateFlags &= ~SKIP_DRAW; 6423 mPrivateFlags |= ONLY_DRAWS_BACKGROUND; 6424 } else { 6425 mPrivateFlags |= SKIP_DRAW; 6426 } 6427 } else { 6428 mPrivateFlags &= ~SKIP_DRAW; 6429 } 6430 requestLayout(); 6431 invalidate(true); 6432 } 6433 6434 if ((changed & KEEP_SCREEN_ON) != 0) { 6435 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 6436 mParent.recomputeViewAttributes(this); 6437 } 6438 } 6439 6440 if ((changed & LAYOUT_DIRECTION_MASK) != 0) { 6441 requestLayout(); 6442 } 6443 } 6444 6445 /** 6446 * Change the view's z order in the tree, so it's on top of other sibling 6447 * views 6448 */ 6449 public void bringToFront() { 6450 if (mParent != null) { 6451 mParent.bringChildToFront(this); 6452 } 6453 } 6454 6455 /** 6456 * This is called in response to an internal scroll in this view (i.e., the 6457 * view scrolled its own contents). This is typically as a result of 6458 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 6459 * called. 6460 * 6461 * @param l Current horizontal scroll origin. 6462 * @param t Current vertical scroll origin. 6463 * @param oldl Previous horizontal scroll origin. 6464 * @param oldt Previous vertical scroll origin. 6465 */ 6466 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 6467 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 6468 postSendViewScrolledAccessibilityEventCallback(); 6469 } 6470 6471 mBackgroundSizeChanged = true; 6472 6473 final AttachInfo ai = mAttachInfo; 6474 if (ai != null) { 6475 ai.mViewScrollChanged = true; 6476 } 6477 } 6478 6479 /** 6480 * Interface definition for a callback to be invoked when the layout bounds of a view 6481 * changes due to layout processing. 6482 */ 6483 public interface OnLayoutChangeListener { 6484 /** 6485 * Called when the focus state of a view has changed. 6486 * 6487 * @param v The view whose state has changed. 6488 * @param left The new value of the view's left property. 6489 * @param top The new value of the view's top property. 6490 * @param right The new value of the view's right property. 6491 * @param bottom The new value of the view's bottom property. 6492 * @param oldLeft The previous value of the view's left property. 6493 * @param oldTop The previous value of the view's top property. 6494 * @param oldRight The previous value of the view's right property. 6495 * @param oldBottom The previous value of the view's bottom property. 6496 */ 6497 void onLayoutChange(View v, int left, int top, int right, int bottom, 6498 int oldLeft, int oldTop, int oldRight, int oldBottom); 6499 } 6500 6501 /** 6502 * This is called during layout when the size of this view has changed. If 6503 * you were just added to the view hierarchy, you're called with the old 6504 * values of 0. 6505 * 6506 * @param w Current width of this view. 6507 * @param h Current height of this view. 6508 * @param oldw Old width of this view. 6509 * @param oldh Old height of this view. 6510 */ 6511 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 6512 } 6513 6514 /** 6515 * Called by draw to draw the child views. This may be overridden 6516 * by derived classes to gain control just before its children are drawn 6517 * (but after its own view has been drawn). 6518 * @param canvas the canvas on which to draw the view 6519 */ 6520 protected void dispatchDraw(Canvas canvas) { 6521 } 6522 6523 /** 6524 * Gets the parent of this view. Note that the parent is a 6525 * ViewParent and not necessarily a View. 6526 * 6527 * @return Parent of this view. 6528 */ 6529 public final ViewParent getParent() { 6530 return mParent; 6531 } 6532 6533 /** 6534 * Set the horizontal scrolled position of your view. This will cause a call to 6535 * {@link #onScrollChanged(int, int, int, int)} and the view will be 6536 * invalidated. 6537 * @param value the x position to scroll to 6538 */ 6539 public void setScrollX(int value) { 6540 scrollTo(value, mScrollY); 6541 } 6542 6543 /** 6544 * Set the vertical scrolled position of your view. This will cause a call to 6545 * {@link #onScrollChanged(int, int, int, int)} and the view will be 6546 * invalidated. 6547 * @param value the y position to scroll to 6548 */ 6549 public void setScrollY(int value) { 6550 scrollTo(mScrollX, value); 6551 } 6552 6553 /** 6554 * Return the scrolled left position of this view. This is the left edge of 6555 * the displayed part of your view. You do not need to draw any pixels 6556 * farther left, since those are outside of the frame of your view on 6557 * screen. 6558 * 6559 * @return The left edge of the displayed part of your view, in pixels. 6560 */ 6561 public final int getScrollX() { 6562 return mScrollX; 6563 } 6564 6565 /** 6566 * Return the scrolled top position of this view. This is the top edge of 6567 * the displayed part of your view. You do not need to draw any pixels above 6568 * it, since those are outside of the frame of your view on screen. 6569 * 6570 * @return The top edge of the displayed part of your view, in pixels. 6571 */ 6572 public final int getScrollY() { 6573 return mScrollY; 6574 } 6575 6576 /** 6577 * Return the width of the your view. 6578 * 6579 * @return The width of your view, in pixels. 6580 */ 6581 @ViewDebug.ExportedProperty(category = "layout") 6582 public final int getWidth() { 6583 return mRight - mLeft; 6584 } 6585 6586 /** 6587 * Return the height of your view. 6588 * 6589 * @return The height of your view, in pixels. 6590 */ 6591 @ViewDebug.ExportedProperty(category = "layout") 6592 public final int getHeight() { 6593 return mBottom - mTop; 6594 } 6595 6596 /** 6597 * Return the visible drawing bounds of your view. Fills in the output 6598 * rectangle with the values from getScrollX(), getScrollY(), 6599 * getWidth(), and getHeight(). 6600 * 6601 * @param outRect The (scrolled) drawing bounds of the view. 6602 */ 6603 public void getDrawingRect(Rect outRect) { 6604 outRect.left = mScrollX; 6605 outRect.top = mScrollY; 6606 outRect.right = mScrollX + (mRight - mLeft); 6607 outRect.bottom = mScrollY + (mBottom - mTop); 6608 } 6609 6610 /** 6611 * Like {@link #getMeasuredWidthAndState()}, but only returns the 6612 * raw width component (that is the result is masked by 6613 * {@link #MEASURED_SIZE_MASK}). 6614 * 6615 * @return The raw measured width of this view. 6616 */ 6617 public final int getMeasuredWidth() { 6618 return mMeasuredWidth & MEASURED_SIZE_MASK; 6619 } 6620 6621 /** 6622 * Return the full width measurement information for this view as computed 6623 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 6624 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 6625 * This should be used during measurement and layout calculations only. Use 6626 * {@link #getWidth()} to see how wide a view is after layout. 6627 * 6628 * @return The measured width of this view as a bit mask. 6629 */ 6630 public final int getMeasuredWidthAndState() { 6631 return mMeasuredWidth; 6632 } 6633 6634 /** 6635 * Like {@link #getMeasuredHeightAndState()}, but only returns the 6636 * raw width component (that is the result is masked by 6637 * {@link #MEASURED_SIZE_MASK}). 6638 * 6639 * @return The raw measured height of this view. 6640 */ 6641 public final int getMeasuredHeight() { 6642 return mMeasuredHeight & MEASURED_SIZE_MASK; 6643 } 6644 6645 /** 6646 * Return the full height measurement information for this view as computed 6647 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 6648 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 6649 * This should be used during measurement and layout calculations only. Use 6650 * {@link #getHeight()} to see how wide a view is after layout. 6651 * 6652 * @return The measured width of this view as a bit mask. 6653 */ 6654 public final int getMeasuredHeightAndState() { 6655 return mMeasuredHeight; 6656 } 6657 6658 /** 6659 * Return only the state bits of {@link #getMeasuredWidthAndState()} 6660 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 6661 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 6662 * and the height component is at the shifted bits 6663 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 6664 */ 6665 public final int getMeasuredState() { 6666 return (mMeasuredWidth&MEASURED_STATE_MASK) 6667 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 6668 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 6669 } 6670 6671 /** 6672 * The transform matrix of this view, which is calculated based on the current 6673 * roation, scale, and pivot properties. 6674 * 6675 * @see #getRotation() 6676 * @see #getScaleX() 6677 * @see #getScaleY() 6678 * @see #getPivotX() 6679 * @see #getPivotY() 6680 * @return The current transform matrix for the view 6681 */ 6682 public Matrix getMatrix() { 6683 updateMatrix(); 6684 return mMatrix; 6685 } 6686 6687 /** 6688 * Utility function to determine if the value is far enough away from zero to be 6689 * considered non-zero. 6690 * @param value A floating point value to check for zero-ness 6691 * @return whether the passed-in value is far enough away from zero to be considered non-zero 6692 */ 6693 private static boolean nonzero(float value) { 6694 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON); 6695 } 6696 6697 /** 6698 * Returns true if the transform matrix is the identity matrix. 6699 * Recomputes the matrix if necessary. 6700 * 6701 * @return True if the transform matrix is the identity matrix, false otherwise. 6702 */ 6703 final boolean hasIdentityMatrix() { 6704 updateMatrix(); 6705 return mMatrixIsIdentity; 6706 } 6707 6708 /** 6709 * Recomputes the transform matrix if necessary. 6710 */ 6711 private void updateMatrix() { 6712 if (mMatrixDirty) { 6713 // transform-related properties have changed since the last time someone 6714 // asked for the matrix; recalculate it with the current values 6715 6716 // Figure out if we need to update the pivot point 6717 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 6718 if ((mRight - mLeft) != mPrevWidth || (mBottom - mTop) != mPrevHeight) { 6719 mPrevWidth = mRight - mLeft; 6720 mPrevHeight = mBottom - mTop; 6721 mPivotX = mPrevWidth / 2f; 6722 mPivotY = mPrevHeight / 2f; 6723 } 6724 } 6725 mMatrix.reset(); 6726 if (!nonzero(mRotationX) && !nonzero(mRotationY)) { 6727 mMatrix.setTranslate(mTranslationX, mTranslationY); 6728 mMatrix.preRotate(mRotation, mPivotX, mPivotY); 6729 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY); 6730 } else { 6731 if (mCamera == null) { 6732 mCamera = new Camera(); 6733 matrix3D = new Matrix(); 6734 } 6735 mCamera.save(); 6736 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY); 6737 mCamera.rotate(mRotationX, mRotationY, -mRotation); 6738 mCamera.getMatrix(matrix3D); 6739 matrix3D.preTranslate(-mPivotX, -mPivotY); 6740 matrix3D.postTranslate(mPivotX + mTranslationX, mPivotY + mTranslationY); 6741 mMatrix.postConcat(matrix3D); 6742 mCamera.restore(); 6743 } 6744 mMatrixDirty = false; 6745 mMatrixIsIdentity = mMatrix.isIdentity(); 6746 mInverseMatrixDirty = true; 6747 } 6748 } 6749 6750 /** 6751 * Utility method to retrieve the inverse of the current mMatrix property. 6752 * We cache the matrix to avoid recalculating it when transform properties 6753 * have not changed. 6754 * 6755 * @return The inverse of the current matrix of this view. 6756 */ 6757 final Matrix getInverseMatrix() { 6758 updateMatrix(); 6759 if (mInverseMatrixDirty) { 6760 if (mInverseMatrix == null) { 6761 mInverseMatrix = new Matrix(); 6762 } 6763 mMatrix.invert(mInverseMatrix); 6764 mInverseMatrixDirty = false; 6765 } 6766 return mInverseMatrix; 6767 } 6768 6769 /** 6770 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 6771 * views are drawn) from the camera to this view. The camera's distance 6772 * affects 3D transformations, for instance rotations around the X and Y 6773 * axis. If the rotationX or rotationY properties are changed and this view is 6774 * large (more than half the size of the screen), it is recommended to always 6775 * use a camera distance that's greater than the height (X axis rotation) or 6776 * the width (Y axis rotation) of this view.</p> 6777 * 6778 * <p>The distance of the camera from the view plane can have an affect on the 6779 * perspective distortion of the view when it is rotated around the x or y axis. 6780 * For example, a large distance will result in a large viewing angle, and there 6781 * will not be much perspective distortion of the view as it rotates. A short 6782 * distance may cause much more perspective distortion upon rotation, and can 6783 * also result in some drawing artifacts if the rotated view ends up partially 6784 * behind the camera (which is why the recommendation is to use a distance at 6785 * least as far as the size of the view, if the view is to be rotated.)</p> 6786 * 6787 * <p>The distance is expressed in "depth pixels." The default distance depends 6788 * on the screen density. For instance, on a medium density display, the 6789 * default distance is 1280. On a high density display, the default distance 6790 * is 1920.</p> 6791 * 6792 * <p>If you want to specify a distance that leads to visually consistent 6793 * results across various densities, use the following formula:</p> 6794 * <pre> 6795 * float scale = context.getResources().getDisplayMetrics().density; 6796 * view.setCameraDistance(distance * scale); 6797 * </pre> 6798 * 6799 * <p>The density scale factor of a high density display is 1.5, 6800 * and 1920 = 1280 * 1.5.</p> 6801 * 6802 * @param distance The distance in "depth pixels", if negative the opposite 6803 * value is used 6804 * 6805 * @see #setRotationX(float) 6806 * @see #setRotationY(float) 6807 */ 6808 public void setCameraDistance(float distance) { 6809 invalidateParentCaches(); 6810 invalidate(false); 6811 6812 final float dpi = mResources.getDisplayMetrics().densityDpi; 6813 if (mCamera == null) { 6814 mCamera = new Camera(); 6815 matrix3D = new Matrix(); 6816 } 6817 6818 mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi); 6819 mMatrixDirty = true; 6820 6821 invalidate(false); 6822 } 6823 6824 /** 6825 * The degrees that the view is rotated around the pivot point. 6826 * 6827 * @see #setRotation(float) 6828 * @see #getPivotX() 6829 * @see #getPivotY() 6830 * 6831 * @return The degrees of rotation. 6832 */ 6833 public float getRotation() { 6834 return mRotation; 6835 } 6836 6837 /** 6838 * Sets the degrees that the view is rotated around the pivot point. Increasing values 6839 * result in clockwise rotation. 6840 * 6841 * @param rotation The degrees of rotation. 6842 * 6843 * @see #getRotation() 6844 * @see #getPivotX() 6845 * @see #getPivotY() 6846 * @see #setRotationX(float) 6847 * @see #setRotationY(float) 6848 * 6849 * @attr ref android.R.styleable#View_rotation 6850 */ 6851 public void setRotation(float rotation) { 6852 if (mRotation != rotation) { 6853 invalidateParentCaches(); 6854 // Double-invalidation is necessary to capture view's old and new areas 6855 invalidate(false); 6856 mRotation = rotation; 6857 mMatrixDirty = true; 6858 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6859 invalidate(false); 6860 } 6861 } 6862 6863 /** 6864 * The degrees that the view is rotated around the vertical axis through the pivot point. 6865 * 6866 * @see #getPivotX() 6867 * @see #getPivotY() 6868 * @see #setRotationY(float) 6869 * 6870 * @return The degrees of Y rotation. 6871 */ 6872 public float getRotationY() { 6873 return mRotationY; 6874 } 6875 6876 /** 6877 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 6878 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 6879 * down the y axis. 6880 * 6881 * When rotating large views, it is recommended to adjust the camera distance 6882 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 6883 * 6884 * @param rotationY The degrees of Y rotation. 6885 * 6886 * @see #getRotationY() 6887 * @see #getPivotX() 6888 * @see #getPivotY() 6889 * @see #setRotation(float) 6890 * @see #setRotationX(float) 6891 * @see #setCameraDistance(float) 6892 * 6893 * @attr ref android.R.styleable#View_rotationY 6894 */ 6895 public void setRotationY(float rotationY) { 6896 if (mRotationY != rotationY) { 6897 invalidateParentCaches(); 6898 // Double-invalidation is necessary to capture view's old and new areas 6899 invalidate(false); 6900 mRotationY = rotationY; 6901 mMatrixDirty = true; 6902 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6903 invalidate(false); 6904 } 6905 } 6906 6907 /** 6908 * The degrees that the view is rotated around the horizontal axis through the pivot point. 6909 * 6910 * @see #getPivotX() 6911 * @see #getPivotY() 6912 * @see #setRotationX(float) 6913 * 6914 * @return The degrees of X rotation. 6915 */ 6916 public float getRotationX() { 6917 return mRotationX; 6918 } 6919 6920 /** 6921 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 6922 * Increasing values result in clockwise rotation from the viewpoint of looking down the 6923 * x axis. 6924 * 6925 * When rotating large views, it is recommended to adjust the camera distance 6926 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 6927 * 6928 * @param rotationX The degrees of X rotation. 6929 * 6930 * @see #getRotationX() 6931 * @see #getPivotX() 6932 * @see #getPivotY() 6933 * @see #setRotation(float) 6934 * @see #setRotationY(float) 6935 * @see #setCameraDistance(float) 6936 * 6937 * @attr ref android.R.styleable#View_rotationX 6938 */ 6939 public void setRotationX(float rotationX) { 6940 if (mRotationX != rotationX) { 6941 invalidateParentCaches(); 6942 // Double-invalidation is necessary to capture view's old and new areas 6943 invalidate(false); 6944 mRotationX = rotationX; 6945 mMatrixDirty = true; 6946 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6947 invalidate(false); 6948 } 6949 } 6950 6951 /** 6952 * The amount that the view is scaled in x around the pivot point, as a proportion of 6953 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 6954 * 6955 * <p>By default, this is 1.0f. 6956 * 6957 * @see #getPivotX() 6958 * @see #getPivotY() 6959 * @return The scaling factor. 6960 */ 6961 public float getScaleX() { 6962 return mScaleX; 6963 } 6964 6965 /** 6966 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 6967 * the view's unscaled width. A value of 1 means that no scaling is applied. 6968 * 6969 * @param scaleX The scaling factor. 6970 * @see #getPivotX() 6971 * @see #getPivotY() 6972 * 6973 * @attr ref android.R.styleable#View_scaleX 6974 */ 6975 public void setScaleX(float scaleX) { 6976 if (mScaleX != scaleX) { 6977 invalidateParentCaches(); 6978 // Double-invalidation is necessary to capture view's old and new areas 6979 invalidate(false); 6980 mScaleX = scaleX; 6981 mMatrixDirty = true; 6982 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6983 invalidate(false); 6984 } 6985 } 6986 6987 /** 6988 * The amount that the view is scaled in y around the pivot point, as a proportion of 6989 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 6990 * 6991 * <p>By default, this is 1.0f. 6992 * 6993 * @see #getPivotX() 6994 * @see #getPivotY() 6995 * @return The scaling factor. 6996 */ 6997 public float getScaleY() { 6998 return mScaleY; 6999 } 7000 7001 /** 7002 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 7003 * the view's unscaled width. A value of 1 means that no scaling is applied. 7004 * 7005 * @param scaleY The scaling factor. 7006 * @see #getPivotX() 7007 * @see #getPivotY() 7008 * 7009 * @attr ref android.R.styleable#View_scaleY 7010 */ 7011 public void setScaleY(float scaleY) { 7012 if (mScaleY != scaleY) { 7013 invalidateParentCaches(); 7014 // Double-invalidation is necessary to capture view's old and new areas 7015 invalidate(false); 7016 mScaleY = scaleY; 7017 mMatrixDirty = true; 7018 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7019 invalidate(false); 7020 } 7021 } 7022 7023 /** 7024 * The x location of the point around which the view is {@link #setRotation(float) rotated} 7025 * and {@link #setScaleX(float) scaled}. 7026 * 7027 * @see #getRotation() 7028 * @see #getScaleX() 7029 * @see #getScaleY() 7030 * @see #getPivotY() 7031 * @return The x location of the pivot point. 7032 */ 7033 public float getPivotX() { 7034 return mPivotX; 7035 } 7036 7037 /** 7038 * Sets the x location of the point around which the view is 7039 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 7040 * By default, the pivot point is centered on the object. 7041 * Setting this property disables this behavior and causes the view to use only the 7042 * explicitly set pivotX and pivotY values. 7043 * 7044 * @param pivotX The x location of the pivot point. 7045 * @see #getRotation() 7046 * @see #getScaleX() 7047 * @see #getScaleY() 7048 * @see #getPivotY() 7049 * 7050 * @attr ref android.R.styleable#View_transformPivotX 7051 */ 7052 public void setPivotX(float pivotX) { 7053 mPrivateFlags |= PIVOT_EXPLICITLY_SET; 7054 if (mPivotX != pivotX) { 7055 invalidateParentCaches(); 7056 // Double-invalidation is necessary to capture view's old and new areas 7057 invalidate(false); 7058 mPivotX = pivotX; 7059 mMatrixDirty = true; 7060 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7061 invalidate(false); 7062 } 7063 } 7064 7065 /** 7066 * The y location of the point around which the view is {@link #setRotation(float) rotated} 7067 * and {@link #setScaleY(float) scaled}. 7068 * 7069 * @see #getRotation() 7070 * @see #getScaleX() 7071 * @see #getScaleY() 7072 * @see #getPivotY() 7073 * @return The y location of the pivot point. 7074 */ 7075 public float getPivotY() { 7076 return mPivotY; 7077 } 7078 7079 /** 7080 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 7081 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 7082 * Setting this property disables this behavior and causes the view to use only the 7083 * explicitly set pivotX and pivotY values. 7084 * 7085 * @param pivotY The y location of the pivot point. 7086 * @see #getRotation() 7087 * @see #getScaleX() 7088 * @see #getScaleY() 7089 * @see #getPivotY() 7090 * 7091 * @attr ref android.R.styleable#View_transformPivotY 7092 */ 7093 public void setPivotY(float pivotY) { 7094 mPrivateFlags |= PIVOT_EXPLICITLY_SET; 7095 if (mPivotY != pivotY) { 7096 invalidateParentCaches(); 7097 // Double-invalidation is necessary to capture view's old and new areas 7098 invalidate(false); 7099 mPivotY = pivotY; 7100 mMatrixDirty = true; 7101 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7102 invalidate(false); 7103 } 7104 } 7105 7106 /** 7107 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 7108 * completely transparent and 1 means the view is completely opaque. 7109 * 7110 * <p>By default this is 1.0f. 7111 * @return The opacity of the view. 7112 */ 7113 public float getAlpha() { 7114 return mAlpha; 7115 } 7116 7117 /** 7118 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 7119 * completely transparent and 1 means the view is completely opaque.</p> 7120 * 7121 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 7122 * responsible for applying the opacity itself. Otherwise, calling this method is 7123 * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and 7124 * setting a hardware layer.</p> 7125 * 7126 * @param alpha The opacity of the view. 7127 * 7128 * @see #setLayerType(int, android.graphics.Paint) 7129 * 7130 * @attr ref android.R.styleable#View_alpha 7131 */ 7132 public void setAlpha(float alpha) { 7133 mAlpha = alpha; 7134 invalidateParentCaches(); 7135 if (onSetAlpha((int) (alpha * 255))) { 7136 mPrivateFlags |= ALPHA_SET; 7137 // subclass is handling alpha - don't optimize rendering cache invalidation 7138 invalidate(true); 7139 } else { 7140 mPrivateFlags &= ~ALPHA_SET; 7141 invalidate(false); 7142 } 7143 } 7144 7145 /** 7146 * Faster version of setAlpha() which performs the same steps except there are 7147 * no calls to invalidate(). The caller of this function should perform proper invalidation 7148 * on the parent and this object. The return value indicates whether the subclass handles 7149 * alpha (the return value for onSetAlpha()). 7150 * 7151 * @param alpha The new value for the alpha property 7152 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) 7153 */ 7154 boolean setAlphaNoInvalidation(float alpha) { 7155 mAlpha = alpha; 7156 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 7157 if (subclassHandlesAlpha) { 7158 mPrivateFlags |= ALPHA_SET; 7159 } else { 7160 mPrivateFlags &= ~ALPHA_SET; 7161 } 7162 return subclassHandlesAlpha; 7163 } 7164 7165 /** 7166 * Top position of this view relative to its parent. 7167 * 7168 * @return The top of this view, in pixels. 7169 */ 7170 @ViewDebug.CapturedViewProperty 7171 public final int getTop() { 7172 return mTop; 7173 } 7174 7175 /** 7176 * Sets the top position of this view relative to its parent. This method is meant to be called 7177 * by the layout system and should not generally be called otherwise, because the property 7178 * may be changed at any time by the layout. 7179 * 7180 * @param top The top of this view, in pixels. 7181 */ 7182 public final void setTop(int top) { 7183 if (top != mTop) { 7184 updateMatrix(); 7185 if (mMatrixIsIdentity) { 7186 if (mAttachInfo != null) { 7187 int minTop; 7188 int yLoc; 7189 if (top < mTop) { 7190 minTop = top; 7191 yLoc = top - mTop; 7192 } else { 7193 minTop = mTop; 7194 yLoc = 0; 7195 } 7196 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 7197 } 7198 } else { 7199 // Double-invalidation is necessary to capture view's old and new areas 7200 invalidate(true); 7201 } 7202 7203 int width = mRight - mLeft; 7204 int oldHeight = mBottom - mTop; 7205 7206 mTop = top; 7207 7208 onSizeChanged(width, mBottom - mTop, width, oldHeight); 7209 7210 if (!mMatrixIsIdentity) { 7211 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7212 // A change in dimension means an auto-centered pivot point changes, too 7213 mMatrixDirty = true; 7214 } 7215 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7216 invalidate(true); 7217 } 7218 mBackgroundSizeChanged = true; 7219 invalidateParentIfNeeded(); 7220 } 7221 } 7222 7223 /** 7224 * Bottom position of this view relative to its parent. 7225 * 7226 * @return The bottom of this view, in pixels. 7227 */ 7228 @ViewDebug.CapturedViewProperty 7229 public final int getBottom() { 7230 return mBottom; 7231 } 7232 7233 /** 7234 * True if this view has changed since the last time being drawn. 7235 * 7236 * @return The dirty state of this view. 7237 */ 7238 public boolean isDirty() { 7239 return (mPrivateFlags & DIRTY_MASK) != 0; 7240 } 7241 7242 /** 7243 * Sets the bottom position of this view relative to its parent. This method is meant to be 7244 * called by the layout system and should not generally be called otherwise, because the 7245 * property may be changed at any time by the layout. 7246 * 7247 * @param bottom The bottom of this view, in pixels. 7248 */ 7249 public final void setBottom(int bottom) { 7250 if (bottom != mBottom) { 7251 updateMatrix(); 7252 if (mMatrixIsIdentity) { 7253 if (mAttachInfo != null) { 7254 int maxBottom; 7255 if (bottom < mBottom) { 7256 maxBottom = mBottom; 7257 } else { 7258 maxBottom = bottom; 7259 } 7260 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 7261 } 7262 } else { 7263 // Double-invalidation is necessary to capture view's old and new areas 7264 invalidate(true); 7265 } 7266 7267 int width = mRight - mLeft; 7268 int oldHeight = mBottom - mTop; 7269 7270 mBottom = bottom; 7271 7272 onSizeChanged(width, mBottom - mTop, width, oldHeight); 7273 7274 if (!mMatrixIsIdentity) { 7275 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7276 // A change in dimension means an auto-centered pivot point changes, too 7277 mMatrixDirty = true; 7278 } 7279 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7280 invalidate(true); 7281 } 7282 mBackgroundSizeChanged = true; 7283 invalidateParentIfNeeded(); 7284 } 7285 } 7286 7287 /** 7288 * Left position of this view relative to its parent. 7289 * 7290 * @return The left edge of this view, in pixels. 7291 */ 7292 @ViewDebug.CapturedViewProperty 7293 public final int getLeft() { 7294 return mLeft; 7295 } 7296 7297 /** 7298 * Sets the left position of this view relative to its parent. This method is meant to be called 7299 * by the layout system and should not generally be called otherwise, because the property 7300 * may be changed at any time by the layout. 7301 * 7302 * @param left The bottom of this view, in pixels. 7303 */ 7304 public final void setLeft(int left) { 7305 if (left != mLeft) { 7306 updateMatrix(); 7307 if (mMatrixIsIdentity) { 7308 if (mAttachInfo != null) { 7309 int minLeft; 7310 int xLoc; 7311 if (left < mLeft) { 7312 minLeft = left; 7313 xLoc = left - mLeft; 7314 } else { 7315 minLeft = mLeft; 7316 xLoc = 0; 7317 } 7318 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 7319 } 7320 } else { 7321 // Double-invalidation is necessary to capture view's old and new areas 7322 invalidate(true); 7323 } 7324 7325 int oldWidth = mRight - mLeft; 7326 int height = mBottom - mTop; 7327 7328 mLeft = left; 7329 7330 onSizeChanged(mRight - mLeft, height, oldWidth, height); 7331 7332 if (!mMatrixIsIdentity) { 7333 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7334 // A change in dimension means an auto-centered pivot point changes, too 7335 mMatrixDirty = true; 7336 } 7337 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7338 invalidate(true); 7339 } 7340 mBackgroundSizeChanged = true; 7341 invalidateParentIfNeeded(); 7342 } 7343 } 7344 7345 /** 7346 * Right position of this view relative to its parent. 7347 * 7348 * @return The right edge of this view, in pixels. 7349 */ 7350 @ViewDebug.CapturedViewProperty 7351 public final int getRight() { 7352 return mRight; 7353 } 7354 7355 /** 7356 * Sets the right position of this view relative to its parent. This method is meant to be called 7357 * by the layout system and should not generally be called otherwise, because the property 7358 * may be changed at any time by the layout. 7359 * 7360 * @param right The bottom of this view, in pixels. 7361 */ 7362 public final void setRight(int right) { 7363 if (right != mRight) { 7364 updateMatrix(); 7365 if (mMatrixIsIdentity) { 7366 if (mAttachInfo != null) { 7367 int maxRight; 7368 if (right < mRight) { 7369 maxRight = mRight; 7370 } else { 7371 maxRight = right; 7372 } 7373 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 7374 } 7375 } else { 7376 // Double-invalidation is necessary to capture view's old and new areas 7377 invalidate(true); 7378 } 7379 7380 int oldWidth = mRight - mLeft; 7381 int height = mBottom - mTop; 7382 7383 mRight = right; 7384 7385 onSizeChanged(mRight - mLeft, height, oldWidth, height); 7386 7387 if (!mMatrixIsIdentity) { 7388 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7389 // A change in dimension means an auto-centered pivot point changes, too 7390 mMatrixDirty = true; 7391 } 7392 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7393 invalidate(true); 7394 } 7395 mBackgroundSizeChanged = true; 7396 invalidateParentIfNeeded(); 7397 } 7398 } 7399 7400 /** 7401 * The visual x position of this view, in pixels. This is equivalent to the 7402 * {@link #setTranslationX(float) translationX} property plus the current 7403 * {@link #getLeft() left} property. 7404 * 7405 * @return The visual x position of this view, in pixels. 7406 */ 7407 public float getX() { 7408 return mLeft + mTranslationX; 7409 } 7410 7411 /** 7412 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 7413 * {@link #setTranslationX(float) translationX} property to be the difference between 7414 * the x value passed in and the current {@link #getLeft() left} property. 7415 * 7416 * @param x The visual x position of this view, in pixels. 7417 */ 7418 public void setX(float x) { 7419 setTranslationX(x - mLeft); 7420 } 7421 7422 /** 7423 * The visual y position of this view, in pixels. This is equivalent to the 7424 * {@link #setTranslationY(float) translationY} property plus the current 7425 * {@link #getTop() top} property. 7426 * 7427 * @return The visual y position of this view, in pixels. 7428 */ 7429 public float getY() { 7430 return mTop + mTranslationY; 7431 } 7432 7433 /** 7434 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 7435 * {@link #setTranslationY(float) translationY} property to be the difference between 7436 * the y value passed in and the current {@link #getTop() top} property. 7437 * 7438 * @param y The visual y position of this view, in pixels. 7439 */ 7440 public void setY(float y) { 7441 setTranslationY(y - mTop); 7442 } 7443 7444 7445 /** 7446 * The horizontal location of this view relative to its {@link #getLeft() left} position. 7447 * This position is post-layout, in addition to wherever the object's 7448 * layout placed it. 7449 * 7450 * @return The horizontal position of this view relative to its left position, in pixels. 7451 */ 7452 public float getTranslationX() { 7453 return mTranslationX; 7454 } 7455 7456 /** 7457 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 7458 * This effectively positions the object post-layout, in addition to wherever the object's 7459 * layout placed it. 7460 * 7461 * @param translationX The horizontal position of this view relative to its left position, 7462 * in pixels. 7463 * 7464 * @attr ref android.R.styleable#View_translationX 7465 */ 7466 public void setTranslationX(float translationX) { 7467 if (mTranslationX != translationX) { 7468 invalidateParentCaches(); 7469 // Double-invalidation is necessary to capture view's old and new areas 7470 invalidate(false); 7471 mTranslationX = translationX; 7472 mMatrixDirty = true; 7473 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7474 invalidate(false); 7475 } 7476 } 7477 7478 /** 7479 * The horizontal location of this view relative to its {@link #getTop() top} position. 7480 * This position is post-layout, in addition to wherever the object's 7481 * layout placed it. 7482 * 7483 * @return The vertical position of this view relative to its top position, 7484 * in pixels. 7485 */ 7486 public float getTranslationY() { 7487 return mTranslationY; 7488 } 7489 7490 /** 7491 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 7492 * This effectively positions the object post-layout, in addition to wherever the object's 7493 * layout placed it. 7494 * 7495 * @param translationY The vertical position of this view relative to its top position, 7496 * in pixels. 7497 * 7498 * @attr ref android.R.styleable#View_translationY 7499 */ 7500 public void setTranslationY(float translationY) { 7501 if (mTranslationY != translationY) { 7502 invalidateParentCaches(); 7503 // Double-invalidation is necessary to capture view's old and new areas 7504 invalidate(false); 7505 mTranslationY = translationY; 7506 mMatrixDirty = true; 7507 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7508 invalidate(false); 7509 } 7510 } 7511 7512 /** 7513 * @hide 7514 */ 7515 public void setFastTranslationX(float x) { 7516 mTranslationX = x; 7517 mMatrixDirty = true; 7518 } 7519 7520 /** 7521 * @hide 7522 */ 7523 public void setFastTranslationY(float y) { 7524 mTranslationY = y; 7525 mMatrixDirty = true; 7526 } 7527 7528 /** 7529 * @hide 7530 */ 7531 public void setFastX(float x) { 7532 mTranslationX = x - mLeft; 7533 mMatrixDirty = true; 7534 } 7535 7536 /** 7537 * @hide 7538 */ 7539 public void setFastY(float y) { 7540 mTranslationY = y - mTop; 7541 mMatrixDirty = true; 7542 } 7543 7544 /** 7545 * @hide 7546 */ 7547 public void setFastScaleX(float x) { 7548 mScaleX = x; 7549 mMatrixDirty = true; 7550 } 7551 7552 /** 7553 * @hide 7554 */ 7555 public void setFastScaleY(float y) { 7556 mScaleY = y; 7557 mMatrixDirty = true; 7558 } 7559 7560 /** 7561 * @hide 7562 */ 7563 public void setFastAlpha(float alpha) { 7564 mAlpha = alpha; 7565 } 7566 7567 /** 7568 * @hide 7569 */ 7570 public void setFastRotationY(float y) { 7571 mRotationY = y; 7572 mMatrixDirty = true; 7573 } 7574 7575 /** 7576 * Hit rectangle in parent's coordinates 7577 * 7578 * @param outRect The hit rectangle of the view. 7579 */ 7580 public void getHitRect(Rect outRect) { 7581 updateMatrix(); 7582 if (mMatrixIsIdentity || mAttachInfo == null) { 7583 outRect.set(mLeft, mTop, mRight, mBottom); 7584 } else { 7585 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 7586 tmpRect.set(-mPivotX, -mPivotY, getWidth() - mPivotX, getHeight() - mPivotY); 7587 mMatrix.mapRect(tmpRect); 7588 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 7589 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 7590 } 7591 } 7592 7593 /** 7594 * Determines whether the given point, in local coordinates is inside the view. 7595 */ 7596 /*package*/ final boolean pointInView(float localX, float localY) { 7597 return localX >= 0 && localX < (mRight - mLeft) 7598 && localY >= 0 && localY < (mBottom - mTop); 7599 } 7600 7601 /** 7602 * Utility method to determine whether the given point, in local coordinates, 7603 * is inside the view, where the area of the view is expanded by the slop factor. 7604 * This method is called while processing touch-move events to determine if the event 7605 * is still within the view. 7606 */ 7607 private boolean pointInView(float localX, float localY, float slop) { 7608 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 7609 localY < ((mBottom - mTop) + slop); 7610 } 7611 7612 /** 7613 * When a view has focus and the user navigates away from it, the next view is searched for 7614 * starting from the rectangle filled in by this method. 7615 * 7616 * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)}) 7617 * of the view. However, if your view maintains some idea of internal selection, 7618 * such as a cursor, or a selected row or column, you should override this method and 7619 * fill in a more specific rectangle. 7620 * 7621 * @param r The rectangle to fill in, in this view's coordinates. 7622 */ 7623 public void getFocusedRect(Rect r) { 7624 getDrawingRect(r); 7625 } 7626 7627 /** 7628 * If some part of this view is not clipped by any of its parents, then 7629 * return that area in r in global (root) coordinates. To convert r to local 7630 * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x, 7631 * -globalOffset.y)) If the view is completely clipped or translated out, 7632 * return false. 7633 * 7634 * @param r If true is returned, r holds the global coordinates of the 7635 * visible portion of this view. 7636 * @param globalOffset If true is returned, globalOffset holds the dx,dy 7637 * between this view and its root. globalOffet may be null. 7638 * @return true if r is non-empty (i.e. part of the view is visible at the 7639 * root level. 7640 */ 7641 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 7642 int width = mRight - mLeft; 7643 int height = mBottom - mTop; 7644 if (width > 0 && height > 0) { 7645 r.set(0, 0, width, height); 7646 if (globalOffset != null) { 7647 globalOffset.set(-mScrollX, -mScrollY); 7648 } 7649 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 7650 } 7651 return false; 7652 } 7653 7654 public final boolean getGlobalVisibleRect(Rect r) { 7655 return getGlobalVisibleRect(r, null); 7656 } 7657 7658 public final boolean getLocalVisibleRect(Rect r) { 7659 Point offset = new Point(); 7660 if (getGlobalVisibleRect(r, offset)) { 7661 r.offset(-offset.x, -offset.y); // make r local 7662 return true; 7663 } 7664 return false; 7665 } 7666 7667 /** 7668 * Offset this view's vertical location by the specified number of pixels. 7669 * 7670 * @param offset the number of pixels to offset the view by 7671 */ 7672 public void offsetTopAndBottom(int offset) { 7673 if (offset != 0) { 7674 updateMatrix(); 7675 if (mMatrixIsIdentity) { 7676 final ViewParent p = mParent; 7677 if (p != null && mAttachInfo != null) { 7678 final Rect r = mAttachInfo.mTmpInvalRect; 7679 int minTop; 7680 int maxBottom; 7681 int yLoc; 7682 if (offset < 0) { 7683 minTop = mTop + offset; 7684 maxBottom = mBottom; 7685 yLoc = offset; 7686 } else { 7687 minTop = mTop; 7688 maxBottom = mBottom + offset; 7689 yLoc = 0; 7690 } 7691 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 7692 p.invalidateChild(this, r); 7693 } 7694 } else { 7695 invalidate(false); 7696 } 7697 7698 mTop += offset; 7699 mBottom += offset; 7700 7701 if (!mMatrixIsIdentity) { 7702 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7703 invalidate(false); 7704 } 7705 invalidateParentIfNeeded(); 7706 } 7707 } 7708 7709 /** 7710 * Offset this view's horizontal location by the specified amount of pixels. 7711 * 7712 * @param offset the numer of pixels to offset the view by 7713 */ 7714 public void offsetLeftAndRight(int offset) { 7715 if (offset != 0) { 7716 updateMatrix(); 7717 if (mMatrixIsIdentity) { 7718 final ViewParent p = mParent; 7719 if (p != null && mAttachInfo != null) { 7720 final Rect r = mAttachInfo.mTmpInvalRect; 7721 int minLeft; 7722 int maxRight; 7723 if (offset < 0) { 7724 minLeft = mLeft + offset; 7725 maxRight = mRight; 7726 } else { 7727 minLeft = mLeft; 7728 maxRight = mRight + offset; 7729 } 7730 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 7731 p.invalidateChild(this, r); 7732 } 7733 } else { 7734 invalidate(false); 7735 } 7736 7737 mLeft += offset; 7738 mRight += offset; 7739 7740 if (!mMatrixIsIdentity) { 7741 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7742 invalidate(false); 7743 } 7744 invalidateParentIfNeeded(); 7745 } 7746 } 7747 7748 /** 7749 * Get the LayoutParams associated with this view. All views should have 7750 * layout parameters. These supply parameters to the <i>parent</i> of this 7751 * view specifying how it should be arranged. There are many subclasses of 7752 * ViewGroup.LayoutParams, and these correspond to the different subclasses 7753 * of ViewGroup that are responsible for arranging their children. 7754 * 7755 * This method may return null if this View is not attached to a parent 7756 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 7757 * was not invoked successfully. When a View is attached to a parent 7758 * ViewGroup, this method must not return null. 7759 * 7760 * @return The LayoutParams associated with this view, or null if no 7761 * parameters have been set yet 7762 */ 7763 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 7764 public ViewGroup.LayoutParams getLayoutParams() { 7765 return mLayoutParams; 7766 } 7767 7768 /** 7769 * Set the layout parameters associated with this view. These supply 7770 * parameters to the <i>parent</i> of this view specifying how it should be 7771 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 7772 * correspond to the different subclasses of ViewGroup that are responsible 7773 * for arranging their children. 7774 * 7775 * @param params The layout parameters for this view, cannot be null 7776 */ 7777 public void setLayoutParams(ViewGroup.LayoutParams params) { 7778 if (params == null) { 7779 throw new NullPointerException("Layout parameters cannot be null"); 7780 } 7781 mLayoutParams = params; 7782 requestLayout(); 7783 } 7784 7785 /** 7786 * Set the scrolled position of your view. This will cause a call to 7787 * {@link #onScrollChanged(int, int, int, int)} and the view will be 7788 * invalidated. 7789 * @param x the x position to scroll to 7790 * @param y the y position to scroll to 7791 */ 7792 public void scrollTo(int x, int y) { 7793 if (mScrollX != x || mScrollY != y) { 7794 int oldX = mScrollX; 7795 int oldY = mScrollY; 7796 mScrollX = x; 7797 mScrollY = y; 7798 invalidateParentCaches(); 7799 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 7800 if (!awakenScrollBars()) { 7801 invalidate(true); 7802 } 7803 } 7804 } 7805 7806 /** 7807 * Move the scrolled position of your view. This will cause a call to 7808 * {@link #onScrollChanged(int, int, int, int)} and the view will be 7809 * invalidated. 7810 * @param x the amount of pixels to scroll by horizontally 7811 * @param y the amount of pixels to scroll by vertically 7812 */ 7813 public void scrollBy(int x, int y) { 7814 scrollTo(mScrollX + x, mScrollY + y); 7815 } 7816 7817 /** 7818 * <p>Trigger the scrollbars to draw. When invoked this method starts an 7819 * animation to fade the scrollbars out after a default delay. If a subclass 7820 * provides animated scrolling, the start delay should equal the duration 7821 * of the scrolling animation.</p> 7822 * 7823 * <p>The animation starts only if at least one of the scrollbars is 7824 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 7825 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 7826 * this method returns true, and false otherwise. If the animation is 7827 * started, this method calls {@link #invalidate()}; in that case the 7828 * caller should not call {@link #invalidate()}.</p> 7829 * 7830 * <p>This method should be invoked every time a subclass directly updates 7831 * the scroll parameters.</p> 7832 * 7833 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 7834 * and {@link #scrollTo(int, int)}.</p> 7835 * 7836 * @return true if the animation is played, false otherwise 7837 * 7838 * @see #awakenScrollBars(int) 7839 * @see #scrollBy(int, int) 7840 * @see #scrollTo(int, int) 7841 * @see #isHorizontalScrollBarEnabled() 7842 * @see #isVerticalScrollBarEnabled() 7843 * @see #setHorizontalScrollBarEnabled(boolean) 7844 * @see #setVerticalScrollBarEnabled(boolean) 7845 */ 7846 protected boolean awakenScrollBars() { 7847 return mScrollCache != null && 7848 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 7849 } 7850 7851 /** 7852 * Trigger the scrollbars to draw. 7853 * This method differs from awakenScrollBars() only in its default duration. 7854 * initialAwakenScrollBars() will show the scroll bars for longer than 7855 * usual to give the user more of a chance to notice them. 7856 * 7857 * @return true if the animation is played, false otherwise. 7858 */ 7859 private boolean initialAwakenScrollBars() { 7860 return mScrollCache != null && 7861 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 7862 } 7863 7864 /** 7865 * <p> 7866 * Trigger the scrollbars to draw. When invoked this method starts an 7867 * animation to fade the scrollbars out after a fixed delay. If a subclass 7868 * provides animated scrolling, the start delay should equal the duration of 7869 * the scrolling animation. 7870 * </p> 7871 * 7872 * <p> 7873 * The animation starts only if at least one of the scrollbars is enabled, 7874 * as specified by {@link #isHorizontalScrollBarEnabled()} and 7875 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 7876 * this method returns true, and false otherwise. If the animation is 7877 * started, this method calls {@link #invalidate()}; in that case the caller 7878 * should not call {@link #invalidate()}. 7879 * </p> 7880 * 7881 * <p> 7882 * This method should be invoked everytime a subclass directly updates the 7883 * scroll parameters. 7884 * </p> 7885 * 7886 * @param startDelay the delay, in milliseconds, after which the animation 7887 * should start; when the delay is 0, the animation starts 7888 * immediately 7889 * @return true if the animation is played, false otherwise 7890 * 7891 * @see #scrollBy(int, int) 7892 * @see #scrollTo(int, int) 7893 * @see #isHorizontalScrollBarEnabled() 7894 * @see #isVerticalScrollBarEnabled() 7895 * @see #setHorizontalScrollBarEnabled(boolean) 7896 * @see #setVerticalScrollBarEnabled(boolean) 7897 */ 7898 protected boolean awakenScrollBars(int startDelay) { 7899 return awakenScrollBars(startDelay, true); 7900 } 7901 7902 /** 7903 * <p> 7904 * Trigger the scrollbars to draw. When invoked this method starts an 7905 * animation to fade the scrollbars out after a fixed delay. If a subclass 7906 * provides animated scrolling, the start delay should equal the duration of 7907 * the scrolling animation. 7908 * </p> 7909 * 7910 * <p> 7911 * The animation starts only if at least one of the scrollbars is enabled, 7912 * as specified by {@link #isHorizontalScrollBarEnabled()} and 7913 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 7914 * this method returns true, and false otherwise. If the animation is 7915 * started, this method calls {@link #invalidate()} if the invalidate parameter 7916 * is set to true; in that case the caller 7917 * should not call {@link #invalidate()}. 7918 * </p> 7919 * 7920 * <p> 7921 * This method should be invoked everytime a subclass directly updates the 7922 * scroll parameters. 7923 * </p> 7924 * 7925 * @param startDelay the delay, in milliseconds, after which the animation 7926 * should start; when the delay is 0, the animation starts 7927 * immediately 7928 * 7929 * @param invalidate Wheter this method should call invalidate 7930 * 7931 * @return true if the animation is played, false otherwise 7932 * 7933 * @see #scrollBy(int, int) 7934 * @see #scrollTo(int, int) 7935 * @see #isHorizontalScrollBarEnabled() 7936 * @see #isVerticalScrollBarEnabled() 7937 * @see #setHorizontalScrollBarEnabled(boolean) 7938 * @see #setVerticalScrollBarEnabled(boolean) 7939 */ 7940 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 7941 final ScrollabilityCache scrollCache = mScrollCache; 7942 7943 if (scrollCache == null || !scrollCache.fadeScrollBars) { 7944 return false; 7945 } 7946 7947 if (scrollCache.scrollBar == null) { 7948 scrollCache.scrollBar = new ScrollBarDrawable(); 7949 } 7950 7951 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 7952 7953 if (invalidate) { 7954 // Invalidate to show the scrollbars 7955 invalidate(true); 7956 } 7957 7958 if (scrollCache.state == ScrollabilityCache.OFF) { 7959 // FIXME: this is copied from WindowManagerService. 7960 // We should get this value from the system when it 7961 // is possible to do so. 7962 final int KEY_REPEAT_FIRST_DELAY = 750; 7963 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 7964 } 7965 7966 // Tell mScrollCache when we should start fading. This may 7967 // extend the fade start time if one was already scheduled 7968 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 7969 scrollCache.fadeStartTime = fadeStartTime; 7970 scrollCache.state = ScrollabilityCache.ON; 7971 7972 // Schedule our fader to run, unscheduling any old ones first 7973 if (mAttachInfo != null) { 7974 mAttachInfo.mHandler.removeCallbacks(scrollCache); 7975 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 7976 } 7977 7978 return true; 7979 } 7980 7981 return false; 7982 } 7983 7984 /** 7985 * Mark the the area defined by dirty as needing to be drawn. If the view is 7986 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point 7987 * in the future. This must be called from a UI thread. To call from a non-UI 7988 * thread, call {@link #postInvalidate()}. 7989 * 7990 * WARNING: This method is destructive to dirty. 7991 * @param dirty the rectangle representing the bounds of the dirty region 7992 */ 7993 public void invalidate(Rect dirty) { 7994 if (ViewDebug.TRACE_HIERARCHY) { 7995 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 7996 } 7997 7998 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 7999 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID || 8000 (mPrivateFlags & INVALIDATED) != INVALIDATED) { 8001 mPrivateFlags &= ~DRAWING_CACHE_VALID; 8002 mPrivateFlags |= INVALIDATED; 8003 final ViewParent p = mParent; 8004 final AttachInfo ai = mAttachInfo; 8005 //noinspection PointlessBooleanExpression,ConstantConditions 8006 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 8007 if (p != null && ai != null && ai.mHardwareAccelerated) { 8008 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 8009 // with a null dirty rect, which tells the ViewAncestor to redraw everything 8010 p.invalidateChild(this, null); 8011 return; 8012 } 8013 } 8014 if (p != null && ai != null) { 8015 final int scrollX = mScrollX; 8016 final int scrollY = mScrollY; 8017 final Rect r = ai.mTmpInvalRect; 8018 r.set(dirty.left - scrollX, dirty.top - scrollY, 8019 dirty.right - scrollX, dirty.bottom - scrollY); 8020 mParent.invalidateChild(this, r); 8021 } 8022 } 8023 } 8024 8025 /** 8026 * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn. 8027 * The coordinates of the dirty rect are relative to the view. 8028 * If the view is visible, {@link #onDraw(android.graphics.Canvas)} 8029 * will be called at some point in the future. This must be called from 8030 * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}. 8031 * @param l the left position of the dirty region 8032 * @param t the top position of the dirty region 8033 * @param r the right position of the dirty region 8034 * @param b the bottom position of the dirty region 8035 */ 8036 public void invalidate(int l, int t, int r, int b) { 8037 if (ViewDebug.TRACE_HIERARCHY) { 8038 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 8039 } 8040 8041 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 8042 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID || 8043 (mPrivateFlags & INVALIDATED) != INVALIDATED) { 8044 mPrivateFlags &= ~DRAWING_CACHE_VALID; 8045 mPrivateFlags |= INVALIDATED; 8046 final ViewParent p = mParent; 8047 final AttachInfo ai = mAttachInfo; 8048 //noinspection PointlessBooleanExpression,ConstantConditions 8049 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 8050 if (p != null && ai != null && ai.mHardwareAccelerated) { 8051 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 8052 // with a null dirty rect, which tells the ViewAncestor to redraw everything 8053 p.invalidateChild(this, null); 8054 return; 8055 } 8056 } 8057 if (p != null && ai != null && l < r && t < b) { 8058 final int scrollX = mScrollX; 8059 final int scrollY = mScrollY; 8060 final Rect tmpr = ai.mTmpInvalRect; 8061 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY); 8062 p.invalidateChild(this, tmpr); 8063 } 8064 } 8065 } 8066 8067 /** 8068 * Invalidate the whole view. If the view is visible, 8069 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 8070 * the future. This must be called from a UI thread. To call from a non-UI thread, 8071 * call {@link #postInvalidate()}. 8072 */ 8073 public void invalidate() { 8074 invalidate(true); 8075 } 8076 8077 /** 8078 * This is where the invalidate() work actually happens. A full invalidate() 8079 * causes the drawing cache to be invalidated, but this function can be called with 8080 * invalidateCache set to false to skip that invalidation step for cases that do not 8081 * need it (for example, a component that remains at the same dimensions with the same 8082 * content). 8083 * 8084 * @param invalidateCache Whether the drawing cache for this view should be invalidated as 8085 * well. This is usually true for a full invalidate, but may be set to false if the 8086 * View's contents or dimensions have not changed. 8087 */ 8088 void invalidate(boolean invalidateCache) { 8089 if (ViewDebug.TRACE_HIERARCHY) { 8090 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 8091 } 8092 8093 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 8094 (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) || 8095 (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) { 8096 mLastIsOpaque = isOpaque(); 8097 mPrivateFlags &= ~DRAWN; 8098 if (invalidateCache) { 8099 mPrivateFlags |= INVALIDATED; 8100 mPrivateFlags &= ~DRAWING_CACHE_VALID; 8101 } 8102 final AttachInfo ai = mAttachInfo; 8103 final ViewParent p = mParent; 8104 //noinspection PointlessBooleanExpression,ConstantConditions 8105 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 8106 if (p != null && ai != null && ai.mHardwareAccelerated) { 8107 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 8108 // with a null dirty rect, which tells the ViewAncestor to redraw everything 8109 p.invalidateChild(this, null); 8110 return; 8111 } 8112 } 8113 8114 if (p != null && ai != null) { 8115 final Rect r = ai.mTmpInvalRect; 8116 r.set(0, 0, mRight - mLeft, mBottom - mTop); 8117 // Don't call invalidate -- we don't want to internally scroll 8118 // our own bounds 8119 p.invalidateChild(this, r); 8120 } 8121 } 8122 } 8123 8124 /** 8125 * @hide 8126 */ 8127 public void fastInvalidate() { 8128 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 8129 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID || 8130 (mPrivateFlags & INVALIDATED) != INVALIDATED) { 8131 if (mParent instanceof View) { 8132 ((View) mParent).mPrivateFlags |= INVALIDATED; 8133 } 8134 mPrivateFlags &= ~DRAWN; 8135 mPrivateFlags |= INVALIDATED; 8136 mPrivateFlags &= ~DRAWING_CACHE_VALID; 8137 if (mParent != null && mAttachInfo != null) { 8138 if (mAttachInfo.mHardwareAccelerated) { 8139 mParent.invalidateChild(this, null); 8140 } else { 8141 final Rect r = mAttachInfo.mTmpInvalRect; 8142 r.set(0, 0, mRight - mLeft, mBottom - mTop); 8143 // Don't call invalidate -- we don't want to internally scroll 8144 // our own bounds 8145 mParent.invalidateChild(this, r); 8146 } 8147 } 8148 } 8149 } 8150 8151 /** 8152 * Used to indicate that the parent of this view should clear its caches. This functionality 8153 * is used to force the parent to rebuild its display list (when hardware-accelerated), 8154 * which is necessary when various parent-managed properties of the view change, such as 8155 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 8156 * clears the parent caches and does not causes an invalidate event. 8157 * 8158 * @hide 8159 */ 8160 protected void invalidateParentCaches() { 8161 if (mParent instanceof View) { 8162 ((View) mParent).mPrivateFlags |= INVALIDATED; 8163 } 8164 } 8165 8166 /** 8167 * Used to indicate that the parent of this view should be invalidated. This functionality 8168 * is used to force the parent to rebuild its display list (when hardware-accelerated), 8169 * which is necessary when various parent-managed properties of the view change, such as 8170 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 8171 * an invalidation event to the parent. 8172 * 8173 * @hide 8174 */ 8175 protected void invalidateParentIfNeeded() { 8176 if (isHardwareAccelerated() && mParent instanceof View) { 8177 ((View) mParent).invalidate(true); 8178 } 8179 } 8180 8181 /** 8182 * Indicates whether this View is opaque. An opaque View guarantees that it will 8183 * draw all the pixels overlapping its bounds using a fully opaque color. 8184 * 8185 * Subclasses of View should override this method whenever possible to indicate 8186 * whether an instance is opaque. Opaque Views are treated in a special way by 8187 * the View hierarchy, possibly allowing it to perform optimizations during 8188 * invalidate/draw passes. 8189 * 8190 * @return True if this View is guaranteed to be fully opaque, false otherwise. 8191 */ 8192 @ViewDebug.ExportedProperty(category = "drawing") 8193 public boolean isOpaque() { 8194 return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK && 8195 (mAlpha >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD); 8196 } 8197 8198 /** 8199 * @hide 8200 */ 8201 protected void computeOpaqueFlags() { 8202 // Opaque if: 8203 // - Has a background 8204 // - Background is opaque 8205 // - Doesn't have scrollbars or scrollbars are inside overlay 8206 8207 if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) { 8208 mPrivateFlags |= OPAQUE_BACKGROUND; 8209 } else { 8210 mPrivateFlags &= ~OPAQUE_BACKGROUND; 8211 } 8212 8213 final int flags = mViewFlags; 8214 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 8215 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) { 8216 mPrivateFlags |= OPAQUE_SCROLLBARS; 8217 } else { 8218 mPrivateFlags &= ~OPAQUE_SCROLLBARS; 8219 } 8220 } 8221 8222 /** 8223 * @hide 8224 */ 8225 protected boolean hasOpaqueScrollbars() { 8226 return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS; 8227 } 8228 8229 /** 8230 * @return A handler associated with the thread running the View. This 8231 * handler can be used to pump events in the UI events queue. 8232 */ 8233 public Handler getHandler() { 8234 if (mAttachInfo != null) { 8235 return mAttachInfo.mHandler; 8236 } 8237 return null; 8238 } 8239 8240 /** 8241 * Causes the Runnable to be added to the message queue. 8242 * The runnable will be run on the user interface thread. 8243 * 8244 * @param action The Runnable that will be executed. 8245 * 8246 * @return Returns true if the Runnable was successfully placed in to the 8247 * message queue. Returns false on failure, usually because the 8248 * looper processing the message queue is exiting. 8249 */ 8250 public boolean post(Runnable action) { 8251 Handler handler; 8252 AttachInfo attachInfo = mAttachInfo; 8253 if (attachInfo != null) { 8254 handler = attachInfo.mHandler; 8255 } else { 8256 // Assume that post will succeed later 8257 ViewRootImpl.getRunQueue().post(action); 8258 return true; 8259 } 8260 8261 return handler.post(action); 8262 } 8263 8264 /** 8265 * Causes the Runnable to be added to the message queue, to be run 8266 * after the specified amount of time elapses. 8267 * The runnable will be run on the user interface thread. 8268 * 8269 * @param action The Runnable that will be executed. 8270 * @param delayMillis The delay (in milliseconds) until the Runnable 8271 * will be executed. 8272 * 8273 * @return true if the Runnable was successfully placed in to the 8274 * message queue. Returns false on failure, usually because the 8275 * looper processing the message queue is exiting. Note that a 8276 * result of true does not mean the Runnable will be processed -- 8277 * if the looper is quit before the delivery time of the message 8278 * occurs then the message will be dropped. 8279 */ 8280 public boolean postDelayed(Runnable action, long delayMillis) { 8281 Handler handler; 8282 AttachInfo attachInfo = mAttachInfo; 8283 if (attachInfo != null) { 8284 handler = attachInfo.mHandler; 8285 } else { 8286 // Assume that post will succeed later 8287 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 8288 return true; 8289 } 8290 8291 return handler.postDelayed(action, delayMillis); 8292 } 8293 8294 /** 8295 * Removes the specified Runnable from the message queue. 8296 * 8297 * @param action The Runnable to remove from the message handling queue 8298 * 8299 * @return true if this view could ask the Handler to remove the Runnable, 8300 * false otherwise. When the returned value is true, the Runnable 8301 * may or may not have been actually removed from the message queue 8302 * (for instance, if the Runnable was not in the queue already.) 8303 */ 8304 public boolean removeCallbacks(Runnable action) { 8305 Handler handler; 8306 AttachInfo attachInfo = mAttachInfo; 8307 if (attachInfo != null) { 8308 handler = attachInfo.mHandler; 8309 } else { 8310 // Assume that post will succeed later 8311 ViewRootImpl.getRunQueue().removeCallbacks(action); 8312 return true; 8313 } 8314 8315 handler.removeCallbacks(action); 8316 return true; 8317 } 8318 8319 /** 8320 * Cause an invalidate to happen on a subsequent cycle through the event loop. 8321 * Use this to invalidate the View from a non-UI thread. 8322 * 8323 * @see #invalidate() 8324 */ 8325 public void postInvalidate() { 8326 postInvalidateDelayed(0); 8327 } 8328 8329 /** 8330 * Cause an invalidate of the specified area to happen on a subsequent cycle 8331 * through the event loop. Use this to invalidate the View from a non-UI thread. 8332 * 8333 * @param left The left coordinate of the rectangle to invalidate. 8334 * @param top The top coordinate of the rectangle to invalidate. 8335 * @param right The right coordinate of the rectangle to invalidate. 8336 * @param bottom The bottom coordinate of the rectangle to invalidate. 8337 * 8338 * @see #invalidate(int, int, int, int) 8339 * @see #invalidate(Rect) 8340 */ 8341 public void postInvalidate(int left, int top, int right, int bottom) { 8342 postInvalidateDelayed(0, left, top, right, bottom); 8343 } 8344 8345 /** 8346 * Cause an invalidate to happen on a subsequent cycle through the event 8347 * loop. Waits for the specified amount of time. 8348 * 8349 * @param delayMilliseconds the duration in milliseconds to delay the 8350 * invalidation by 8351 */ 8352 public void postInvalidateDelayed(long delayMilliseconds) { 8353 // We try only with the AttachInfo because there's no point in invalidating 8354 // if we are not attached to our window 8355 AttachInfo attachInfo = mAttachInfo; 8356 if (attachInfo != null) { 8357 Message msg = Message.obtain(); 8358 msg.what = AttachInfo.INVALIDATE_MSG; 8359 msg.obj = this; 8360 attachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds); 8361 } 8362 } 8363 8364 /** 8365 * Cause an invalidate of the specified area to happen on a subsequent cycle 8366 * through the event loop. Waits for the specified amount of time. 8367 * 8368 * @param delayMilliseconds the duration in milliseconds to delay the 8369 * invalidation by 8370 * @param left The left coordinate of the rectangle to invalidate. 8371 * @param top The top coordinate of the rectangle to invalidate. 8372 * @param right The right coordinate of the rectangle to invalidate. 8373 * @param bottom The bottom coordinate of the rectangle to invalidate. 8374 */ 8375 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 8376 int right, int bottom) { 8377 8378 // We try only with the AttachInfo because there's no point in invalidating 8379 // if we are not attached to our window 8380 AttachInfo attachInfo = mAttachInfo; 8381 if (attachInfo != null) { 8382 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire(); 8383 info.target = this; 8384 info.left = left; 8385 info.top = top; 8386 info.right = right; 8387 info.bottom = bottom; 8388 8389 final Message msg = Message.obtain(); 8390 msg.what = AttachInfo.INVALIDATE_RECT_MSG; 8391 msg.obj = info; 8392 attachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds); 8393 } 8394 } 8395 8396 /** 8397 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 8398 * This event is sent at most once every 8399 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 8400 */ 8401 private void postSendViewScrolledAccessibilityEventCallback() { 8402 if (mSendViewScrolledAccessibilityEvent == null) { 8403 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 8404 } 8405 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 8406 mSendViewScrolledAccessibilityEvent.mIsPending = true; 8407 postDelayed(mSendViewScrolledAccessibilityEvent, 8408 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 8409 } 8410 } 8411 8412 /** 8413 * Called by a parent to request that a child update its values for mScrollX 8414 * and mScrollY if necessary. This will typically be done if the child is 8415 * animating a scroll using a {@link android.widget.Scroller Scroller} 8416 * object. 8417 */ 8418 public void computeScroll() { 8419 } 8420 8421 /** 8422 * <p>Indicate whether the horizontal edges are faded when the view is 8423 * scrolled horizontally.</p> 8424 * 8425 * @return true if the horizontal edges should are faded on scroll, false 8426 * otherwise 8427 * 8428 * @see #setHorizontalFadingEdgeEnabled(boolean) 8429 * @attr ref android.R.styleable#View_fadingEdge 8430 */ 8431 public boolean isHorizontalFadingEdgeEnabled() { 8432 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 8433 } 8434 8435 /** 8436 * <p>Define whether the horizontal edges should be faded when this view 8437 * is scrolled horizontally.</p> 8438 * 8439 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 8440 * be faded when the view is scrolled 8441 * horizontally 8442 * 8443 * @see #isHorizontalFadingEdgeEnabled() 8444 * @attr ref android.R.styleable#View_fadingEdge 8445 */ 8446 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 8447 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 8448 if (horizontalFadingEdgeEnabled) { 8449 initScrollCache(); 8450 } 8451 8452 mViewFlags ^= FADING_EDGE_HORIZONTAL; 8453 } 8454 } 8455 8456 /** 8457 * <p>Indicate whether the vertical edges are faded when the view is 8458 * scrolled horizontally.</p> 8459 * 8460 * @return true if the vertical edges should are faded on scroll, false 8461 * otherwise 8462 * 8463 * @see #setVerticalFadingEdgeEnabled(boolean) 8464 * @attr ref android.R.styleable#View_fadingEdge 8465 */ 8466 public boolean isVerticalFadingEdgeEnabled() { 8467 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 8468 } 8469 8470 /** 8471 * <p>Define whether the vertical edges should be faded when this view 8472 * is scrolled vertically.</p> 8473 * 8474 * @param verticalFadingEdgeEnabled true if the vertical edges should 8475 * be faded when the view is scrolled 8476 * vertically 8477 * 8478 * @see #isVerticalFadingEdgeEnabled() 8479 * @attr ref android.R.styleable#View_fadingEdge 8480 */ 8481 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 8482 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 8483 if (verticalFadingEdgeEnabled) { 8484 initScrollCache(); 8485 } 8486 8487 mViewFlags ^= FADING_EDGE_VERTICAL; 8488 } 8489 } 8490 8491 /** 8492 * Returns the strength, or intensity, of the top faded edge. The strength is 8493 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 8494 * returns 0.0 or 1.0 but no value in between. 8495 * 8496 * Subclasses should override this method to provide a smoother fade transition 8497 * when scrolling occurs. 8498 * 8499 * @return the intensity of the top fade as a float between 0.0f and 1.0f 8500 */ 8501 protected float getTopFadingEdgeStrength() { 8502 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 8503 } 8504 8505 /** 8506 * Returns the strength, or intensity, of the bottom faded edge. The strength is 8507 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 8508 * returns 0.0 or 1.0 but no value in between. 8509 * 8510 * Subclasses should override this method to provide a smoother fade transition 8511 * when scrolling occurs. 8512 * 8513 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 8514 */ 8515 protected float getBottomFadingEdgeStrength() { 8516 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 8517 computeVerticalScrollRange() ? 1.0f : 0.0f; 8518 } 8519 8520 /** 8521 * Returns the strength, or intensity, of the left faded edge. The strength is 8522 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 8523 * returns 0.0 or 1.0 but no value in between. 8524 * 8525 * Subclasses should override this method to provide a smoother fade transition 8526 * when scrolling occurs. 8527 * 8528 * @return the intensity of the left fade as a float between 0.0f and 1.0f 8529 */ 8530 protected float getLeftFadingEdgeStrength() { 8531 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 8532 } 8533 8534 /** 8535 * Returns the strength, or intensity, of the right faded edge. The strength is 8536 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 8537 * returns 0.0 or 1.0 but no value in between. 8538 * 8539 * Subclasses should override this method to provide a smoother fade transition 8540 * when scrolling occurs. 8541 * 8542 * @return the intensity of the right fade as a float between 0.0f and 1.0f 8543 */ 8544 protected float getRightFadingEdgeStrength() { 8545 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 8546 computeHorizontalScrollRange() ? 1.0f : 0.0f; 8547 } 8548 8549 /** 8550 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 8551 * scrollbar is not drawn by default.</p> 8552 * 8553 * @return true if the horizontal scrollbar should be painted, false 8554 * otherwise 8555 * 8556 * @see #setHorizontalScrollBarEnabled(boolean) 8557 */ 8558 public boolean isHorizontalScrollBarEnabled() { 8559 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 8560 } 8561 8562 /** 8563 * <p>Define whether the horizontal scrollbar should be drawn or not. The 8564 * scrollbar is not drawn by default.</p> 8565 * 8566 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 8567 * be painted 8568 * 8569 * @see #isHorizontalScrollBarEnabled() 8570 */ 8571 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 8572 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 8573 mViewFlags ^= SCROLLBARS_HORIZONTAL; 8574 computeOpaqueFlags(); 8575 resolvePadding(); 8576 } 8577 } 8578 8579 /** 8580 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 8581 * scrollbar is not drawn by default.</p> 8582 * 8583 * @return true if the vertical scrollbar should be painted, false 8584 * otherwise 8585 * 8586 * @see #setVerticalScrollBarEnabled(boolean) 8587 */ 8588 public boolean isVerticalScrollBarEnabled() { 8589 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 8590 } 8591 8592 /** 8593 * <p>Define whether the vertical scrollbar should be drawn or not. The 8594 * scrollbar is not drawn by default.</p> 8595 * 8596 * @param verticalScrollBarEnabled true if the vertical scrollbar should 8597 * be painted 8598 * 8599 * @see #isVerticalScrollBarEnabled() 8600 */ 8601 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 8602 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 8603 mViewFlags ^= SCROLLBARS_VERTICAL; 8604 computeOpaqueFlags(); 8605 resolvePadding(); 8606 } 8607 } 8608 8609 /** 8610 * @hide 8611 */ 8612 protected void recomputePadding() { 8613 setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 8614 } 8615 8616 /** 8617 * Define whether scrollbars will fade when the view is not scrolling. 8618 * 8619 * @param fadeScrollbars wheter to enable fading 8620 * 8621 */ 8622 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 8623 initScrollCache(); 8624 final ScrollabilityCache scrollabilityCache = mScrollCache; 8625 scrollabilityCache.fadeScrollBars = fadeScrollbars; 8626 if (fadeScrollbars) { 8627 scrollabilityCache.state = ScrollabilityCache.OFF; 8628 } else { 8629 scrollabilityCache.state = ScrollabilityCache.ON; 8630 } 8631 } 8632 8633 /** 8634 * 8635 * Returns true if scrollbars will fade when this view is not scrolling 8636 * 8637 * @return true if scrollbar fading is enabled 8638 */ 8639 public boolean isScrollbarFadingEnabled() { 8640 return mScrollCache != null && mScrollCache.fadeScrollBars; 8641 } 8642 8643 /** 8644 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 8645 * inset. When inset, they add to the padding of the view. And the scrollbars 8646 * can be drawn inside the padding area or on the edge of the view. For example, 8647 * if a view has a background drawable and you want to draw the scrollbars 8648 * inside the padding specified by the drawable, you can use 8649 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 8650 * appear at the edge of the view, ignoring the padding, then you can use 8651 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 8652 * @param style the style of the scrollbars. Should be one of 8653 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 8654 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 8655 * @see #SCROLLBARS_INSIDE_OVERLAY 8656 * @see #SCROLLBARS_INSIDE_INSET 8657 * @see #SCROLLBARS_OUTSIDE_OVERLAY 8658 * @see #SCROLLBARS_OUTSIDE_INSET 8659 */ 8660 public void setScrollBarStyle(int style) { 8661 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 8662 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 8663 computeOpaqueFlags(); 8664 resolvePadding(); 8665 } 8666 } 8667 8668 /** 8669 * <p>Returns the current scrollbar style.</p> 8670 * @return the current scrollbar style 8671 * @see #SCROLLBARS_INSIDE_OVERLAY 8672 * @see #SCROLLBARS_INSIDE_INSET 8673 * @see #SCROLLBARS_OUTSIDE_OVERLAY 8674 * @see #SCROLLBARS_OUTSIDE_INSET 8675 */ 8676 public int getScrollBarStyle() { 8677 return mViewFlags & SCROLLBARS_STYLE_MASK; 8678 } 8679 8680 /** 8681 * <p>Compute the horizontal range that the horizontal scrollbar 8682 * represents.</p> 8683 * 8684 * <p>The range is expressed in arbitrary units that must be the same as the 8685 * units used by {@link #computeHorizontalScrollExtent()} and 8686 * {@link #computeHorizontalScrollOffset()}.</p> 8687 * 8688 * <p>The default range is the drawing width of this view.</p> 8689 * 8690 * @return the total horizontal range represented by the horizontal 8691 * scrollbar 8692 * 8693 * @see #computeHorizontalScrollExtent() 8694 * @see #computeHorizontalScrollOffset() 8695 * @see android.widget.ScrollBarDrawable 8696 */ 8697 protected int computeHorizontalScrollRange() { 8698 return getWidth(); 8699 } 8700 8701 /** 8702 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 8703 * within the horizontal range. This value is used to compute the position 8704 * of the thumb within the scrollbar's track.</p> 8705 * 8706 * <p>The range is expressed in arbitrary units that must be the same as the 8707 * units used by {@link #computeHorizontalScrollRange()} and 8708 * {@link #computeHorizontalScrollExtent()}.</p> 8709 * 8710 * <p>The default offset is the scroll offset of this view.</p> 8711 * 8712 * @return the horizontal offset of the scrollbar's thumb 8713 * 8714 * @see #computeHorizontalScrollRange() 8715 * @see #computeHorizontalScrollExtent() 8716 * @see android.widget.ScrollBarDrawable 8717 */ 8718 protected int computeHorizontalScrollOffset() { 8719 return mScrollX; 8720 } 8721 8722 /** 8723 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 8724 * within the horizontal range. This value is used to compute the length 8725 * of the thumb within the scrollbar's track.</p> 8726 * 8727 * <p>The range is expressed in arbitrary units that must be the same as the 8728 * units used by {@link #computeHorizontalScrollRange()} and 8729 * {@link #computeHorizontalScrollOffset()}.</p> 8730 * 8731 * <p>The default extent is the drawing width of this view.</p> 8732 * 8733 * @return the horizontal extent of the scrollbar's thumb 8734 * 8735 * @see #computeHorizontalScrollRange() 8736 * @see #computeHorizontalScrollOffset() 8737 * @see android.widget.ScrollBarDrawable 8738 */ 8739 protected int computeHorizontalScrollExtent() { 8740 return getWidth(); 8741 } 8742 8743 /** 8744 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 8745 * 8746 * <p>The range is expressed in arbitrary units that must be the same as the 8747 * units used by {@link #computeVerticalScrollExtent()} and 8748 * {@link #computeVerticalScrollOffset()}.</p> 8749 * 8750 * @return the total vertical range represented by the vertical scrollbar 8751 * 8752 * <p>The default range is the drawing height of this view.</p> 8753 * 8754 * @see #computeVerticalScrollExtent() 8755 * @see #computeVerticalScrollOffset() 8756 * @see android.widget.ScrollBarDrawable 8757 */ 8758 protected int computeVerticalScrollRange() { 8759 return getHeight(); 8760 } 8761 8762 /** 8763 * <p>Compute the vertical offset of the vertical scrollbar's thumb 8764 * within the horizontal range. This value is used to compute the position 8765 * of the thumb within the scrollbar's track.</p> 8766 * 8767 * <p>The range is expressed in arbitrary units that must be the same as the 8768 * units used by {@link #computeVerticalScrollRange()} and 8769 * {@link #computeVerticalScrollExtent()}.</p> 8770 * 8771 * <p>The default offset is the scroll offset of this view.</p> 8772 * 8773 * @return the vertical offset of the scrollbar's thumb 8774 * 8775 * @see #computeVerticalScrollRange() 8776 * @see #computeVerticalScrollExtent() 8777 * @see android.widget.ScrollBarDrawable 8778 */ 8779 protected int computeVerticalScrollOffset() { 8780 return mScrollY; 8781 } 8782 8783 /** 8784 * <p>Compute the vertical extent of the horizontal scrollbar's thumb 8785 * within the vertical range. This value is used to compute the length 8786 * of the thumb within the scrollbar's track.</p> 8787 * 8788 * <p>The range is expressed in arbitrary units that must be the same as the 8789 * units used by {@link #computeVerticalScrollRange()} and 8790 * {@link #computeVerticalScrollOffset()}.</p> 8791 * 8792 * <p>The default extent is the drawing height of this view.</p> 8793 * 8794 * @return the vertical extent of the scrollbar's thumb 8795 * 8796 * @see #computeVerticalScrollRange() 8797 * @see #computeVerticalScrollOffset() 8798 * @see android.widget.ScrollBarDrawable 8799 */ 8800 protected int computeVerticalScrollExtent() { 8801 return getHeight(); 8802 } 8803 8804 /** 8805 * Check if this view can be scrolled horizontally in a certain direction. 8806 * 8807 * @param direction Negative to check scrolling left, positive to check scrolling right. 8808 * @return true if this view can be scrolled in the specified direction, false otherwise. 8809 */ 8810 public boolean canScrollHorizontally(int direction) { 8811 final int offset = computeHorizontalScrollOffset(); 8812 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 8813 if (range == 0) return false; 8814 if (direction < 0) { 8815 return offset > 0; 8816 } else { 8817 return offset < range - 1; 8818 } 8819 } 8820 8821 /** 8822 * Check if this view can be scrolled vertically in a certain direction. 8823 * 8824 * @param direction Negative to check scrolling up, positive to check scrolling down. 8825 * @return true if this view can be scrolled in the specified direction, false otherwise. 8826 */ 8827 public boolean canScrollVertically(int direction) { 8828 final int offset = computeVerticalScrollOffset(); 8829 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 8830 if (range == 0) return false; 8831 if (direction < 0) { 8832 return offset > 0; 8833 } else { 8834 return offset < range - 1; 8835 } 8836 } 8837 8838 /** 8839 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 8840 * scrollbars are painted only if they have been awakened first.</p> 8841 * 8842 * @param canvas the canvas on which to draw the scrollbars 8843 * 8844 * @see #awakenScrollBars(int) 8845 */ 8846 protected final void onDrawScrollBars(Canvas canvas) { 8847 // scrollbars are drawn only when the animation is running 8848 final ScrollabilityCache cache = mScrollCache; 8849 if (cache != null) { 8850 8851 int state = cache.state; 8852 8853 if (state == ScrollabilityCache.OFF) { 8854 return; 8855 } 8856 8857 boolean invalidate = false; 8858 8859 if (state == ScrollabilityCache.FADING) { 8860 // We're fading -- get our fade interpolation 8861 if (cache.interpolatorValues == null) { 8862 cache.interpolatorValues = new float[1]; 8863 } 8864 8865 float[] values = cache.interpolatorValues; 8866 8867 // Stops the animation if we're done 8868 if (cache.scrollBarInterpolator.timeToValues(values) == 8869 Interpolator.Result.FREEZE_END) { 8870 cache.state = ScrollabilityCache.OFF; 8871 } else { 8872 cache.scrollBar.setAlpha(Math.round(values[0])); 8873 } 8874 8875 // This will make the scroll bars inval themselves after 8876 // drawing. We only want this when we're fading so that 8877 // we prevent excessive redraws 8878 invalidate = true; 8879 } else { 8880 // We're just on -- but we may have been fading before so 8881 // reset alpha 8882 cache.scrollBar.setAlpha(255); 8883 } 8884 8885 8886 final int viewFlags = mViewFlags; 8887 8888 final boolean drawHorizontalScrollBar = 8889 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 8890 final boolean drawVerticalScrollBar = 8891 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 8892 && !isVerticalScrollBarHidden(); 8893 8894 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 8895 final int width = mRight - mLeft; 8896 final int height = mBottom - mTop; 8897 8898 final ScrollBarDrawable scrollBar = cache.scrollBar; 8899 8900 final int scrollX = mScrollX; 8901 final int scrollY = mScrollY; 8902 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 8903 8904 int left, top, right, bottom; 8905 8906 if (drawHorizontalScrollBar) { 8907 int size = scrollBar.getSize(false); 8908 if (size <= 0) { 8909 size = cache.scrollBarSize; 8910 } 8911 8912 scrollBar.setParameters(computeHorizontalScrollRange(), 8913 computeHorizontalScrollOffset(), 8914 computeHorizontalScrollExtent(), false); 8915 final int verticalScrollBarGap = drawVerticalScrollBar ? 8916 getVerticalScrollbarWidth() : 0; 8917 top = scrollY + height - size - (mUserPaddingBottom & inside); 8918 left = scrollX + (mPaddingLeft & inside); 8919 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 8920 bottom = top + size; 8921 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 8922 if (invalidate) { 8923 invalidate(left, top, right, bottom); 8924 } 8925 } 8926 8927 if (drawVerticalScrollBar) { 8928 int size = scrollBar.getSize(true); 8929 if (size <= 0) { 8930 size = cache.scrollBarSize; 8931 } 8932 8933 scrollBar.setParameters(computeVerticalScrollRange(), 8934 computeVerticalScrollOffset(), 8935 computeVerticalScrollExtent(), true); 8936 switch (mVerticalScrollbarPosition) { 8937 default: 8938 case SCROLLBAR_POSITION_DEFAULT: 8939 case SCROLLBAR_POSITION_RIGHT: 8940 left = scrollX + width - size - (mUserPaddingRight & inside); 8941 break; 8942 case SCROLLBAR_POSITION_LEFT: 8943 left = scrollX + (mUserPaddingLeft & inside); 8944 break; 8945 } 8946 top = scrollY + (mPaddingTop & inside); 8947 right = left + size; 8948 bottom = scrollY + height - (mUserPaddingBottom & inside); 8949 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 8950 if (invalidate) { 8951 invalidate(left, top, right, bottom); 8952 } 8953 } 8954 } 8955 } 8956 } 8957 8958 /** 8959 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 8960 * FastScroller is visible. 8961 * @return whether to temporarily hide the vertical scrollbar 8962 * @hide 8963 */ 8964 protected boolean isVerticalScrollBarHidden() { 8965 return false; 8966 } 8967 8968 /** 8969 * <p>Draw the horizontal scrollbar if 8970 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 8971 * 8972 * @param canvas the canvas on which to draw the scrollbar 8973 * @param scrollBar the scrollbar's drawable 8974 * 8975 * @see #isHorizontalScrollBarEnabled() 8976 * @see #computeHorizontalScrollRange() 8977 * @see #computeHorizontalScrollExtent() 8978 * @see #computeHorizontalScrollOffset() 8979 * @see android.widget.ScrollBarDrawable 8980 * @hide 8981 */ 8982 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 8983 int l, int t, int r, int b) { 8984 scrollBar.setBounds(l, t, r, b); 8985 scrollBar.draw(canvas); 8986 } 8987 8988 /** 8989 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 8990 * returns true.</p> 8991 * 8992 * @param canvas the canvas on which to draw the scrollbar 8993 * @param scrollBar the scrollbar's drawable 8994 * 8995 * @see #isVerticalScrollBarEnabled() 8996 * @see #computeVerticalScrollRange() 8997 * @see #computeVerticalScrollExtent() 8998 * @see #computeVerticalScrollOffset() 8999 * @see android.widget.ScrollBarDrawable 9000 * @hide 9001 */ 9002 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 9003 int l, int t, int r, int b) { 9004 scrollBar.setBounds(l, t, r, b); 9005 scrollBar.draw(canvas); 9006 } 9007 9008 /** 9009 * Implement this to do your drawing. 9010 * 9011 * @param canvas the canvas on which the background will be drawn 9012 */ 9013 protected void onDraw(Canvas canvas) { 9014 } 9015 9016 /* 9017 * Caller is responsible for calling requestLayout if necessary. 9018 * (This allows addViewInLayout to not request a new layout.) 9019 */ 9020 void assignParent(ViewParent parent) { 9021 if (mParent == null) { 9022 mParent = parent; 9023 } else if (parent == null) { 9024 mParent = null; 9025 } else { 9026 throw new RuntimeException("view " + this + " being added, but" 9027 + " it already has a parent"); 9028 } 9029 } 9030 9031 /** 9032 * This is called when the view is attached to a window. At this point it 9033 * has a Surface and will start drawing. Note that this function is 9034 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 9035 * however it may be called any time before the first onDraw -- including 9036 * before or after {@link #onMeasure(int, int)}. 9037 * 9038 * @see #onDetachedFromWindow() 9039 */ 9040 protected void onAttachedToWindow() { 9041 if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) { 9042 mParent.requestTransparentRegion(this); 9043 } 9044 if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 9045 initialAwakenScrollBars(); 9046 mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH; 9047 } 9048 jumpDrawablesToCurrentState(); 9049 resolveLayoutDirectionIfNeeded(); 9050 resolvePadding(); 9051 resolveTextDirection(); 9052 if (isFocused()) { 9053 InputMethodManager imm = InputMethodManager.peekInstance(); 9054 imm.focusIn(this); 9055 } 9056 } 9057 9058 /** 9059 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 9060 * that the parent directionality can and will be resolved before its children. 9061 */ 9062 private void resolveLayoutDirectionIfNeeded() { 9063 // Do not resolve if it is not needed 9064 if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) == LAYOUT_DIRECTION_RESOLVED) return; 9065 9066 // Clear any previous layout direction resolution 9067 mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_RTL; 9068 9069 // Set resolved depending on layout direction 9070 switch (getLayoutDirection()) { 9071 case LAYOUT_DIRECTION_INHERIT: 9072 // We cannot do the resolution if there is no parent 9073 if (mParent == null) return; 9074 9075 // If this is root view, no need to look at parent's layout dir. 9076 if (mParent instanceof ViewGroup) { 9077 ViewGroup viewGroup = ((ViewGroup) mParent); 9078 9079 // Check if the parent view group can resolve 9080 if (! viewGroup.canResolveLayoutDirection()) { 9081 return; 9082 } 9083 if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) { 9084 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL; 9085 } 9086 } 9087 break; 9088 case LAYOUT_DIRECTION_RTL: 9089 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL; 9090 break; 9091 case LAYOUT_DIRECTION_LOCALE: 9092 if(isLayoutDirectionRtl(Locale.getDefault())) { 9093 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL; 9094 } 9095 break; 9096 default: 9097 // Nothing to do, LTR by default 9098 } 9099 9100 // Set to resolved 9101 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED; 9102 } 9103 9104 private void resolvePadding() { 9105 // If the user specified the absolute padding (either with android:padding or 9106 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise 9107 // use the default padding or the padding from the background drawable 9108 // (stored at this point in mPadding*) 9109 switch (getResolvedLayoutDirection()) { 9110 case LAYOUT_DIRECTION_RTL: 9111 // Start user padding override Right user padding. Otherwise, if Right user 9112 // padding is not defined, use the default Right padding. If Right user padding 9113 // is defined, just use it. 9114 if (mUserPaddingStart >= 0) { 9115 mUserPaddingRight = mUserPaddingStart; 9116 } else if (mUserPaddingRight < 0) { 9117 mUserPaddingRight = mPaddingRight; 9118 } 9119 if (mUserPaddingEnd >= 0) { 9120 mUserPaddingLeft = mUserPaddingEnd; 9121 } else if (mUserPaddingLeft < 0) { 9122 mUserPaddingLeft = mPaddingLeft; 9123 } 9124 break; 9125 case LAYOUT_DIRECTION_LTR: 9126 default: 9127 // Start user padding override Left user padding. Otherwise, if Left user 9128 // padding is not defined, use the default left padding. If Left user padding 9129 // is defined, just use it. 9130 if (mUserPaddingStart >= 0) { 9131 mUserPaddingLeft = mUserPaddingStart; 9132 } else if (mUserPaddingLeft < 0) { 9133 mUserPaddingLeft = mPaddingLeft; 9134 } 9135 if (mUserPaddingEnd >= 0) { 9136 mUserPaddingRight = mUserPaddingEnd; 9137 } else if (mUserPaddingRight < 0) { 9138 mUserPaddingRight = mPaddingRight; 9139 } 9140 } 9141 9142 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 9143 9144 recomputePadding(); 9145 } 9146 9147 protected boolean canResolveLayoutDirection() { 9148 switch (getLayoutDirection()) { 9149 case LAYOUT_DIRECTION_INHERIT: 9150 return (mParent != null); 9151 default: 9152 return true; 9153 } 9154 } 9155 9156 /** 9157 * Reset the resolved layout direction. 9158 * 9159 * Subclasses need to override this method to clear cached information that depends on the 9160 * resolved layout direction, or to inform child views that inherit their layout direction. 9161 * Overrides must also call the superclass implementation at the start of their implementation. 9162 * 9163 * @hide 9164 */ 9165 protected void resetResolvedLayoutDirection() { 9166 // Reset the current View resolution 9167 mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED; 9168 } 9169 9170 /** 9171 * Check if a Locale is corresponding to a RTL script. 9172 * 9173 * @param locale Locale to check 9174 * @return true if a Locale is corresponding to a RTL script. 9175 */ 9176 protected static boolean isLayoutDirectionRtl(Locale locale) { 9177 return (LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE == 9178 LocaleUtil.getLayoutDirectionFromLocale(locale)); 9179 } 9180 9181 /** 9182 * This is called when the view is detached from a window. At this point it 9183 * no longer has a surface for drawing. 9184 * 9185 * @see #onAttachedToWindow() 9186 */ 9187 protected void onDetachedFromWindow() { 9188 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT; 9189 9190 removeUnsetPressCallback(); 9191 removeLongPressCallback(); 9192 removePerformClickCallback(); 9193 removeSendViewScrolledAccessibilityEventCallback(); 9194 9195 destroyDrawingCache(); 9196 9197 if (mHardwareLayer != null) { 9198 mHardwareLayer.destroy(); 9199 mHardwareLayer = null; 9200 } 9201 9202 if (mDisplayList != null) { 9203 mDisplayList.invalidate(); 9204 } 9205 9206 if (mAttachInfo != null) { 9207 mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_MSG, this); 9208 mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_RECT_MSG, this); 9209 } 9210 9211 mCurrentAnimation = null; 9212 9213 resetResolvedLayoutDirection(); 9214 resetResolvedTextDirection(); 9215 } 9216 9217 /** 9218 * @return The number of times this view has been attached to a window 9219 */ 9220 protected int getWindowAttachCount() { 9221 return mWindowAttachCount; 9222 } 9223 9224 /** 9225 * Retrieve a unique token identifying the window this view is attached to. 9226 * @return Return the window's token for use in 9227 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 9228 */ 9229 public IBinder getWindowToken() { 9230 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 9231 } 9232 9233 /** 9234 * Retrieve a unique token identifying the top-level "real" window of 9235 * the window that this view is attached to. That is, this is like 9236 * {@link #getWindowToken}, except if the window this view in is a panel 9237 * window (attached to another containing window), then the token of 9238 * the containing window is returned instead. 9239 * 9240 * @return Returns the associated window token, either 9241 * {@link #getWindowToken()} or the containing window's token. 9242 */ 9243 public IBinder getApplicationWindowToken() { 9244 AttachInfo ai = mAttachInfo; 9245 if (ai != null) { 9246 IBinder appWindowToken = ai.mPanelParentWindowToken; 9247 if (appWindowToken == null) { 9248 appWindowToken = ai.mWindowToken; 9249 } 9250 return appWindowToken; 9251 } 9252 return null; 9253 } 9254 9255 /** 9256 * Retrieve private session object this view hierarchy is using to 9257 * communicate with the window manager. 9258 * @return the session object to communicate with the window manager 9259 */ 9260 /*package*/ IWindowSession getWindowSession() { 9261 return mAttachInfo != null ? mAttachInfo.mSession : null; 9262 } 9263 9264 /** 9265 * @param info the {@link android.view.View.AttachInfo} to associated with 9266 * this view 9267 */ 9268 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 9269 //System.out.println("Attached! " + this); 9270 mAttachInfo = info; 9271 mWindowAttachCount++; 9272 // We will need to evaluate the drawable state at least once. 9273 mPrivateFlags |= DRAWABLE_STATE_DIRTY; 9274 if (mFloatingTreeObserver != null) { 9275 info.mTreeObserver.merge(mFloatingTreeObserver); 9276 mFloatingTreeObserver = null; 9277 } 9278 if ((mPrivateFlags&SCROLL_CONTAINER) != 0) { 9279 mAttachInfo.mScrollContainers.add(this); 9280 mPrivateFlags |= SCROLL_CONTAINER_ADDED; 9281 } 9282 performCollectViewAttributes(visibility); 9283 onAttachedToWindow(); 9284 9285 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 9286 mOnAttachStateChangeListeners; 9287 if (listeners != null && listeners.size() > 0) { 9288 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 9289 // perform the dispatching. The iterator is a safe guard against listeners that 9290 // could mutate the list by calling the various add/remove methods. This prevents 9291 // the array from being modified while we iterate it. 9292 for (OnAttachStateChangeListener listener : listeners) { 9293 listener.onViewAttachedToWindow(this); 9294 } 9295 } 9296 9297 int vis = info.mWindowVisibility; 9298 if (vis != GONE) { 9299 onWindowVisibilityChanged(vis); 9300 } 9301 if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) { 9302 // If nobody has evaluated the drawable state yet, then do it now. 9303 refreshDrawableState(); 9304 } 9305 } 9306 9307 void dispatchDetachedFromWindow() { 9308 AttachInfo info = mAttachInfo; 9309 if (info != null) { 9310 int vis = info.mWindowVisibility; 9311 if (vis != GONE) { 9312 onWindowVisibilityChanged(GONE); 9313 } 9314 } 9315 9316 onDetachedFromWindow(); 9317 9318 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 9319 mOnAttachStateChangeListeners; 9320 if (listeners != null && listeners.size() > 0) { 9321 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 9322 // perform the dispatching. The iterator is a safe guard against listeners that 9323 // could mutate the list by calling the various add/remove methods. This prevents 9324 // the array from being modified while we iterate it. 9325 for (OnAttachStateChangeListener listener : listeners) { 9326 listener.onViewDetachedFromWindow(this); 9327 } 9328 } 9329 9330 if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) { 9331 mAttachInfo.mScrollContainers.remove(this); 9332 mPrivateFlags &= ~SCROLL_CONTAINER_ADDED; 9333 } 9334 9335 mAttachInfo = null; 9336 } 9337 9338 /** 9339 * Store this view hierarchy's frozen state into the given container. 9340 * 9341 * @param container The SparseArray in which to save the view's state. 9342 * 9343 * @see #restoreHierarchyState(android.util.SparseArray) 9344 * @see #dispatchSaveInstanceState(android.util.SparseArray) 9345 * @see #onSaveInstanceState() 9346 */ 9347 public void saveHierarchyState(SparseArray<Parcelable> container) { 9348 dispatchSaveInstanceState(container); 9349 } 9350 9351 /** 9352 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 9353 * this view and its children. May be overridden to modify how freezing happens to a 9354 * view's children; for example, some views may want to not store state for their children. 9355 * 9356 * @param container The SparseArray in which to save the view's state. 9357 * 9358 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 9359 * @see #saveHierarchyState(android.util.SparseArray) 9360 * @see #onSaveInstanceState() 9361 */ 9362 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 9363 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 9364 mPrivateFlags &= ~SAVE_STATE_CALLED; 9365 Parcelable state = onSaveInstanceState(); 9366 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) { 9367 throw new IllegalStateException( 9368 "Derived class did not call super.onSaveInstanceState()"); 9369 } 9370 if (state != null) { 9371 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 9372 // + ": " + state); 9373 container.put(mID, state); 9374 } 9375 } 9376 } 9377 9378 /** 9379 * Hook allowing a view to generate a representation of its internal state 9380 * that can later be used to create a new instance with that same state. 9381 * This state should only contain information that is not persistent or can 9382 * not be reconstructed later. For example, you will never store your 9383 * current position on screen because that will be computed again when a 9384 * new instance of the view is placed in its view hierarchy. 9385 * <p> 9386 * Some examples of things you may store here: the current cursor position 9387 * in a text view (but usually not the text itself since that is stored in a 9388 * content provider or other persistent storage), the currently selected 9389 * item in a list view. 9390 * 9391 * @return Returns a Parcelable object containing the view's current dynamic 9392 * state, or null if there is nothing interesting to save. The 9393 * default implementation returns null. 9394 * @see #onRestoreInstanceState(android.os.Parcelable) 9395 * @see #saveHierarchyState(android.util.SparseArray) 9396 * @see #dispatchSaveInstanceState(android.util.SparseArray) 9397 * @see #setSaveEnabled(boolean) 9398 */ 9399 protected Parcelable onSaveInstanceState() { 9400 mPrivateFlags |= SAVE_STATE_CALLED; 9401 return BaseSavedState.EMPTY_STATE; 9402 } 9403 9404 /** 9405 * Restore this view hierarchy's frozen state from the given container. 9406 * 9407 * @param container The SparseArray which holds previously frozen states. 9408 * 9409 * @see #saveHierarchyState(android.util.SparseArray) 9410 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 9411 * @see #onRestoreInstanceState(android.os.Parcelable) 9412 */ 9413 public void restoreHierarchyState(SparseArray<Parcelable> container) { 9414 dispatchRestoreInstanceState(container); 9415 } 9416 9417 /** 9418 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 9419 * state for this view and its children. May be overridden to modify how restoring 9420 * happens to a view's children; for example, some views may want to not store state 9421 * for their children. 9422 * 9423 * @param container The SparseArray which holds previously saved state. 9424 * 9425 * @see #dispatchSaveInstanceState(android.util.SparseArray) 9426 * @see #restoreHierarchyState(android.util.SparseArray) 9427 * @see #onRestoreInstanceState(android.os.Parcelable) 9428 */ 9429 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 9430 if (mID != NO_ID) { 9431 Parcelable state = container.get(mID); 9432 if (state != null) { 9433 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 9434 // + ": " + state); 9435 mPrivateFlags &= ~SAVE_STATE_CALLED; 9436 onRestoreInstanceState(state); 9437 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) { 9438 throw new IllegalStateException( 9439 "Derived class did not call super.onRestoreInstanceState()"); 9440 } 9441 } 9442 } 9443 } 9444 9445 /** 9446 * Hook allowing a view to re-apply a representation of its internal state that had previously 9447 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 9448 * null state. 9449 * 9450 * @param state The frozen state that had previously been returned by 9451 * {@link #onSaveInstanceState}. 9452 * 9453 * @see #onSaveInstanceState() 9454 * @see #restoreHierarchyState(android.util.SparseArray) 9455 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 9456 */ 9457 protected void onRestoreInstanceState(Parcelable state) { 9458 mPrivateFlags |= SAVE_STATE_CALLED; 9459 if (state != BaseSavedState.EMPTY_STATE && state != null) { 9460 throw new IllegalArgumentException("Wrong state class, expecting View State but " 9461 + "received " + state.getClass().toString() + " instead. This usually happens " 9462 + "when two views of different type have the same id in the same hierarchy. " 9463 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 9464 + "other views do not use the same id."); 9465 } 9466 } 9467 9468 /** 9469 * <p>Return the time at which the drawing of the view hierarchy started.</p> 9470 * 9471 * @return the drawing start time in milliseconds 9472 */ 9473 public long getDrawingTime() { 9474 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 9475 } 9476 9477 /** 9478 * <p>Enables or disables the duplication of the parent's state into this view. When 9479 * duplication is enabled, this view gets its drawable state from its parent rather 9480 * than from its own internal properties.</p> 9481 * 9482 * <p>Note: in the current implementation, setting this property to true after the 9483 * view was added to a ViewGroup might have no effect at all. This property should 9484 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 9485 * 9486 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 9487 * property is enabled, an exception will be thrown.</p> 9488 * 9489 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 9490 * parent, these states should not be affected by this method.</p> 9491 * 9492 * @param enabled True to enable duplication of the parent's drawable state, false 9493 * to disable it. 9494 * 9495 * @see #getDrawableState() 9496 * @see #isDuplicateParentStateEnabled() 9497 */ 9498 public void setDuplicateParentStateEnabled(boolean enabled) { 9499 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 9500 } 9501 9502 /** 9503 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 9504 * 9505 * @return True if this view's drawable state is duplicated from the parent, 9506 * false otherwise 9507 * 9508 * @see #getDrawableState() 9509 * @see #setDuplicateParentStateEnabled(boolean) 9510 */ 9511 public boolean isDuplicateParentStateEnabled() { 9512 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 9513 } 9514 9515 /** 9516 * <p>Specifies the type of layer backing this view. The layer can be 9517 * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or 9518 * {@link #LAYER_TYPE_HARDWARE hardware}.</p> 9519 * 9520 * <p>A layer is associated with an optional {@link android.graphics.Paint} 9521 * instance that controls how the layer is composed on screen. The following 9522 * properties of the paint are taken into account when composing the layer:</p> 9523 * <ul> 9524 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 9525 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 9526 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 9527 * </ul> 9528 * 9529 * <p>If this view has an alpha value set to < 1.0 by calling 9530 * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by 9531 * this view's alpha value. Calling {@link #setAlpha(float)} is therefore 9532 * equivalent to setting a hardware layer on this view and providing a paint with 9533 * the desired alpha value.<p> 9534 * 9535 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled}, 9536 * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware} 9537 * for more information on when and how to use layers.</p> 9538 * 9539 * @param layerType The ype of layer to use with this view, must be one of 9540 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 9541 * {@link #LAYER_TYPE_HARDWARE} 9542 * @param paint The paint used to compose the layer. This argument is optional 9543 * and can be null. It is ignored when the layer type is 9544 * {@link #LAYER_TYPE_NONE} 9545 * 9546 * @see #getLayerType() 9547 * @see #LAYER_TYPE_NONE 9548 * @see #LAYER_TYPE_SOFTWARE 9549 * @see #LAYER_TYPE_HARDWARE 9550 * @see #setAlpha(float) 9551 * 9552 * @attr ref android.R.styleable#View_layerType 9553 */ 9554 public void setLayerType(int layerType, Paint paint) { 9555 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 9556 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 9557 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 9558 } 9559 9560 if (layerType == mLayerType) { 9561 if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) { 9562 mLayerPaint = paint == null ? new Paint() : paint; 9563 invalidateParentCaches(); 9564 invalidate(true); 9565 } 9566 return; 9567 } 9568 9569 // Destroy any previous software drawing cache if needed 9570 switch (mLayerType) { 9571 case LAYER_TYPE_HARDWARE: 9572 if (mHardwareLayer != null) { 9573 mHardwareLayer.destroy(); 9574 mHardwareLayer = null; 9575 } 9576 // fall through - unaccelerated views may use software layer mechanism instead 9577 case LAYER_TYPE_SOFTWARE: 9578 if (mDrawingCache != null) { 9579 mDrawingCache.recycle(); 9580 mDrawingCache = null; 9581 } 9582 9583 if (mUnscaledDrawingCache != null) { 9584 mUnscaledDrawingCache.recycle(); 9585 mUnscaledDrawingCache = null; 9586 } 9587 break; 9588 default: 9589 break; 9590 } 9591 9592 mLayerType = layerType; 9593 final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE; 9594 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 9595 mLocalDirtyRect = layerDisabled ? null : new Rect(); 9596 9597 invalidateParentCaches(); 9598 invalidate(true); 9599 } 9600 9601 /** 9602 * Indicates what type of layer is currently associated with this view. By default 9603 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 9604 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 9605 * for more information on the different types of layers. 9606 * 9607 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 9608 * {@link #LAYER_TYPE_HARDWARE} 9609 * 9610 * @see #setLayerType(int, android.graphics.Paint) 9611 * @see #buildLayer() 9612 * @see #LAYER_TYPE_NONE 9613 * @see #LAYER_TYPE_SOFTWARE 9614 * @see #LAYER_TYPE_HARDWARE 9615 */ 9616 public int getLayerType() { 9617 return mLayerType; 9618 } 9619 9620 /** 9621 * Forces this view's layer to be created and this view to be rendered 9622 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 9623 * invoking this method will have no effect. 9624 * 9625 * This method can for instance be used to render a view into its layer before 9626 * starting an animation. If this view is complex, rendering into the layer 9627 * before starting the animation will avoid skipping frames. 9628 * 9629 * @throws IllegalStateException If this view is not attached to a window 9630 * 9631 * @see #setLayerType(int, android.graphics.Paint) 9632 */ 9633 public void buildLayer() { 9634 if (mLayerType == LAYER_TYPE_NONE) return; 9635 9636 if (mAttachInfo == null) { 9637 throw new IllegalStateException("This view must be attached to a window first"); 9638 } 9639 9640 switch (mLayerType) { 9641 case LAYER_TYPE_HARDWARE: 9642 getHardwareLayer(); 9643 break; 9644 case LAYER_TYPE_SOFTWARE: 9645 buildDrawingCache(true); 9646 break; 9647 } 9648 } 9649 9650 /** 9651 * <p>Returns a hardware layer that can be used to draw this view again 9652 * without executing its draw method.</p> 9653 * 9654 * @return A HardwareLayer ready to render, or null if an error occurred. 9655 */ 9656 HardwareLayer getHardwareLayer() { 9657 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null) { 9658 return null; 9659 } 9660 9661 final int width = mRight - mLeft; 9662 final int height = mBottom - mTop; 9663 9664 if (width == 0 || height == 0) { 9665 return null; 9666 } 9667 9668 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) { 9669 if (mHardwareLayer == null) { 9670 mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer( 9671 width, height, isOpaque()); 9672 mLocalDirtyRect.setEmpty(); 9673 } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) { 9674 mHardwareLayer.resize(width, height); 9675 mLocalDirtyRect.setEmpty(); 9676 } 9677 9678 HardwareCanvas currentCanvas = mAttachInfo.mHardwareCanvas; 9679 final HardwareCanvas canvas = mHardwareLayer.start(currentCanvas); 9680 mAttachInfo.mHardwareCanvas = canvas; 9681 try { 9682 canvas.setViewport(width, height); 9683 canvas.onPreDraw(mLocalDirtyRect); 9684 mLocalDirtyRect.setEmpty(); 9685 9686 final int restoreCount = canvas.save(); 9687 9688 computeScroll(); 9689 canvas.translate(-mScrollX, -mScrollY); 9690 9691 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 9692 9693 // Fast path for layouts with no backgrounds 9694 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 9695 mPrivateFlags &= ~DIRTY_MASK; 9696 dispatchDraw(canvas); 9697 } else { 9698 draw(canvas); 9699 } 9700 9701 canvas.restoreToCount(restoreCount); 9702 } finally { 9703 canvas.onPostDraw(); 9704 mHardwareLayer.end(currentCanvas); 9705 mAttachInfo.mHardwareCanvas = currentCanvas; 9706 } 9707 } 9708 9709 return mHardwareLayer; 9710 } 9711 9712 /** 9713 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 9714 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 9715 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 9716 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 9717 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 9718 * null.</p> 9719 * 9720 * <p>Enabling the drawing cache is similar to 9721 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 9722 * acceleration is turned off. When hardware acceleration is turned on, enabling the 9723 * drawing cache has no effect on rendering because the system uses a different mechanism 9724 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 9725 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 9726 * for information on how to enable software and hardware layers.</p> 9727 * 9728 * <p>This API can be used to manually generate 9729 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 9730 * {@link #getDrawingCache()}.</p> 9731 * 9732 * @param enabled true to enable the drawing cache, false otherwise 9733 * 9734 * @see #isDrawingCacheEnabled() 9735 * @see #getDrawingCache() 9736 * @see #buildDrawingCache() 9737 * @see #setLayerType(int, android.graphics.Paint) 9738 */ 9739 public void setDrawingCacheEnabled(boolean enabled) { 9740 mCachingFailed = false; 9741 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 9742 } 9743 9744 /** 9745 * <p>Indicates whether the drawing cache is enabled for this view.</p> 9746 * 9747 * @return true if the drawing cache is enabled 9748 * 9749 * @see #setDrawingCacheEnabled(boolean) 9750 * @see #getDrawingCache() 9751 */ 9752 @ViewDebug.ExportedProperty(category = "drawing") 9753 public boolean isDrawingCacheEnabled() { 9754 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 9755 } 9756 9757 /** 9758 * Debugging utility which recursively outputs the dirty state of a view and its 9759 * descendants. 9760 * 9761 * @hide 9762 */ 9763 @SuppressWarnings({"UnusedDeclaration"}) 9764 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 9765 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) + 9766 ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" + 9767 (mPrivateFlags & View.DRAWING_CACHE_VALID) + 9768 ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")"); 9769 if (clear) { 9770 mPrivateFlags &= clearMask; 9771 } 9772 if (this instanceof ViewGroup) { 9773 ViewGroup parent = (ViewGroup) this; 9774 final int count = parent.getChildCount(); 9775 for (int i = 0; i < count; i++) { 9776 final View child = parent.getChildAt(i); 9777 child.outputDirtyFlags(indent + " ", clear, clearMask); 9778 } 9779 } 9780 } 9781 9782 /** 9783 * This method is used by ViewGroup to cause its children to restore or recreate their 9784 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 9785 * to recreate its own display list, which would happen if it went through the normal 9786 * draw/dispatchDraw mechanisms. 9787 * 9788 * @hide 9789 */ 9790 protected void dispatchGetDisplayList() {} 9791 9792 /** 9793 * A view that is not attached or hardware accelerated cannot create a display list. 9794 * This method checks these conditions and returns the appropriate result. 9795 * 9796 * @return true if view has the ability to create a display list, false otherwise. 9797 * 9798 * @hide 9799 */ 9800 public boolean canHaveDisplayList() { 9801 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 9802 } 9803 9804 /** 9805 * <p>Returns a display list that can be used to draw this view again 9806 * without executing its draw method.</p> 9807 * 9808 * @return A DisplayList ready to replay, or null if caching is not enabled. 9809 * 9810 * @hide 9811 */ 9812 public DisplayList getDisplayList() { 9813 if (!canHaveDisplayList()) { 9814 return null; 9815 } 9816 9817 if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || 9818 mDisplayList == null || !mDisplayList.isValid() || 9819 mRecreateDisplayList)) { 9820 // Don't need to recreate the display list, just need to tell our 9821 // children to restore/recreate theirs 9822 if (mDisplayList != null && mDisplayList.isValid() && 9823 !mRecreateDisplayList) { 9824 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 9825 mPrivateFlags &= ~DIRTY_MASK; 9826 dispatchGetDisplayList(); 9827 9828 return mDisplayList; 9829 } 9830 9831 // If we got here, we're recreating it. Mark it as such to ensure that 9832 // we copy in child display lists into ours in drawChild() 9833 mRecreateDisplayList = true; 9834 if (mDisplayList == null) { 9835 mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList(this); 9836 // If we're creating a new display list, make sure our parent gets invalidated 9837 // since they will need to recreate their display list to account for this 9838 // new child display list. 9839 invalidateParentCaches(); 9840 } 9841 9842 final HardwareCanvas canvas = mDisplayList.start(); 9843 try { 9844 int width = mRight - mLeft; 9845 int height = mBottom - mTop; 9846 9847 canvas.setViewport(width, height); 9848 // The dirty rect should always be null for a display list 9849 canvas.onPreDraw(null); 9850 9851 final int restoreCount = canvas.save(); 9852 9853 computeScroll(); 9854 canvas.translate(-mScrollX, -mScrollY); 9855 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 9856 mPrivateFlags &= ~DIRTY_MASK; 9857 9858 // Fast path for layouts with no backgrounds 9859 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 9860 dispatchDraw(canvas); 9861 } else { 9862 draw(canvas); 9863 } 9864 9865 canvas.restoreToCount(restoreCount); 9866 } finally { 9867 canvas.onPostDraw(); 9868 9869 mDisplayList.end(); 9870 } 9871 } else { 9872 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 9873 mPrivateFlags &= ~DIRTY_MASK; 9874 } 9875 9876 return mDisplayList; 9877 } 9878 9879 /** 9880 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 9881 * 9882 * @return A non-scaled bitmap representing this view or null if cache is disabled. 9883 * 9884 * @see #getDrawingCache(boolean) 9885 */ 9886 public Bitmap getDrawingCache() { 9887 return getDrawingCache(false); 9888 } 9889 9890 /** 9891 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 9892 * is null when caching is disabled. If caching is enabled and the cache is not ready, 9893 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 9894 * draw from the cache when the cache is enabled. To benefit from the cache, you must 9895 * request the drawing cache by calling this method and draw it on screen if the 9896 * returned bitmap is not null.</p> 9897 * 9898 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 9899 * this method will create a bitmap of the same size as this view. Because this bitmap 9900 * will be drawn scaled by the parent ViewGroup, the result on screen might show 9901 * scaling artifacts. To avoid such artifacts, you should call this method by setting 9902 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 9903 * size than the view. This implies that your application must be able to handle this 9904 * size.</p> 9905 * 9906 * @param autoScale Indicates whether the generated bitmap should be scaled based on 9907 * the current density of the screen when the application is in compatibility 9908 * mode. 9909 * 9910 * @return A bitmap representing this view or null if cache is disabled. 9911 * 9912 * @see #setDrawingCacheEnabled(boolean) 9913 * @see #isDrawingCacheEnabled() 9914 * @see #buildDrawingCache(boolean) 9915 * @see #destroyDrawingCache() 9916 */ 9917 public Bitmap getDrawingCache(boolean autoScale) { 9918 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 9919 return null; 9920 } 9921 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 9922 buildDrawingCache(autoScale); 9923 } 9924 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 9925 } 9926 9927 /** 9928 * <p>Frees the resources used by the drawing cache. If you call 9929 * {@link #buildDrawingCache()} manually without calling 9930 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 9931 * should cleanup the cache with this method afterwards.</p> 9932 * 9933 * @see #setDrawingCacheEnabled(boolean) 9934 * @see #buildDrawingCache() 9935 * @see #getDrawingCache() 9936 */ 9937 public void destroyDrawingCache() { 9938 if (mDrawingCache != null) { 9939 mDrawingCache.recycle(); 9940 mDrawingCache = null; 9941 } 9942 if (mUnscaledDrawingCache != null) { 9943 mUnscaledDrawingCache.recycle(); 9944 mUnscaledDrawingCache = null; 9945 } 9946 } 9947 9948 /** 9949 * Setting a solid background color for the drawing cache's bitmaps will improve 9950 * perfromance and memory usage. Note, though that this should only be used if this 9951 * view will always be drawn on top of a solid color. 9952 * 9953 * @param color The background color to use for the drawing cache's bitmap 9954 * 9955 * @see #setDrawingCacheEnabled(boolean) 9956 * @see #buildDrawingCache() 9957 * @see #getDrawingCache() 9958 */ 9959 public void setDrawingCacheBackgroundColor(int color) { 9960 if (color != mDrawingCacheBackgroundColor) { 9961 mDrawingCacheBackgroundColor = color; 9962 mPrivateFlags &= ~DRAWING_CACHE_VALID; 9963 } 9964 } 9965 9966 /** 9967 * @see #setDrawingCacheBackgroundColor(int) 9968 * 9969 * @return The background color to used for the drawing cache's bitmap 9970 */ 9971 public int getDrawingCacheBackgroundColor() { 9972 return mDrawingCacheBackgroundColor; 9973 } 9974 9975 /** 9976 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 9977 * 9978 * @see #buildDrawingCache(boolean) 9979 */ 9980 public void buildDrawingCache() { 9981 buildDrawingCache(false); 9982 } 9983 9984 /** 9985 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 9986 * 9987 * <p>If you call {@link #buildDrawingCache()} manually without calling 9988 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 9989 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 9990 * 9991 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 9992 * this method will create a bitmap of the same size as this view. Because this bitmap 9993 * will be drawn scaled by the parent ViewGroup, the result on screen might show 9994 * scaling artifacts. To avoid such artifacts, you should call this method by setting 9995 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 9996 * size than the view. This implies that your application must be able to handle this 9997 * size.</p> 9998 * 9999 * <p>You should avoid calling this method when hardware acceleration is enabled. If 10000 * you do not need the drawing cache bitmap, calling this method will increase memory 10001 * usage and cause the view to be rendered in software once, thus negatively impacting 10002 * performance.</p> 10003 * 10004 * @see #getDrawingCache() 10005 * @see #destroyDrawingCache() 10006 */ 10007 public void buildDrawingCache(boolean autoScale) { 10008 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ? 10009 mDrawingCache == null : mUnscaledDrawingCache == null)) { 10010 mCachingFailed = false; 10011 10012 if (ViewDebug.TRACE_HIERARCHY) { 10013 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE); 10014 } 10015 10016 int width = mRight - mLeft; 10017 int height = mBottom - mTop; 10018 10019 final AttachInfo attachInfo = mAttachInfo; 10020 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 10021 10022 if (autoScale && scalingRequired) { 10023 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 10024 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 10025 } 10026 10027 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 10028 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 10029 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 10030 10031 if (width <= 0 || height <= 0 || 10032 // Projected bitmap size in bytes 10033 (width * height * (opaque && !use32BitCache ? 2 : 4) > 10034 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) { 10035 destroyDrawingCache(); 10036 mCachingFailed = true; 10037 return; 10038 } 10039 10040 boolean clear = true; 10041 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 10042 10043 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 10044 Bitmap.Config quality; 10045 if (!opaque) { 10046 // Never pick ARGB_4444 because it looks awful 10047 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 10048 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 10049 case DRAWING_CACHE_QUALITY_AUTO: 10050 quality = Bitmap.Config.ARGB_8888; 10051 break; 10052 case DRAWING_CACHE_QUALITY_LOW: 10053 quality = Bitmap.Config.ARGB_8888; 10054 break; 10055 case DRAWING_CACHE_QUALITY_HIGH: 10056 quality = Bitmap.Config.ARGB_8888; 10057 break; 10058 default: 10059 quality = Bitmap.Config.ARGB_8888; 10060 break; 10061 } 10062 } else { 10063 // Optimization for translucent windows 10064 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 10065 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 10066 } 10067 10068 // Try to cleanup memory 10069 if (bitmap != null) bitmap.recycle(); 10070 10071 try { 10072 bitmap = Bitmap.createBitmap(width, height, quality); 10073 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 10074 if (autoScale) { 10075 mDrawingCache = bitmap; 10076 } else { 10077 mUnscaledDrawingCache = bitmap; 10078 } 10079 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 10080 } catch (OutOfMemoryError e) { 10081 // If there is not enough memory to create the bitmap cache, just 10082 // ignore the issue as bitmap caches are not required to draw the 10083 // view hierarchy 10084 if (autoScale) { 10085 mDrawingCache = null; 10086 } else { 10087 mUnscaledDrawingCache = null; 10088 } 10089 mCachingFailed = true; 10090 return; 10091 } 10092 10093 clear = drawingCacheBackgroundColor != 0; 10094 } 10095 10096 Canvas canvas; 10097 if (attachInfo != null) { 10098 canvas = attachInfo.mCanvas; 10099 if (canvas == null) { 10100 canvas = new Canvas(); 10101 } 10102 canvas.setBitmap(bitmap); 10103 // Temporarily clobber the cached Canvas in case one of our children 10104 // is also using a drawing cache. Without this, the children would 10105 // steal the canvas by attaching their own bitmap to it and bad, bad 10106 // thing would happen (invisible views, corrupted drawings, etc.) 10107 attachInfo.mCanvas = null; 10108 } else { 10109 // This case should hopefully never or seldom happen 10110 canvas = new Canvas(bitmap); 10111 } 10112 10113 if (clear) { 10114 bitmap.eraseColor(drawingCacheBackgroundColor); 10115 } 10116 10117 computeScroll(); 10118 final int restoreCount = canvas.save(); 10119 10120 if (autoScale && scalingRequired) { 10121 final float scale = attachInfo.mApplicationScale; 10122 canvas.scale(scale, scale); 10123 } 10124 10125 canvas.translate(-mScrollX, -mScrollY); 10126 10127 mPrivateFlags |= DRAWN; 10128 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 10129 mLayerType != LAYER_TYPE_NONE) { 10130 mPrivateFlags |= DRAWING_CACHE_VALID; 10131 } 10132 10133 // Fast path for layouts with no backgrounds 10134 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 10135 if (ViewDebug.TRACE_HIERARCHY) { 10136 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); 10137 } 10138 mPrivateFlags &= ~DIRTY_MASK; 10139 dispatchDraw(canvas); 10140 } else { 10141 draw(canvas); 10142 } 10143 10144 canvas.restoreToCount(restoreCount); 10145 10146 if (attachInfo != null) { 10147 // Restore the cached Canvas for our siblings 10148 attachInfo.mCanvas = canvas; 10149 } 10150 } 10151 } 10152 10153 /** 10154 * Create a snapshot of the view into a bitmap. We should probably make 10155 * some form of this public, but should think about the API. 10156 */ 10157 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 10158 int width = mRight - mLeft; 10159 int height = mBottom - mTop; 10160 10161 final AttachInfo attachInfo = mAttachInfo; 10162 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 10163 width = (int) ((width * scale) + 0.5f); 10164 height = (int) ((height * scale) + 0.5f); 10165 10166 Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality); 10167 if (bitmap == null) { 10168 throw new OutOfMemoryError(); 10169 } 10170 10171 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 10172 10173 Canvas canvas; 10174 if (attachInfo != null) { 10175 canvas = attachInfo.mCanvas; 10176 if (canvas == null) { 10177 canvas = new Canvas(); 10178 } 10179 canvas.setBitmap(bitmap); 10180 // Temporarily clobber the cached Canvas in case one of our children 10181 // is also using a drawing cache. Without this, the children would 10182 // steal the canvas by attaching their own bitmap to it and bad, bad 10183 // things would happen (invisible views, corrupted drawings, etc.) 10184 attachInfo.mCanvas = null; 10185 } else { 10186 // This case should hopefully never or seldom happen 10187 canvas = new Canvas(bitmap); 10188 } 10189 10190 if ((backgroundColor & 0xff000000) != 0) { 10191 bitmap.eraseColor(backgroundColor); 10192 } 10193 10194 computeScroll(); 10195 final int restoreCount = canvas.save(); 10196 canvas.scale(scale, scale); 10197 canvas.translate(-mScrollX, -mScrollY); 10198 10199 // Temporarily remove the dirty mask 10200 int flags = mPrivateFlags; 10201 mPrivateFlags &= ~DIRTY_MASK; 10202 10203 // Fast path for layouts with no backgrounds 10204 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 10205 dispatchDraw(canvas); 10206 } else { 10207 draw(canvas); 10208 } 10209 10210 mPrivateFlags = flags; 10211 10212 canvas.restoreToCount(restoreCount); 10213 10214 if (attachInfo != null) { 10215 // Restore the cached Canvas for our siblings 10216 attachInfo.mCanvas = canvas; 10217 } 10218 10219 return bitmap; 10220 } 10221 10222 /** 10223 * Indicates whether this View is currently in edit mode. A View is usually 10224 * in edit mode when displayed within a developer tool. For instance, if 10225 * this View is being drawn by a visual user interface builder, this method 10226 * should return true. 10227 * 10228 * Subclasses should check the return value of this method to provide 10229 * different behaviors if their normal behavior might interfere with the 10230 * host environment. For instance: the class spawns a thread in its 10231 * constructor, the drawing code relies on device-specific features, etc. 10232 * 10233 * This method is usually checked in the drawing code of custom widgets. 10234 * 10235 * @return True if this View is in edit mode, false otherwise. 10236 */ 10237 public boolean isInEditMode() { 10238 return false; 10239 } 10240 10241 /** 10242 * If the View draws content inside its padding and enables fading edges, 10243 * it needs to support padding offsets. Padding offsets are added to the 10244 * fading edges to extend the length of the fade so that it covers pixels 10245 * drawn inside the padding. 10246 * 10247 * Subclasses of this class should override this method if they need 10248 * to draw content inside the padding. 10249 * 10250 * @return True if padding offset must be applied, false otherwise. 10251 * 10252 * @see #getLeftPaddingOffset() 10253 * @see #getRightPaddingOffset() 10254 * @see #getTopPaddingOffset() 10255 * @see #getBottomPaddingOffset() 10256 * 10257 * @since CURRENT 10258 */ 10259 protected boolean isPaddingOffsetRequired() { 10260 return false; 10261 } 10262 10263 /** 10264 * Amount by which to extend the left fading region. Called only when 10265 * {@link #isPaddingOffsetRequired()} returns true. 10266 * 10267 * @return The left padding offset in pixels. 10268 * 10269 * @see #isPaddingOffsetRequired() 10270 * 10271 * @since CURRENT 10272 */ 10273 protected int getLeftPaddingOffset() { 10274 return 0; 10275 } 10276 10277 /** 10278 * Amount by which to extend the right fading region. Called only when 10279 * {@link #isPaddingOffsetRequired()} returns true. 10280 * 10281 * @return The right padding offset in pixels. 10282 * 10283 * @see #isPaddingOffsetRequired() 10284 * 10285 * @since CURRENT 10286 */ 10287 protected int getRightPaddingOffset() { 10288 return 0; 10289 } 10290 10291 /** 10292 * Amount by which to extend the top fading region. Called only when 10293 * {@link #isPaddingOffsetRequired()} returns true. 10294 * 10295 * @return The top padding offset in pixels. 10296 * 10297 * @see #isPaddingOffsetRequired() 10298 * 10299 * @since CURRENT 10300 */ 10301 protected int getTopPaddingOffset() { 10302 return 0; 10303 } 10304 10305 /** 10306 * Amount by which to extend the bottom fading region. Called only when 10307 * {@link #isPaddingOffsetRequired()} returns true. 10308 * 10309 * @return The bottom padding offset in pixels. 10310 * 10311 * @see #isPaddingOffsetRequired() 10312 * 10313 * @since CURRENT 10314 */ 10315 protected int getBottomPaddingOffset() { 10316 return 0; 10317 } 10318 10319 /** 10320 * <p>Indicates whether this view is attached to an hardware accelerated 10321 * window or not.</p> 10322 * 10323 * <p>Even if this method returns true, it does not mean that every call 10324 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 10325 * accelerated {@link android.graphics.Canvas}. For instance, if this view 10326 * is drawn onto an offscren {@link android.graphics.Bitmap} and its 10327 * window is hardware accelerated, 10328 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 10329 * return false, and this method will return true.</p> 10330 * 10331 * @return True if the view is attached to a window and the window is 10332 * hardware accelerated; false in any other case. 10333 */ 10334 public boolean isHardwareAccelerated() { 10335 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 10336 } 10337 10338 /** 10339 * Manually render this view (and all of its children) to the given Canvas. 10340 * The view must have already done a full layout before this function is 10341 * called. When implementing a view, implement 10342 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 10343 * If you do need to override this method, call the superclass version. 10344 * 10345 * @param canvas The Canvas to which the View is rendered. 10346 */ 10347 public void draw(Canvas canvas) { 10348 if (ViewDebug.TRACE_HIERARCHY) { 10349 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); 10350 } 10351 10352 final int privateFlags = mPrivateFlags; 10353 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE && 10354 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 10355 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN; 10356 10357 /* 10358 * Draw traversal performs several drawing steps which must be executed 10359 * in the appropriate order: 10360 * 10361 * 1. Draw the background 10362 * 2. If necessary, save the canvas' layers to prepare for fading 10363 * 3. Draw view's content 10364 * 4. Draw children 10365 * 5. If necessary, draw the fading edges and restore layers 10366 * 6. Draw decorations (scrollbars for instance) 10367 */ 10368 10369 // Step 1, draw the background, if needed 10370 int saveCount; 10371 10372 if (!dirtyOpaque) { 10373 final Drawable background = mBGDrawable; 10374 if (background != null) { 10375 final int scrollX = mScrollX; 10376 final int scrollY = mScrollY; 10377 10378 if (mBackgroundSizeChanged) { 10379 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 10380 mBackgroundSizeChanged = false; 10381 } 10382 10383 if ((scrollX | scrollY) == 0) { 10384 background.draw(canvas); 10385 } else { 10386 canvas.translate(scrollX, scrollY); 10387 background.draw(canvas); 10388 canvas.translate(-scrollX, -scrollY); 10389 } 10390 } 10391 } 10392 10393 // skip step 2 & 5 if possible (common case) 10394 final int viewFlags = mViewFlags; 10395 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 10396 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 10397 if (!verticalEdges && !horizontalEdges) { 10398 // Step 3, draw the content 10399 if (!dirtyOpaque) onDraw(canvas); 10400 10401 // Step 4, draw the children 10402 dispatchDraw(canvas); 10403 10404 // Step 6, draw decorations (scrollbars) 10405 onDrawScrollBars(canvas); 10406 10407 // we're done... 10408 return; 10409 } 10410 10411 /* 10412 * Here we do the full fledged routine... 10413 * (this is an uncommon case where speed matters less, 10414 * this is why we repeat some of the tests that have been 10415 * done above) 10416 */ 10417 10418 boolean drawTop = false; 10419 boolean drawBottom = false; 10420 boolean drawLeft = false; 10421 boolean drawRight = false; 10422 10423 float topFadeStrength = 0.0f; 10424 float bottomFadeStrength = 0.0f; 10425 float leftFadeStrength = 0.0f; 10426 float rightFadeStrength = 0.0f; 10427 10428 // Step 2, save the canvas' layers 10429 int paddingLeft = mPaddingLeft; 10430 int paddingTop = mPaddingTop; 10431 10432 final boolean offsetRequired = isPaddingOffsetRequired(); 10433 if (offsetRequired) { 10434 paddingLeft += getLeftPaddingOffset(); 10435 paddingTop += getTopPaddingOffset(); 10436 } 10437 10438 int left = mScrollX + paddingLeft; 10439 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 10440 int top = mScrollY + paddingTop; 10441 int bottom = top + mBottom - mTop - mPaddingBottom - paddingTop; 10442 10443 if (offsetRequired) { 10444 right += getRightPaddingOffset(); 10445 bottom += getBottomPaddingOffset(); 10446 } 10447 10448 final ScrollabilityCache scrollabilityCache = mScrollCache; 10449 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 10450 int length = (int) fadeHeight; 10451 10452 // clip the fade length if top and bottom fades overlap 10453 // overlapping fades produce odd-looking artifacts 10454 if (verticalEdges && (top + length > bottom - length)) { 10455 length = (bottom - top) / 2; 10456 } 10457 10458 // also clip horizontal fades if necessary 10459 if (horizontalEdges && (left + length > right - length)) { 10460 length = (right - left) / 2; 10461 } 10462 10463 if (verticalEdges) { 10464 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 10465 drawTop = topFadeStrength * fadeHeight > 1.0f; 10466 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 10467 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 10468 } 10469 10470 if (horizontalEdges) { 10471 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 10472 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 10473 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 10474 drawRight = rightFadeStrength * fadeHeight > 1.0f; 10475 } 10476 10477 saveCount = canvas.getSaveCount(); 10478 10479 int solidColor = getSolidColor(); 10480 if (solidColor == 0) { 10481 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 10482 10483 if (drawTop) { 10484 canvas.saveLayer(left, top, right, top + length, null, flags); 10485 } 10486 10487 if (drawBottom) { 10488 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 10489 } 10490 10491 if (drawLeft) { 10492 canvas.saveLayer(left, top, left + length, bottom, null, flags); 10493 } 10494 10495 if (drawRight) { 10496 canvas.saveLayer(right - length, top, right, bottom, null, flags); 10497 } 10498 } else { 10499 scrollabilityCache.setFadeColor(solidColor); 10500 } 10501 10502 // Step 3, draw the content 10503 if (!dirtyOpaque) onDraw(canvas); 10504 10505 // Step 4, draw the children 10506 dispatchDraw(canvas); 10507 10508 // Step 5, draw the fade effect and restore layers 10509 final Paint p = scrollabilityCache.paint; 10510 final Matrix matrix = scrollabilityCache.matrix; 10511 final Shader fade = scrollabilityCache.shader; 10512 10513 if (drawTop) { 10514 matrix.setScale(1, fadeHeight * topFadeStrength); 10515 matrix.postTranslate(left, top); 10516 fade.setLocalMatrix(matrix); 10517 canvas.drawRect(left, top, right, top + length, p); 10518 } 10519 10520 if (drawBottom) { 10521 matrix.setScale(1, fadeHeight * bottomFadeStrength); 10522 matrix.postRotate(180); 10523 matrix.postTranslate(left, bottom); 10524 fade.setLocalMatrix(matrix); 10525 canvas.drawRect(left, bottom - length, right, bottom, p); 10526 } 10527 10528 if (drawLeft) { 10529 matrix.setScale(1, fadeHeight * leftFadeStrength); 10530 matrix.postRotate(-90); 10531 matrix.postTranslate(left, top); 10532 fade.setLocalMatrix(matrix); 10533 canvas.drawRect(left, top, left + length, bottom, p); 10534 } 10535 10536 if (drawRight) { 10537 matrix.setScale(1, fadeHeight * rightFadeStrength); 10538 matrix.postRotate(90); 10539 matrix.postTranslate(right, top); 10540 fade.setLocalMatrix(matrix); 10541 canvas.drawRect(right - length, top, right, bottom, p); 10542 } 10543 10544 canvas.restoreToCount(saveCount); 10545 10546 // Step 6, draw decorations (scrollbars) 10547 onDrawScrollBars(canvas); 10548 } 10549 10550 /** 10551 * Override this if your view is known to always be drawn on top of a solid color background, 10552 * and needs to draw fading edges. Returning a non-zero color enables the view system to 10553 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 10554 * should be set to 0xFF. 10555 * 10556 * @see #setVerticalFadingEdgeEnabled(boolean) 10557 * @see #setHorizontalFadingEdgeEnabled(boolean) 10558 * 10559 * @return The known solid color background for this view, or 0 if the color may vary 10560 */ 10561 @ViewDebug.ExportedProperty(category = "drawing") 10562 public int getSolidColor() { 10563 return 0; 10564 } 10565 10566 /** 10567 * Build a human readable string representation of the specified view flags. 10568 * 10569 * @param flags the view flags to convert to a string 10570 * @return a String representing the supplied flags 10571 */ 10572 private static String printFlags(int flags) { 10573 String output = ""; 10574 int numFlags = 0; 10575 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 10576 output += "TAKES_FOCUS"; 10577 numFlags++; 10578 } 10579 10580 switch (flags & VISIBILITY_MASK) { 10581 case INVISIBLE: 10582 if (numFlags > 0) { 10583 output += " "; 10584 } 10585 output += "INVISIBLE"; 10586 // USELESS HERE numFlags++; 10587 break; 10588 case GONE: 10589 if (numFlags > 0) { 10590 output += " "; 10591 } 10592 output += "GONE"; 10593 // USELESS HERE numFlags++; 10594 break; 10595 default: 10596 break; 10597 } 10598 return output; 10599 } 10600 10601 /** 10602 * Build a human readable string representation of the specified private 10603 * view flags. 10604 * 10605 * @param privateFlags the private view flags to convert to a string 10606 * @return a String representing the supplied flags 10607 */ 10608 private static String printPrivateFlags(int privateFlags) { 10609 String output = ""; 10610 int numFlags = 0; 10611 10612 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) { 10613 output += "WANTS_FOCUS"; 10614 numFlags++; 10615 } 10616 10617 if ((privateFlags & FOCUSED) == FOCUSED) { 10618 if (numFlags > 0) { 10619 output += " "; 10620 } 10621 output += "FOCUSED"; 10622 numFlags++; 10623 } 10624 10625 if ((privateFlags & SELECTED) == SELECTED) { 10626 if (numFlags > 0) { 10627 output += " "; 10628 } 10629 output += "SELECTED"; 10630 numFlags++; 10631 } 10632 10633 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) { 10634 if (numFlags > 0) { 10635 output += " "; 10636 } 10637 output += "IS_ROOT_NAMESPACE"; 10638 numFlags++; 10639 } 10640 10641 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) { 10642 if (numFlags > 0) { 10643 output += " "; 10644 } 10645 output += "HAS_BOUNDS"; 10646 numFlags++; 10647 } 10648 10649 if ((privateFlags & DRAWN) == DRAWN) { 10650 if (numFlags > 0) { 10651 output += " "; 10652 } 10653 output += "DRAWN"; 10654 // USELESS HERE numFlags++; 10655 } 10656 return output; 10657 } 10658 10659 /** 10660 * <p>Indicates whether or not this view's layout will be requested during 10661 * the next hierarchy layout pass.</p> 10662 * 10663 * @return true if the layout will be forced during next layout pass 10664 */ 10665 public boolean isLayoutRequested() { 10666 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT; 10667 } 10668 10669 /** 10670 * Assign a size and position to a view and all of its 10671 * descendants 10672 * 10673 * <p>This is the second phase of the layout mechanism. 10674 * (The first is measuring). In this phase, each parent calls 10675 * layout on all of its children to position them. 10676 * This is typically done using the child measurements 10677 * that were stored in the measure pass().</p> 10678 * 10679 * <p>Derived classes should not override this method. 10680 * Derived classes with children should override 10681 * onLayout. In that method, they should 10682 * call layout on each of their children.</p> 10683 * 10684 * @param l Left position, relative to parent 10685 * @param t Top position, relative to parent 10686 * @param r Right position, relative to parent 10687 * @param b Bottom position, relative to parent 10688 */ 10689 @SuppressWarnings({"unchecked"}) 10690 public void layout(int l, int t, int r, int b) { 10691 int oldL = mLeft; 10692 int oldT = mTop; 10693 int oldB = mBottom; 10694 int oldR = mRight; 10695 boolean changed = setFrame(l, t, r, b); 10696 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) { 10697 if (ViewDebug.TRACE_HIERARCHY) { 10698 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT); 10699 } 10700 10701 onLayout(changed, l, t, r, b); 10702 mPrivateFlags &= ~LAYOUT_REQUIRED; 10703 10704 if (mOnLayoutChangeListeners != null) { 10705 ArrayList<OnLayoutChangeListener> listenersCopy = 10706 (ArrayList<OnLayoutChangeListener>) mOnLayoutChangeListeners.clone(); 10707 int numListeners = listenersCopy.size(); 10708 for (int i = 0; i < numListeners; ++i) { 10709 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 10710 } 10711 } 10712 } 10713 mPrivateFlags &= ~FORCE_LAYOUT; 10714 } 10715 10716 /** 10717 * Called from layout when this view should 10718 * assign a size and position to each of its children. 10719 * 10720 * Derived classes with children should override 10721 * this method and call layout on each of 10722 * their children. 10723 * @param changed This is a new size or position for this view 10724 * @param left Left position, relative to parent 10725 * @param top Top position, relative to parent 10726 * @param right Right position, relative to parent 10727 * @param bottom Bottom position, relative to parent 10728 */ 10729 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 10730 } 10731 10732 /** 10733 * Assign a size and position to this view. 10734 * 10735 * This is called from layout. 10736 * 10737 * @param left Left position, relative to parent 10738 * @param top Top position, relative to parent 10739 * @param right Right position, relative to parent 10740 * @param bottom Bottom position, relative to parent 10741 * @return true if the new size and position are different than the 10742 * previous ones 10743 * {@hide} 10744 */ 10745 protected boolean setFrame(int left, int top, int right, int bottom) { 10746 boolean changed = false; 10747 10748 if (DBG) { 10749 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 10750 + right + "," + bottom + ")"); 10751 } 10752 10753 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 10754 changed = true; 10755 10756 // Remember our drawn bit 10757 int drawn = mPrivateFlags & DRAWN; 10758 10759 // Invalidate our old position 10760 invalidate(true); 10761 10762 10763 int oldWidth = mRight - mLeft; 10764 int oldHeight = mBottom - mTop; 10765 10766 mLeft = left; 10767 mTop = top; 10768 mRight = right; 10769 mBottom = bottom; 10770 10771 mPrivateFlags |= HAS_BOUNDS; 10772 10773 int newWidth = right - left; 10774 int newHeight = bottom - top; 10775 10776 if (newWidth != oldWidth || newHeight != oldHeight) { 10777 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 10778 // A change in dimension means an auto-centered pivot point changes, too 10779 mMatrixDirty = true; 10780 } 10781 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 10782 } 10783 10784 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 10785 // If we are visible, force the DRAWN bit to on so that 10786 // this invalidate will go through (at least to our parent). 10787 // This is because someone may have invalidated this view 10788 // before this call to setFrame came in, thereby clearing 10789 // the DRAWN bit. 10790 mPrivateFlags |= DRAWN; 10791 invalidate(true); 10792 // parent display list may need to be recreated based on a change in the bounds 10793 // of any child 10794 invalidateParentCaches(); 10795 } 10796 10797 // Reset drawn bit to original value (invalidate turns it off) 10798 mPrivateFlags |= drawn; 10799 10800 mBackgroundSizeChanged = true; 10801 } 10802 return changed; 10803 } 10804 10805 /** 10806 * Finalize inflating a view from XML. This is called as the last phase 10807 * of inflation, after all child views have been added. 10808 * 10809 * <p>Even if the subclass overrides onFinishInflate, they should always be 10810 * sure to call the super method, so that we get called. 10811 */ 10812 protected void onFinishInflate() { 10813 } 10814 10815 /** 10816 * Returns the resources associated with this view. 10817 * 10818 * @return Resources object. 10819 */ 10820 public Resources getResources() { 10821 return mResources; 10822 } 10823 10824 /** 10825 * Invalidates the specified Drawable. 10826 * 10827 * @param drawable the drawable to invalidate 10828 */ 10829 public void invalidateDrawable(Drawable drawable) { 10830 if (verifyDrawable(drawable)) { 10831 final Rect dirty = drawable.getBounds(); 10832 final int scrollX = mScrollX; 10833 final int scrollY = mScrollY; 10834 10835 invalidate(dirty.left + scrollX, dirty.top + scrollY, 10836 dirty.right + scrollX, dirty.bottom + scrollY); 10837 } 10838 } 10839 10840 /** 10841 * Schedules an action on a drawable to occur at a specified time. 10842 * 10843 * @param who the recipient of the action 10844 * @param what the action to run on the drawable 10845 * @param when the time at which the action must occur. Uses the 10846 * {@link SystemClock#uptimeMillis} timebase. 10847 */ 10848 public void scheduleDrawable(Drawable who, Runnable what, long when) { 10849 if (verifyDrawable(who) && what != null && mAttachInfo != null) { 10850 mAttachInfo.mHandler.postAtTime(what, who, when); 10851 } 10852 } 10853 10854 /** 10855 * Cancels a scheduled action on a drawable. 10856 * 10857 * @param who the recipient of the action 10858 * @param what the action to cancel 10859 */ 10860 public void unscheduleDrawable(Drawable who, Runnable what) { 10861 if (verifyDrawable(who) && what != null && mAttachInfo != null) { 10862 mAttachInfo.mHandler.removeCallbacks(what, who); 10863 } 10864 } 10865 10866 /** 10867 * Unschedule any events associated with the given Drawable. This can be 10868 * used when selecting a new Drawable into a view, so that the previous 10869 * one is completely unscheduled. 10870 * 10871 * @param who The Drawable to unschedule. 10872 * 10873 * @see #drawableStateChanged 10874 */ 10875 public void unscheduleDrawable(Drawable who) { 10876 if (mAttachInfo != null) { 10877 mAttachInfo.mHandler.removeCallbacksAndMessages(who); 10878 } 10879 } 10880 10881 /** 10882 * Return the layout direction of a given Drawable. 10883 * 10884 * @param who the Drawable to query 10885 * 10886 * @hide 10887 */ 10888 public int getResolvedLayoutDirection(Drawable who) { 10889 return (who == mBGDrawable) ? getResolvedLayoutDirection() : LAYOUT_DIRECTION_DEFAULT; 10890 } 10891 10892 /** 10893 * If your view subclass is displaying its own Drawable objects, it should 10894 * override this function and return true for any Drawable it is 10895 * displaying. This allows animations for those drawables to be 10896 * scheduled. 10897 * 10898 * <p>Be sure to call through to the super class when overriding this 10899 * function. 10900 * 10901 * @param who The Drawable to verify. Return true if it is one you are 10902 * displaying, else return the result of calling through to the 10903 * super class. 10904 * 10905 * @return boolean If true than the Drawable is being displayed in the 10906 * view; else false and it is not allowed to animate. 10907 * 10908 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 10909 * @see #drawableStateChanged() 10910 */ 10911 protected boolean verifyDrawable(Drawable who) { 10912 return who == mBGDrawable; 10913 } 10914 10915 /** 10916 * This function is called whenever the state of the view changes in such 10917 * a way that it impacts the state of drawables being shown. 10918 * 10919 * <p>Be sure to call through to the superclass when overriding this 10920 * function. 10921 * 10922 * @see Drawable#setState(int[]) 10923 */ 10924 protected void drawableStateChanged() { 10925 Drawable d = mBGDrawable; 10926 if (d != null && d.isStateful()) { 10927 d.setState(getDrawableState()); 10928 } 10929 } 10930 10931 /** 10932 * Call this to force a view to update its drawable state. This will cause 10933 * drawableStateChanged to be called on this view. Views that are interested 10934 * in the new state should call getDrawableState. 10935 * 10936 * @see #drawableStateChanged 10937 * @see #getDrawableState 10938 */ 10939 public void refreshDrawableState() { 10940 mPrivateFlags |= DRAWABLE_STATE_DIRTY; 10941 drawableStateChanged(); 10942 10943 ViewParent parent = mParent; 10944 if (parent != null) { 10945 parent.childDrawableStateChanged(this); 10946 } 10947 } 10948 10949 /** 10950 * Return an array of resource IDs of the drawable states representing the 10951 * current state of the view. 10952 * 10953 * @return The current drawable state 10954 * 10955 * @see Drawable#setState(int[]) 10956 * @see #drawableStateChanged() 10957 * @see #onCreateDrawableState(int) 10958 */ 10959 public final int[] getDrawableState() { 10960 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) { 10961 return mDrawableState; 10962 } else { 10963 mDrawableState = onCreateDrawableState(0); 10964 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY; 10965 return mDrawableState; 10966 } 10967 } 10968 10969 /** 10970 * Generate the new {@link android.graphics.drawable.Drawable} state for 10971 * this view. This is called by the view 10972 * system when the cached Drawable state is determined to be invalid. To 10973 * retrieve the current state, you should use {@link #getDrawableState}. 10974 * 10975 * @param extraSpace if non-zero, this is the number of extra entries you 10976 * would like in the returned array in which you can place your own 10977 * states. 10978 * 10979 * @return Returns an array holding the current {@link Drawable} state of 10980 * the view. 10981 * 10982 * @see #mergeDrawableStates(int[], int[]) 10983 */ 10984 protected int[] onCreateDrawableState(int extraSpace) { 10985 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 10986 mParent instanceof View) { 10987 return ((View) mParent).onCreateDrawableState(extraSpace); 10988 } 10989 10990 int[] drawableState; 10991 10992 int privateFlags = mPrivateFlags; 10993 10994 int viewStateIndex = 0; 10995 if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 10996 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 10997 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 10998 if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 10999 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 11000 if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 11001 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 11002 HardwareRenderer.isAvailable()) { 11003 // This is set if HW acceleration is requested, even if the current 11004 // process doesn't allow it. This is just to allow app preview 11005 // windows to better match their app. 11006 viewStateIndex |= VIEW_STATE_ACCELERATED; 11007 } 11008 if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 11009 11010 final int privateFlags2 = mPrivateFlags2; 11011 if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 11012 if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 11013 11014 drawableState = VIEW_STATE_SETS[viewStateIndex]; 11015 11016 //noinspection ConstantIfStatement 11017 if (false) { 11018 Log.i("View", "drawableStateIndex=" + viewStateIndex); 11019 Log.i("View", toString() 11020 + " pressed=" + ((privateFlags & PRESSED) != 0) 11021 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 11022 + " fo=" + hasFocus() 11023 + " sl=" + ((privateFlags & SELECTED) != 0) 11024 + " wf=" + hasWindowFocus() 11025 + ": " + Arrays.toString(drawableState)); 11026 } 11027 11028 if (extraSpace == 0) { 11029 return drawableState; 11030 } 11031 11032 final int[] fullState; 11033 if (drawableState != null) { 11034 fullState = new int[drawableState.length + extraSpace]; 11035 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 11036 } else { 11037 fullState = new int[extraSpace]; 11038 } 11039 11040 return fullState; 11041 } 11042 11043 /** 11044 * Merge your own state values in <var>additionalState</var> into the base 11045 * state values <var>baseState</var> that were returned by 11046 * {@link #onCreateDrawableState(int)}. 11047 * 11048 * @param baseState The base state values returned by 11049 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 11050 * own additional state values. 11051 * 11052 * @param additionalState The additional state values you would like 11053 * added to <var>baseState</var>; this array is not modified. 11054 * 11055 * @return As a convenience, the <var>baseState</var> array you originally 11056 * passed into the function is returned. 11057 * 11058 * @see #onCreateDrawableState(int) 11059 */ 11060 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 11061 final int N = baseState.length; 11062 int i = N - 1; 11063 while (i >= 0 && baseState[i] == 0) { 11064 i--; 11065 } 11066 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 11067 return baseState; 11068 } 11069 11070 /** 11071 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 11072 * on all Drawable objects associated with this view. 11073 */ 11074 public void jumpDrawablesToCurrentState() { 11075 if (mBGDrawable != null) { 11076 mBGDrawable.jumpToCurrentState(); 11077 } 11078 } 11079 11080 /** 11081 * Sets the background color for this view. 11082 * @param color the color of the background 11083 */ 11084 @RemotableViewMethod 11085 public void setBackgroundColor(int color) { 11086 if (mBGDrawable instanceof ColorDrawable) { 11087 ((ColorDrawable) mBGDrawable).setColor(color); 11088 } else { 11089 setBackgroundDrawable(new ColorDrawable(color)); 11090 } 11091 } 11092 11093 /** 11094 * Set the background to a given resource. The resource should refer to 11095 * a Drawable object or 0 to remove the background. 11096 * @param resid The identifier of the resource. 11097 * @attr ref android.R.styleable#View_background 11098 */ 11099 @RemotableViewMethod 11100 public void setBackgroundResource(int resid) { 11101 if (resid != 0 && resid == mBackgroundResource) { 11102 return; 11103 } 11104 11105 Drawable d= null; 11106 if (resid != 0) { 11107 d = mResources.getDrawable(resid); 11108 } 11109 setBackgroundDrawable(d); 11110 11111 mBackgroundResource = resid; 11112 } 11113 11114 /** 11115 * Set the background to a given Drawable, or remove the background. If the 11116 * background has padding, this View's padding is set to the background's 11117 * padding. However, when a background is removed, this View's padding isn't 11118 * touched. If setting the padding is desired, please use 11119 * {@link #setPadding(int, int, int, int)}. 11120 * 11121 * @param d The Drawable to use as the background, or null to remove the 11122 * background 11123 */ 11124 public void setBackgroundDrawable(Drawable d) { 11125 if (d == mBGDrawable) { 11126 return; 11127 } 11128 11129 boolean requestLayout = false; 11130 11131 mBackgroundResource = 0; 11132 11133 /* 11134 * Regardless of whether we're setting a new background or not, we want 11135 * to clear the previous drawable. 11136 */ 11137 if (mBGDrawable != null) { 11138 mBGDrawable.setCallback(null); 11139 unscheduleDrawable(mBGDrawable); 11140 } 11141 11142 if (d != null) { 11143 Rect padding = sThreadLocal.get(); 11144 if (padding == null) { 11145 padding = new Rect(); 11146 sThreadLocal.set(padding); 11147 } 11148 if (d.getPadding(padding)) { 11149 switch (d.getResolvedLayoutDirectionSelf()) { 11150 case LAYOUT_DIRECTION_RTL: 11151 setPadding(padding.right, padding.top, padding.left, padding.bottom); 11152 break; 11153 case LAYOUT_DIRECTION_LTR: 11154 default: 11155 setPadding(padding.left, padding.top, padding.right, padding.bottom); 11156 } 11157 } 11158 11159 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 11160 // if it has a different minimum size, we should layout again 11161 if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() || 11162 mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) { 11163 requestLayout = true; 11164 } 11165 11166 d.setCallback(this); 11167 if (d.isStateful()) { 11168 d.setState(getDrawableState()); 11169 } 11170 d.setVisible(getVisibility() == VISIBLE, false); 11171 mBGDrawable = d; 11172 11173 if ((mPrivateFlags & SKIP_DRAW) != 0) { 11174 mPrivateFlags &= ~SKIP_DRAW; 11175 mPrivateFlags |= ONLY_DRAWS_BACKGROUND; 11176 requestLayout = true; 11177 } 11178 } else { 11179 /* Remove the background */ 11180 mBGDrawable = null; 11181 11182 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) { 11183 /* 11184 * This view ONLY drew the background before and we're removing 11185 * the background, so now it won't draw anything 11186 * (hence we SKIP_DRAW) 11187 */ 11188 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND; 11189 mPrivateFlags |= SKIP_DRAW; 11190 } 11191 11192 /* 11193 * When the background is set, we try to apply its padding to this 11194 * View. When the background is removed, we don't touch this View's 11195 * padding. This is noted in the Javadocs. Hence, we don't need to 11196 * requestLayout(), the invalidate() below is sufficient. 11197 */ 11198 11199 // The old background's minimum size could have affected this 11200 // View's layout, so let's requestLayout 11201 requestLayout = true; 11202 } 11203 11204 computeOpaqueFlags(); 11205 11206 if (requestLayout) { 11207 requestLayout(); 11208 } 11209 11210 mBackgroundSizeChanged = true; 11211 invalidate(true); 11212 } 11213 11214 /** 11215 * Gets the background drawable 11216 * @return The drawable used as the background for this view, if any. 11217 */ 11218 public Drawable getBackground() { 11219 return mBGDrawable; 11220 } 11221 11222 /** 11223 * Sets the padding. The view may add on the space required to display 11224 * the scrollbars, depending on the style and visibility of the scrollbars. 11225 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 11226 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 11227 * from the values set in this call. 11228 * 11229 * @attr ref android.R.styleable#View_padding 11230 * @attr ref android.R.styleable#View_paddingBottom 11231 * @attr ref android.R.styleable#View_paddingLeft 11232 * @attr ref android.R.styleable#View_paddingRight 11233 * @attr ref android.R.styleable#View_paddingTop 11234 * @param left the left padding in pixels 11235 * @param top the top padding in pixels 11236 * @param right the right padding in pixels 11237 * @param bottom the bottom padding in pixels 11238 */ 11239 public void setPadding(int left, int top, int right, int bottom) { 11240 boolean changed = false; 11241 11242 mUserPaddingRelative = false; 11243 11244 mUserPaddingLeft = left; 11245 mUserPaddingRight = right; 11246 mUserPaddingBottom = bottom; 11247 11248 final int viewFlags = mViewFlags; 11249 11250 // Common case is there are no scroll bars. 11251 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 11252 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 11253 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 11254 ? 0 : getVerticalScrollbarWidth(); 11255 switch (mVerticalScrollbarPosition) { 11256 case SCROLLBAR_POSITION_DEFAULT: 11257 if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) { 11258 left += offset; 11259 } else { 11260 right += offset; 11261 } 11262 break; 11263 case SCROLLBAR_POSITION_RIGHT: 11264 right += offset; 11265 break; 11266 case SCROLLBAR_POSITION_LEFT: 11267 left += offset; 11268 break; 11269 } 11270 } 11271 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 11272 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 11273 ? 0 : getHorizontalScrollbarHeight(); 11274 } 11275 } 11276 11277 if (mPaddingLeft != left) { 11278 changed = true; 11279 mPaddingLeft = left; 11280 } 11281 if (mPaddingTop != top) { 11282 changed = true; 11283 mPaddingTop = top; 11284 } 11285 if (mPaddingRight != right) { 11286 changed = true; 11287 mPaddingRight = right; 11288 } 11289 if (mPaddingBottom != bottom) { 11290 changed = true; 11291 mPaddingBottom = bottom; 11292 } 11293 11294 if (changed) { 11295 requestLayout(); 11296 } 11297 } 11298 11299 /** 11300 * Sets the relative padding. The view may add on the space required to display 11301 * the scrollbars, depending on the style and visibility of the scrollbars. 11302 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 11303 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 11304 * from the values set in this call. 11305 * 11306 * @attr ref android.R.styleable#View_padding 11307 * @attr ref android.R.styleable#View_paddingBottom 11308 * @attr ref android.R.styleable#View_paddingStart 11309 * @attr ref android.R.styleable#View_paddingEnd 11310 * @attr ref android.R.styleable#View_paddingTop 11311 * @param start the start padding in pixels 11312 * @param top the top padding in pixels 11313 * @param end the end padding in pixels 11314 * @param bottom the bottom padding in pixels 11315 * 11316 * @hide 11317 */ 11318 public void setPaddingRelative(int start, int top, int end, int bottom) { 11319 mUserPaddingRelative = true; 11320 11321 mUserPaddingStart = start; 11322 mUserPaddingEnd = end; 11323 11324 switch(getResolvedLayoutDirection()) { 11325 case LAYOUT_DIRECTION_RTL: 11326 setPadding(end, top, start, bottom); 11327 break; 11328 case LAYOUT_DIRECTION_LTR: 11329 default: 11330 setPadding(start, top, end, bottom); 11331 } 11332 } 11333 11334 /** 11335 * Returns the top padding of this view. 11336 * 11337 * @return the top padding in pixels 11338 */ 11339 public int getPaddingTop() { 11340 return mPaddingTop; 11341 } 11342 11343 /** 11344 * Returns the bottom padding of this view. If there are inset and enabled 11345 * scrollbars, this value may include the space required to display the 11346 * scrollbars as well. 11347 * 11348 * @return the bottom padding in pixels 11349 */ 11350 public int getPaddingBottom() { 11351 return mPaddingBottom; 11352 } 11353 11354 /** 11355 * Returns the left padding of this view. If there are inset and enabled 11356 * scrollbars, this value may include the space required to display the 11357 * scrollbars as well. 11358 * 11359 * @return the left padding in pixels 11360 */ 11361 public int getPaddingLeft() { 11362 return mPaddingLeft; 11363 } 11364 11365 /** 11366 * Returns the start padding of this view. If there are inset and enabled 11367 * scrollbars, this value may include the space required to display the 11368 * scrollbars as well. 11369 * 11370 * @return the start padding in pixels 11371 * 11372 * @hide 11373 */ 11374 public int getPaddingStart() { 11375 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 11376 mPaddingRight : mPaddingLeft; 11377 } 11378 11379 /** 11380 * Returns the right padding of this view. If there are inset and enabled 11381 * scrollbars, this value may include the space required to display the 11382 * scrollbars as well. 11383 * 11384 * @return the right padding in pixels 11385 */ 11386 public int getPaddingRight() { 11387 return mPaddingRight; 11388 } 11389 11390 /** 11391 * Returns the end padding of this view. If there are inset and enabled 11392 * scrollbars, this value may include the space required to display the 11393 * scrollbars as well. 11394 * 11395 * @return the end padding in pixels 11396 * 11397 * @hide 11398 */ 11399 public int getPaddingEnd() { 11400 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 11401 mPaddingLeft : mPaddingRight; 11402 } 11403 11404 /** 11405 * Return if the padding as been set thru relative values 11406 * {@link #setPaddingRelative(int, int, int, int)} or thru 11407 * @attr ref android.R.styleable#View_paddingStart or 11408 * @attr ref android.R.styleable#View_paddingEnd 11409 * 11410 * @return true if the padding is relative or false if it is not. 11411 * 11412 * @hide 11413 */ 11414 public boolean isPaddingRelative() { 11415 return mUserPaddingRelative; 11416 } 11417 11418 /** 11419 * Changes the selection state of this view. A view can be selected or not. 11420 * Note that selection is not the same as focus. Views are typically 11421 * selected in the context of an AdapterView like ListView or GridView; 11422 * the selected view is the view that is highlighted. 11423 * 11424 * @param selected true if the view must be selected, false otherwise 11425 */ 11426 public void setSelected(boolean selected) { 11427 if (((mPrivateFlags & SELECTED) != 0) != selected) { 11428 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0); 11429 if (!selected) resetPressedState(); 11430 invalidate(true); 11431 refreshDrawableState(); 11432 dispatchSetSelected(selected); 11433 } 11434 } 11435 11436 /** 11437 * Dispatch setSelected to all of this View's children. 11438 * 11439 * @see #setSelected(boolean) 11440 * 11441 * @param selected The new selected state 11442 */ 11443 protected void dispatchSetSelected(boolean selected) { 11444 } 11445 11446 /** 11447 * Indicates the selection state of this view. 11448 * 11449 * @return true if the view is selected, false otherwise 11450 */ 11451 @ViewDebug.ExportedProperty 11452 public boolean isSelected() { 11453 return (mPrivateFlags & SELECTED) != 0; 11454 } 11455 11456 /** 11457 * Changes the activated state of this view. A view can be activated or not. 11458 * Note that activation is not the same as selection. Selection is 11459 * a transient property, representing the view (hierarchy) the user is 11460 * currently interacting with. Activation is a longer-term state that the 11461 * user can move views in and out of. For example, in a list view with 11462 * single or multiple selection enabled, the views in the current selection 11463 * set are activated. (Um, yeah, we are deeply sorry about the terminology 11464 * here.) The activated state is propagated down to children of the view it 11465 * is set on. 11466 * 11467 * @param activated true if the view must be activated, false otherwise 11468 */ 11469 public void setActivated(boolean activated) { 11470 if (((mPrivateFlags & ACTIVATED) != 0) != activated) { 11471 mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0); 11472 invalidate(true); 11473 refreshDrawableState(); 11474 dispatchSetActivated(activated); 11475 } 11476 } 11477 11478 /** 11479 * Dispatch setActivated to all of this View's children. 11480 * 11481 * @see #setActivated(boolean) 11482 * 11483 * @param activated The new activated state 11484 */ 11485 protected void dispatchSetActivated(boolean activated) { 11486 } 11487 11488 /** 11489 * Indicates the activation state of this view. 11490 * 11491 * @return true if the view is activated, false otherwise 11492 */ 11493 @ViewDebug.ExportedProperty 11494 public boolean isActivated() { 11495 return (mPrivateFlags & ACTIVATED) != 0; 11496 } 11497 11498 /** 11499 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 11500 * observer can be used to get notifications when global events, like 11501 * layout, happen. 11502 * 11503 * The returned ViewTreeObserver observer is not guaranteed to remain 11504 * valid for the lifetime of this View. If the caller of this method keeps 11505 * a long-lived reference to ViewTreeObserver, it should always check for 11506 * the return value of {@link ViewTreeObserver#isAlive()}. 11507 * 11508 * @return The ViewTreeObserver for this view's hierarchy. 11509 */ 11510 public ViewTreeObserver getViewTreeObserver() { 11511 if (mAttachInfo != null) { 11512 return mAttachInfo.mTreeObserver; 11513 } 11514 if (mFloatingTreeObserver == null) { 11515 mFloatingTreeObserver = new ViewTreeObserver(); 11516 } 11517 return mFloatingTreeObserver; 11518 } 11519 11520 /** 11521 * <p>Finds the topmost view in the current view hierarchy.</p> 11522 * 11523 * @return the topmost view containing this view 11524 */ 11525 public View getRootView() { 11526 if (mAttachInfo != null) { 11527 final View v = mAttachInfo.mRootView; 11528 if (v != null) { 11529 return v; 11530 } 11531 } 11532 11533 View parent = this; 11534 11535 while (parent.mParent != null && parent.mParent instanceof View) { 11536 parent = (View) parent.mParent; 11537 } 11538 11539 return parent; 11540 } 11541 11542 /** 11543 * <p>Computes the coordinates of this view on the screen. The argument 11544 * must be an array of two integers. After the method returns, the array 11545 * contains the x and y location in that order.</p> 11546 * 11547 * @param location an array of two integers in which to hold the coordinates 11548 */ 11549 public void getLocationOnScreen(int[] location) { 11550 getLocationInWindow(location); 11551 11552 final AttachInfo info = mAttachInfo; 11553 if (info != null) { 11554 location[0] += info.mWindowLeft; 11555 location[1] += info.mWindowTop; 11556 } 11557 } 11558 11559 /** 11560 * <p>Computes the coordinates of this view in its window. The argument 11561 * must be an array of two integers. After the method returns, the array 11562 * contains the x and y location in that order.</p> 11563 * 11564 * @param location an array of two integers in which to hold the coordinates 11565 */ 11566 public void getLocationInWindow(int[] location) { 11567 if (location == null || location.length < 2) { 11568 throw new IllegalArgumentException("location must be an array of " 11569 + "two integers"); 11570 } 11571 11572 location[0] = mLeft + (int) (mTranslationX + 0.5f); 11573 location[1] = mTop + (int) (mTranslationY + 0.5f); 11574 11575 ViewParent viewParent = mParent; 11576 while (viewParent instanceof View) { 11577 final View view = (View)viewParent; 11578 location[0] += view.mLeft + (int) (view.mTranslationX + 0.5f) - view.mScrollX; 11579 location[1] += view.mTop + (int) (view.mTranslationY + 0.5f) - view.mScrollY; 11580 viewParent = view.mParent; 11581 } 11582 11583 if (viewParent instanceof ViewRootImpl) { 11584 // *cough* 11585 final ViewRootImpl vr = (ViewRootImpl)viewParent; 11586 location[1] -= vr.mCurScrollY; 11587 } 11588 } 11589 11590 /** 11591 * {@hide} 11592 * @param id the id of the view to be found 11593 * @return the view of the specified id, null if cannot be found 11594 */ 11595 protected View findViewTraversal(int id) { 11596 if (id == mID) { 11597 return this; 11598 } 11599 return null; 11600 } 11601 11602 /** 11603 * {@hide} 11604 * @param tag the tag of the view to be found 11605 * @return the view of specified tag, null if cannot be found 11606 */ 11607 protected View findViewWithTagTraversal(Object tag) { 11608 if (tag != null && tag.equals(mTag)) { 11609 return this; 11610 } 11611 return null; 11612 } 11613 11614 /** 11615 * {@hide} 11616 * @param predicate The predicate to evaluate. 11617 * @return The first view that matches the predicate or null. 11618 */ 11619 protected View findViewByPredicateTraversal(Predicate<View> predicate) { 11620 if (predicate.apply(this)) { 11621 return this; 11622 } 11623 return null; 11624 } 11625 11626 /** 11627 * Look for a child view with the given id. If this view has the given 11628 * id, return this view. 11629 * 11630 * @param id The id to search for. 11631 * @return The view that has the given id in the hierarchy or null 11632 */ 11633 public final View findViewById(int id) { 11634 if (id < 0) { 11635 return null; 11636 } 11637 return findViewTraversal(id); 11638 } 11639 11640 /** 11641 * Look for a child view with the given tag. If this view has the given 11642 * tag, return this view. 11643 * 11644 * @param tag The tag to search for, using "tag.equals(getTag())". 11645 * @return The View that has the given tag in the hierarchy or null 11646 */ 11647 public final View findViewWithTag(Object tag) { 11648 if (tag == null) { 11649 return null; 11650 } 11651 return findViewWithTagTraversal(tag); 11652 } 11653 11654 /** 11655 * {@hide} 11656 * Look for a child view that matches the specified predicate. 11657 * If this view matches the predicate, return this view. 11658 * 11659 * @param predicate The predicate to evaluate. 11660 * @return The first view that matches the predicate or null. 11661 */ 11662 public final View findViewByPredicate(Predicate<View> predicate) { 11663 return findViewByPredicateTraversal(predicate); 11664 } 11665 11666 /** 11667 * Sets the identifier for this view. The identifier does not have to be 11668 * unique in this view's hierarchy. The identifier should be a positive 11669 * number. 11670 * 11671 * @see #NO_ID 11672 * @see #getId() 11673 * @see #findViewById(int) 11674 * 11675 * @param id a number used to identify the view 11676 * 11677 * @attr ref android.R.styleable#View_id 11678 */ 11679 public void setId(int id) { 11680 mID = id; 11681 } 11682 11683 /** 11684 * {@hide} 11685 * 11686 * @param isRoot true if the view belongs to the root namespace, false 11687 * otherwise 11688 */ 11689 public void setIsRootNamespace(boolean isRoot) { 11690 if (isRoot) { 11691 mPrivateFlags |= IS_ROOT_NAMESPACE; 11692 } else { 11693 mPrivateFlags &= ~IS_ROOT_NAMESPACE; 11694 } 11695 } 11696 11697 /** 11698 * {@hide} 11699 * 11700 * @return true if the view belongs to the root namespace, false otherwise 11701 */ 11702 public boolean isRootNamespace() { 11703 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0; 11704 } 11705 11706 /** 11707 * Returns this view's identifier. 11708 * 11709 * @return a positive integer used to identify the view or {@link #NO_ID} 11710 * if the view has no ID 11711 * 11712 * @see #setId(int) 11713 * @see #findViewById(int) 11714 * @attr ref android.R.styleable#View_id 11715 */ 11716 @ViewDebug.CapturedViewProperty 11717 public int getId() { 11718 return mID; 11719 } 11720 11721 /** 11722 * Returns this view's tag. 11723 * 11724 * @return the Object stored in this view as a tag 11725 * 11726 * @see #setTag(Object) 11727 * @see #getTag(int) 11728 */ 11729 @ViewDebug.ExportedProperty 11730 public Object getTag() { 11731 return mTag; 11732 } 11733 11734 /** 11735 * Sets the tag associated with this view. A tag can be used to mark 11736 * a view in its hierarchy and does not have to be unique within the 11737 * hierarchy. Tags can also be used to store data within a view without 11738 * resorting to another data structure. 11739 * 11740 * @param tag an Object to tag the view with 11741 * 11742 * @see #getTag() 11743 * @see #setTag(int, Object) 11744 */ 11745 public void setTag(final Object tag) { 11746 mTag = tag; 11747 } 11748 11749 /** 11750 * Returns the tag associated with this view and the specified key. 11751 * 11752 * @param key The key identifying the tag 11753 * 11754 * @return the Object stored in this view as a tag 11755 * 11756 * @see #setTag(int, Object) 11757 * @see #getTag() 11758 */ 11759 public Object getTag(int key) { 11760 SparseArray<Object> tags = null; 11761 synchronized (sTagsLock) { 11762 if (sTags != null) { 11763 tags = sTags.get(this); 11764 } 11765 } 11766 11767 if (tags != null) return tags.get(key); 11768 return null; 11769 } 11770 11771 /** 11772 * Sets a tag associated with this view and a key. A tag can be used 11773 * to mark a view in its hierarchy and does not have to be unique within 11774 * the hierarchy. Tags can also be used to store data within a view 11775 * without resorting to another data structure. 11776 * 11777 * The specified key should be an id declared in the resources of the 11778 * application to ensure it is unique (see the <a 11779 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 11780 * Keys identified as belonging to 11781 * the Android framework or not associated with any package will cause 11782 * an {@link IllegalArgumentException} to be thrown. 11783 * 11784 * @param key The key identifying the tag 11785 * @param tag An Object to tag the view with 11786 * 11787 * @throws IllegalArgumentException If they specified key is not valid 11788 * 11789 * @see #setTag(Object) 11790 * @see #getTag(int) 11791 */ 11792 public void setTag(int key, final Object tag) { 11793 // If the package id is 0x00 or 0x01, it's either an undefined package 11794 // or a framework id 11795 if ((key >>> 24) < 2) { 11796 throw new IllegalArgumentException("The key must be an application-specific " 11797 + "resource id."); 11798 } 11799 11800 setTagInternal(this, key, tag); 11801 } 11802 11803 /** 11804 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 11805 * framework id. 11806 * 11807 * @hide 11808 */ 11809 public void setTagInternal(int key, Object tag) { 11810 if ((key >>> 24) != 0x1) { 11811 throw new IllegalArgumentException("The key must be a framework-specific " 11812 + "resource id."); 11813 } 11814 11815 setTagInternal(this, key, tag); 11816 } 11817 11818 private static void setTagInternal(View view, int key, Object tag) { 11819 SparseArray<Object> tags = null; 11820 synchronized (sTagsLock) { 11821 if (sTags == null) { 11822 sTags = new WeakHashMap<View, SparseArray<Object>>(); 11823 } else { 11824 tags = sTags.get(view); 11825 } 11826 } 11827 11828 if (tags == null) { 11829 tags = new SparseArray<Object>(2); 11830 synchronized (sTagsLock) { 11831 sTags.put(view, tags); 11832 } 11833 } 11834 11835 tags.put(key, tag); 11836 } 11837 11838 /** 11839 * @param consistency The type of consistency. See ViewDebug for more information. 11840 * 11841 * @hide 11842 */ 11843 protected boolean dispatchConsistencyCheck(int consistency) { 11844 return onConsistencyCheck(consistency); 11845 } 11846 11847 /** 11848 * Method that subclasses should implement to check their consistency. The type of 11849 * consistency check is indicated by the bit field passed as a parameter. 11850 * 11851 * @param consistency The type of consistency. See ViewDebug for more information. 11852 * 11853 * @throws IllegalStateException if the view is in an inconsistent state. 11854 * 11855 * @hide 11856 */ 11857 protected boolean onConsistencyCheck(int consistency) { 11858 boolean result = true; 11859 11860 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0; 11861 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0; 11862 11863 if (checkLayout) { 11864 if (getParent() == null) { 11865 result = false; 11866 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 11867 "View " + this + " does not have a parent."); 11868 } 11869 11870 if (mAttachInfo == null) { 11871 result = false; 11872 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 11873 "View " + this + " is not attached to a window."); 11874 } 11875 } 11876 11877 if (checkDrawing) { 11878 // Do not check the DIRTY/DRAWN flags because views can call invalidate() 11879 // from their draw() method 11880 11881 if ((mPrivateFlags & DRAWN) != DRAWN && 11882 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) { 11883 result = false; 11884 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 11885 "View " + this + " was invalidated but its drawing cache is valid."); 11886 } 11887 } 11888 11889 return result; 11890 } 11891 11892 /** 11893 * Prints information about this view in the log output, with the tag 11894 * {@link #VIEW_LOG_TAG}. 11895 * 11896 * @hide 11897 */ 11898 public void debug() { 11899 debug(0); 11900 } 11901 11902 /** 11903 * Prints information about this view in the log output, with the tag 11904 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 11905 * indentation defined by the <code>depth</code>. 11906 * 11907 * @param depth the indentation level 11908 * 11909 * @hide 11910 */ 11911 protected void debug(int depth) { 11912 String output = debugIndent(depth - 1); 11913 11914 output += "+ " + this; 11915 int id = getId(); 11916 if (id != -1) { 11917 output += " (id=" + id + ")"; 11918 } 11919 Object tag = getTag(); 11920 if (tag != null) { 11921 output += " (tag=" + tag + ")"; 11922 } 11923 Log.d(VIEW_LOG_TAG, output); 11924 11925 if ((mPrivateFlags & FOCUSED) != 0) { 11926 output = debugIndent(depth) + " FOCUSED"; 11927 Log.d(VIEW_LOG_TAG, output); 11928 } 11929 11930 output = debugIndent(depth); 11931 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 11932 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 11933 + "} "; 11934 Log.d(VIEW_LOG_TAG, output); 11935 11936 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 11937 || mPaddingBottom != 0) { 11938 output = debugIndent(depth); 11939 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 11940 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 11941 Log.d(VIEW_LOG_TAG, output); 11942 } 11943 11944 output = debugIndent(depth); 11945 output += "mMeasureWidth=" + mMeasuredWidth + 11946 " mMeasureHeight=" + mMeasuredHeight; 11947 Log.d(VIEW_LOG_TAG, output); 11948 11949 output = debugIndent(depth); 11950 if (mLayoutParams == null) { 11951 output += "BAD! no layout params"; 11952 } else { 11953 output = mLayoutParams.debug(output); 11954 } 11955 Log.d(VIEW_LOG_TAG, output); 11956 11957 output = debugIndent(depth); 11958 output += "flags={"; 11959 output += View.printFlags(mViewFlags); 11960 output += "}"; 11961 Log.d(VIEW_LOG_TAG, output); 11962 11963 output = debugIndent(depth); 11964 output += "privateFlags={"; 11965 output += View.printPrivateFlags(mPrivateFlags); 11966 output += "}"; 11967 Log.d(VIEW_LOG_TAG, output); 11968 } 11969 11970 /** 11971 * Creates an string of whitespaces used for indentation. 11972 * 11973 * @param depth the indentation level 11974 * @return a String containing (depth * 2 + 3) * 2 white spaces 11975 * 11976 * @hide 11977 */ 11978 protected static String debugIndent(int depth) { 11979 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 11980 for (int i = 0; i < (depth * 2) + 3; i++) { 11981 spaces.append(' ').append(' '); 11982 } 11983 return spaces.toString(); 11984 } 11985 11986 /** 11987 * <p>Return the offset of the widget's text baseline from the widget's top 11988 * boundary. If this widget does not support baseline alignment, this 11989 * method returns -1. </p> 11990 * 11991 * @return the offset of the baseline within the widget's bounds or -1 11992 * if baseline alignment is not supported 11993 */ 11994 @ViewDebug.ExportedProperty(category = "layout") 11995 public int getBaseline() { 11996 return -1; 11997 } 11998 11999 /** 12000 * Call this when something has changed which has invalidated the 12001 * layout of this view. This will schedule a layout pass of the view 12002 * tree. 12003 */ 12004 public void requestLayout() { 12005 if (ViewDebug.TRACE_HIERARCHY) { 12006 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT); 12007 } 12008 12009 mPrivateFlags |= FORCE_LAYOUT; 12010 mPrivateFlags |= INVALIDATED; 12011 12012 if (mLayoutParams != null && mParent != null) { 12013 mLayoutParams.resolveWithDirection(getResolvedLayoutDirection()); 12014 } 12015 12016 if (mParent != null && !mParent.isLayoutRequested()) { 12017 mParent.requestLayout(); 12018 } 12019 } 12020 12021 /** 12022 * Forces this view to be laid out during the next layout pass. 12023 * This method does not call requestLayout() or forceLayout() 12024 * on the parent. 12025 */ 12026 public void forceLayout() { 12027 mPrivateFlags |= FORCE_LAYOUT; 12028 mPrivateFlags |= INVALIDATED; 12029 } 12030 12031 /** 12032 * <p> 12033 * This is called to find out how big a view should be. The parent 12034 * supplies constraint information in the width and height parameters. 12035 * </p> 12036 * 12037 * <p> 12038 * The actual mesurement work of a view is performed in 12039 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 12040 * {@link #onMeasure(int, int)} can and must be overriden by subclasses. 12041 * </p> 12042 * 12043 * 12044 * @param widthMeasureSpec Horizontal space requirements as imposed by the 12045 * parent 12046 * @param heightMeasureSpec Vertical space requirements as imposed by the 12047 * parent 12048 * 12049 * @see #onMeasure(int, int) 12050 */ 12051 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 12052 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT || 12053 widthMeasureSpec != mOldWidthMeasureSpec || 12054 heightMeasureSpec != mOldHeightMeasureSpec) { 12055 12056 // first clears the measured dimension flag 12057 mPrivateFlags &= ~MEASURED_DIMENSION_SET; 12058 12059 if (ViewDebug.TRACE_HIERARCHY) { 12060 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE); 12061 } 12062 12063 // measure ourselves, this should set the measured dimension flag back 12064 onMeasure(widthMeasureSpec, heightMeasureSpec); 12065 12066 // flag not set, setMeasuredDimension() was not invoked, we raise 12067 // an exception to warn the developer 12068 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) { 12069 throw new IllegalStateException("onMeasure() did not set the" 12070 + " measured dimension by calling" 12071 + " setMeasuredDimension()"); 12072 } 12073 12074 mPrivateFlags |= LAYOUT_REQUIRED; 12075 } 12076 12077 mOldWidthMeasureSpec = widthMeasureSpec; 12078 mOldHeightMeasureSpec = heightMeasureSpec; 12079 } 12080 12081 /** 12082 * <p> 12083 * Measure the view and its content to determine the measured width and the 12084 * measured height. This method is invoked by {@link #measure(int, int)} and 12085 * should be overriden by subclasses to provide accurate and efficient 12086 * measurement of their contents. 12087 * </p> 12088 * 12089 * <p> 12090 * <strong>CONTRACT:</strong> When overriding this method, you 12091 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 12092 * measured width and height of this view. Failure to do so will trigger an 12093 * <code>IllegalStateException</code>, thrown by 12094 * {@link #measure(int, int)}. Calling the superclass' 12095 * {@link #onMeasure(int, int)} is a valid use. 12096 * </p> 12097 * 12098 * <p> 12099 * The base class implementation of measure defaults to the background size, 12100 * unless a larger size is allowed by the MeasureSpec. Subclasses should 12101 * override {@link #onMeasure(int, int)} to provide better measurements of 12102 * their content. 12103 * </p> 12104 * 12105 * <p> 12106 * If this method is overridden, it is the subclass's responsibility to make 12107 * sure the measured height and width are at least the view's minimum height 12108 * and width ({@link #getSuggestedMinimumHeight()} and 12109 * {@link #getSuggestedMinimumWidth()}). 12110 * </p> 12111 * 12112 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 12113 * The requirements are encoded with 12114 * {@link android.view.View.MeasureSpec}. 12115 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 12116 * The requirements are encoded with 12117 * {@link android.view.View.MeasureSpec}. 12118 * 12119 * @see #getMeasuredWidth() 12120 * @see #getMeasuredHeight() 12121 * @see #setMeasuredDimension(int, int) 12122 * @see #getSuggestedMinimumHeight() 12123 * @see #getSuggestedMinimumWidth() 12124 * @see android.view.View.MeasureSpec#getMode(int) 12125 * @see android.view.View.MeasureSpec#getSize(int) 12126 */ 12127 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 12128 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 12129 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 12130 } 12131 12132 /** 12133 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the 12134 * measured width and measured height. Failing to do so will trigger an 12135 * exception at measurement time.</p> 12136 * 12137 * @param measuredWidth The measured width of this view. May be a complex 12138 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 12139 * {@link #MEASURED_STATE_TOO_SMALL}. 12140 * @param measuredHeight The measured height of this view. May be a complex 12141 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 12142 * {@link #MEASURED_STATE_TOO_SMALL}. 12143 */ 12144 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 12145 mMeasuredWidth = measuredWidth; 12146 mMeasuredHeight = measuredHeight; 12147 12148 mPrivateFlags |= MEASURED_DIMENSION_SET; 12149 } 12150 12151 /** 12152 * Merge two states as returned by {@link #getMeasuredState()}. 12153 * @param curState The current state as returned from a view or the result 12154 * of combining multiple views. 12155 * @param newState The new view state to combine. 12156 * @return Returns a new integer reflecting the combination of the two 12157 * states. 12158 */ 12159 public static int combineMeasuredStates(int curState, int newState) { 12160 return curState | newState; 12161 } 12162 12163 /** 12164 * Version of {@link #resolveSizeAndState(int, int, int)} 12165 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 12166 */ 12167 public static int resolveSize(int size, int measureSpec) { 12168 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 12169 } 12170 12171 /** 12172 * Utility to reconcile a desired size and state, with constraints imposed 12173 * by a MeasureSpec. Will take the desired size, unless a different size 12174 * is imposed by the constraints. The returned value is a compound integer, 12175 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 12176 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 12177 * size is smaller than the size the view wants to be. 12178 * 12179 * @param size How big the view wants to be 12180 * @param measureSpec Constraints imposed by the parent 12181 * @return Size information bit mask as defined by 12182 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 12183 */ 12184 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 12185 int result = size; 12186 int specMode = MeasureSpec.getMode(measureSpec); 12187 int specSize = MeasureSpec.getSize(measureSpec); 12188 switch (specMode) { 12189 case MeasureSpec.UNSPECIFIED: 12190 result = size; 12191 break; 12192 case MeasureSpec.AT_MOST: 12193 if (specSize < size) { 12194 result = specSize | MEASURED_STATE_TOO_SMALL; 12195 } else { 12196 result = size; 12197 } 12198 break; 12199 case MeasureSpec.EXACTLY: 12200 result = specSize; 12201 break; 12202 } 12203 return result | (childMeasuredState&MEASURED_STATE_MASK); 12204 } 12205 12206 /** 12207 * Utility to return a default size. Uses the supplied size if the 12208 * MeasureSpec imposed no constraints. Will get larger if allowed 12209 * by the MeasureSpec. 12210 * 12211 * @param size Default size for this view 12212 * @param measureSpec Constraints imposed by the parent 12213 * @return The size this view should be. 12214 */ 12215 public static int getDefaultSize(int size, int measureSpec) { 12216 int result = size; 12217 int specMode = MeasureSpec.getMode(measureSpec); 12218 int specSize = MeasureSpec.getSize(measureSpec); 12219 12220 switch (specMode) { 12221 case MeasureSpec.UNSPECIFIED: 12222 result = size; 12223 break; 12224 case MeasureSpec.AT_MOST: 12225 case MeasureSpec.EXACTLY: 12226 result = specSize; 12227 break; 12228 } 12229 return result; 12230 } 12231 12232 /** 12233 * Returns the suggested minimum height that the view should use. This 12234 * returns the maximum of the view's minimum height 12235 * and the background's minimum height 12236 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 12237 * <p> 12238 * When being used in {@link #onMeasure(int, int)}, the caller should still 12239 * ensure the returned height is within the requirements of the parent. 12240 * 12241 * @return The suggested minimum height of the view. 12242 */ 12243 protected int getSuggestedMinimumHeight() { 12244 int suggestedMinHeight = mMinHeight; 12245 12246 if (mBGDrawable != null) { 12247 final int bgMinHeight = mBGDrawable.getMinimumHeight(); 12248 if (suggestedMinHeight < bgMinHeight) { 12249 suggestedMinHeight = bgMinHeight; 12250 } 12251 } 12252 12253 return suggestedMinHeight; 12254 } 12255 12256 /** 12257 * Returns the suggested minimum width that the view should use. This 12258 * returns the maximum of the view's minimum width) 12259 * and the background's minimum width 12260 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 12261 * <p> 12262 * When being used in {@link #onMeasure(int, int)}, the caller should still 12263 * ensure the returned width is within the requirements of the parent. 12264 * 12265 * @return The suggested minimum width of the view. 12266 */ 12267 protected int getSuggestedMinimumWidth() { 12268 int suggestedMinWidth = mMinWidth; 12269 12270 if (mBGDrawable != null) { 12271 final int bgMinWidth = mBGDrawable.getMinimumWidth(); 12272 if (suggestedMinWidth < bgMinWidth) { 12273 suggestedMinWidth = bgMinWidth; 12274 } 12275 } 12276 12277 return suggestedMinWidth; 12278 } 12279 12280 /** 12281 * Sets the minimum height of the view. It is not guaranteed the view will 12282 * be able to achieve this minimum height (for example, if its parent layout 12283 * constrains it with less available height). 12284 * 12285 * @param minHeight The minimum height the view will try to be. 12286 */ 12287 public void setMinimumHeight(int minHeight) { 12288 mMinHeight = minHeight; 12289 } 12290 12291 /** 12292 * Sets the minimum width of the view. It is not guaranteed the view will 12293 * be able to achieve this minimum width (for example, if its parent layout 12294 * constrains it with less available width). 12295 * 12296 * @param minWidth The minimum width the view will try to be. 12297 */ 12298 public void setMinimumWidth(int minWidth) { 12299 mMinWidth = minWidth; 12300 } 12301 12302 /** 12303 * Get the animation currently associated with this view. 12304 * 12305 * @return The animation that is currently playing or 12306 * scheduled to play for this view. 12307 */ 12308 public Animation getAnimation() { 12309 return mCurrentAnimation; 12310 } 12311 12312 /** 12313 * Start the specified animation now. 12314 * 12315 * @param animation the animation to start now 12316 */ 12317 public void startAnimation(Animation animation) { 12318 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 12319 setAnimation(animation); 12320 invalidateParentCaches(); 12321 invalidate(true); 12322 } 12323 12324 /** 12325 * Cancels any animations for this view. 12326 */ 12327 public void clearAnimation() { 12328 if (mCurrentAnimation != null) { 12329 mCurrentAnimation.detach(); 12330 } 12331 mCurrentAnimation = null; 12332 invalidateParentIfNeeded(); 12333 } 12334 12335 /** 12336 * Sets the next animation to play for this view. 12337 * If you want the animation to play immediately, use 12338 * startAnimation. This method provides allows fine-grained 12339 * control over the start time and invalidation, but you 12340 * must make sure that 1) the animation has a start time set, and 12341 * 2) the view will be invalidated when the animation is supposed to 12342 * start. 12343 * 12344 * @param animation The next animation, or null. 12345 */ 12346 public void setAnimation(Animation animation) { 12347 mCurrentAnimation = animation; 12348 if (animation != null) { 12349 animation.reset(); 12350 } 12351 } 12352 12353 /** 12354 * Invoked by a parent ViewGroup to notify the start of the animation 12355 * currently associated with this view. If you override this method, 12356 * always call super.onAnimationStart(); 12357 * 12358 * @see #setAnimation(android.view.animation.Animation) 12359 * @see #getAnimation() 12360 */ 12361 protected void onAnimationStart() { 12362 mPrivateFlags |= ANIMATION_STARTED; 12363 } 12364 12365 /** 12366 * Invoked by a parent ViewGroup to notify the end of the animation 12367 * currently associated with this view. If you override this method, 12368 * always call super.onAnimationEnd(); 12369 * 12370 * @see #setAnimation(android.view.animation.Animation) 12371 * @see #getAnimation() 12372 */ 12373 protected void onAnimationEnd() { 12374 mPrivateFlags &= ~ANIMATION_STARTED; 12375 } 12376 12377 /** 12378 * Invoked if there is a Transform that involves alpha. Subclass that can 12379 * draw themselves with the specified alpha should return true, and then 12380 * respect that alpha when their onDraw() is called. If this returns false 12381 * then the view may be redirected to draw into an offscreen buffer to 12382 * fulfill the request, which will look fine, but may be slower than if the 12383 * subclass handles it internally. The default implementation returns false. 12384 * 12385 * @param alpha The alpha (0..255) to apply to the view's drawing 12386 * @return true if the view can draw with the specified alpha. 12387 */ 12388 protected boolean onSetAlpha(int alpha) { 12389 return false; 12390 } 12391 12392 /** 12393 * This is used by the RootView to perform an optimization when 12394 * the view hierarchy contains one or several SurfaceView. 12395 * SurfaceView is always considered transparent, but its children are not, 12396 * therefore all View objects remove themselves from the global transparent 12397 * region (passed as a parameter to this function). 12398 * 12399 * @param region The transparent region for this ViewAncestor (window). 12400 * 12401 * @return Returns true if the effective visibility of the view at this 12402 * point is opaque, regardless of the transparent region; returns false 12403 * if it is possible for underlying windows to be seen behind the view. 12404 * 12405 * {@hide} 12406 */ 12407 public boolean gatherTransparentRegion(Region region) { 12408 final AttachInfo attachInfo = mAttachInfo; 12409 if (region != null && attachInfo != null) { 12410 final int pflags = mPrivateFlags; 12411 if ((pflags & SKIP_DRAW) == 0) { 12412 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 12413 // remove it from the transparent region. 12414 final int[] location = attachInfo.mTransparentLocation; 12415 getLocationInWindow(location); 12416 region.op(location[0], location[1], location[0] + mRight - mLeft, 12417 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 12418 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) { 12419 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 12420 // exists, so we remove the background drawable's non-transparent 12421 // parts from this transparent region. 12422 applyDrawableToTransparentRegion(mBGDrawable, region); 12423 } 12424 } 12425 return true; 12426 } 12427 12428 /** 12429 * Play a sound effect for this view. 12430 * 12431 * <p>The framework will play sound effects for some built in actions, such as 12432 * clicking, but you may wish to play these effects in your widget, 12433 * for instance, for internal navigation. 12434 * 12435 * <p>The sound effect will only be played if sound effects are enabled by the user, and 12436 * {@link #isSoundEffectsEnabled()} is true. 12437 * 12438 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 12439 */ 12440 public void playSoundEffect(int soundConstant) { 12441 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 12442 return; 12443 } 12444 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 12445 } 12446 12447 /** 12448 * BZZZTT!!1! 12449 * 12450 * <p>Provide haptic feedback to the user for this view. 12451 * 12452 * <p>The framework will provide haptic feedback for some built in actions, 12453 * such as long presses, but you may wish to provide feedback for your 12454 * own widget. 12455 * 12456 * <p>The feedback will only be performed if 12457 * {@link #isHapticFeedbackEnabled()} is true. 12458 * 12459 * @param feedbackConstant One of the constants defined in 12460 * {@link HapticFeedbackConstants} 12461 */ 12462 public boolean performHapticFeedback(int feedbackConstant) { 12463 return performHapticFeedback(feedbackConstant, 0); 12464 } 12465 12466 /** 12467 * BZZZTT!!1! 12468 * 12469 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 12470 * 12471 * @param feedbackConstant One of the constants defined in 12472 * {@link HapticFeedbackConstants} 12473 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 12474 */ 12475 public boolean performHapticFeedback(int feedbackConstant, int flags) { 12476 if (mAttachInfo == null) { 12477 return false; 12478 } 12479 //noinspection SimplifiableIfStatement 12480 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 12481 && !isHapticFeedbackEnabled()) { 12482 return false; 12483 } 12484 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 12485 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 12486 } 12487 12488 /** 12489 * Request that the visibility of the status bar be changed. 12490 * @param visibility Either {@link #STATUS_BAR_VISIBLE} or {@link #STATUS_BAR_HIDDEN}. 12491 */ 12492 public void setSystemUiVisibility(int visibility) { 12493 if (visibility != mSystemUiVisibility) { 12494 mSystemUiVisibility = visibility; 12495 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 12496 mParent.recomputeViewAttributes(this); 12497 } 12498 } 12499 } 12500 12501 /** 12502 * Returns the status bar visibility that this view has requested. 12503 * @return Either {@link #STATUS_BAR_VISIBLE} or {@link #STATUS_BAR_HIDDEN}. 12504 */ 12505 public int getSystemUiVisibility() { 12506 return mSystemUiVisibility; 12507 } 12508 12509 /** 12510 * Set a listener to receive callbacks when the visibility of the system bar changes. 12511 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 12512 */ 12513 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 12514 mOnSystemUiVisibilityChangeListener = l; 12515 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 12516 mParent.recomputeViewAttributes(this); 12517 } 12518 } 12519 12520 /** 12521 */ 12522 public void dispatchSystemUiVisibilityChanged(int visibility) { 12523 if (mOnSystemUiVisibilityChangeListener != null) { 12524 mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 12525 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 12526 } 12527 } 12528 12529 /** 12530 * Creates an image that the system displays during the drag and drop 12531 * operation. This is called a "drag shadow". The default implementation 12532 * for a DragShadowBuilder based on a View returns an image that has exactly the same 12533 * appearance as the given View. The default also positions the center of the drag shadow 12534 * directly under the touch point. If no View is provided (the constructor with no parameters 12535 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 12536 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 12537 * default is an invisible drag shadow. 12538 * <p> 12539 * You are not required to use the View you provide to the constructor as the basis of the 12540 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 12541 * anything you want as the drag shadow. 12542 * </p> 12543 * <p> 12544 * You pass a DragShadowBuilder object to the system when you start the drag. The system 12545 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 12546 * size and position of the drag shadow. It uses this data to construct a 12547 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 12548 * so that your application can draw the shadow image in the Canvas. 12549 * </p> 12550 */ 12551 public static class DragShadowBuilder { 12552 private final WeakReference<View> mView; 12553 12554 /** 12555 * Constructs a shadow image builder based on a View. By default, the resulting drag 12556 * shadow will have the same appearance and dimensions as the View, with the touch point 12557 * over the center of the View. 12558 * @param view A View. Any View in scope can be used. 12559 */ 12560 public DragShadowBuilder(View view) { 12561 mView = new WeakReference<View>(view); 12562 } 12563 12564 /** 12565 * Construct a shadow builder object with no associated View. This 12566 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 12567 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 12568 * to supply the drag shadow's dimensions and appearance without 12569 * reference to any View object. If they are not overridden, then the result is an 12570 * invisible drag shadow. 12571 */ 12572 public DragShadowBuilder() { 12573 mView = new WeakReference<View>(null); 12574 } 12575 12576 /** 12577 * Returns the View object that had been passed to the 12578 * {@link #View.DragShadowBuilder(View)} 12579 * constructor. If that View parameter was {@code null} or if the 12580 * {@link #View.DragShadowBuilder()} 12581 * constructor was used to instantiate the builder object, this method will return 12582 * null. 12583 * 12584 * @return The View object associate with this builder object. 12585 */ 12586 @SuppressWarnings({"JavadocReference"}) 12587 final public View getView() { 12588 return mView.get(); 12589 } 12590 12591 /** 12592 * Provides the metrics for the shadow image. These include the dimensions of 12593 * the shadow image, and the point within that shadow that should 12594 * be centered under the touch location while dragging. 12595 * <p> 12596 * The default implementation sets the dimensions of the shadow to be the 12597 * same as the dimensions of the View itself and centers the shadow under 12598 * the touch point. 12599 * </p> 12600 * 12601 * @param shadowSize A {@link android.graphics.Point} containing the width and height 12602 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 12603 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 12604 * image. 12605 * 12606 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 12607 * shadow image that should be underneath the touch point during the drag and drop 12608 * operation. Your application must set {@link android.graphics.Point#x} to the 12609 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 12610 */ 12611 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 12612 final View view = mView.get(); 12613 if (view != null) { 12614 shadowSize.set(view.getWidth(), view.getHeight()); 12615 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 12616 } else { 12617 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 12618 } 12619 } 12620 12621 /** 12622 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 12623 * based on the dimensions it received from the 12624 * {@link #onProvideShadowMetrics(Point, Point)} callback. 12625 * 12626 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 12627 */ 12628 public void onDrawShadow(Canvas canvas) { 12629 final View view = mView.get(); 12630 if (view != null) { 12631 view.draw(canvas); 12632 } else { 12633 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 12634 } 12635 } 12636 } 12637 12638 /** 12639 * Starts a drag and drop operation. When your application calls this method, it passes a 12640 * {@link android.view.View.DragShadowBuilder} object to the system. The 12641 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 12642 * to get metrics for the drag shadow, and then calls the object's 12643 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 12644 * <p> 12645 * Once the system has the drag shadow, it begins the drag and drop operation by sending 12646 * drag events to all the View objects in your application that are currently visible. It does 12647 * this either by calling the View object's drag listener (an implementation of 12648 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 12649 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 12650 * Both are passed a {@link android.view.DragEvent} object that has a 12651 * {@link android.view.DragEvent#getAction()} value of 12652 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 12653 * </p> 12654 * <p> 12655 * Your application can invoke startDrag() on any attached View object. The View object does not 12656 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 12657 * be related to the View the user selected for dragging. 12658 * </p> 12659 * @param data A {@link android.content.ClipData} object pointing to the data to be 12660 * transferred by the drag and drop operation. 12661 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 12662 * drag shadow. 12663 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 12664 * drop operation. This Object is put into every DragEvent object sent by the system during the 12665 * current drag. 12666 * <p> 12667 * myLocalState is a lightweight mechanism for the sending information from the dragged View 12668 * to the target Views. For example, it can contain flags that differentiate between a 12669 * a copy operation and a move operation. 12670 * </p> 12671 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 12672 * so the parameter should be set to 0. 12673 * @return {@code true} if the method completes successfully, or 12674 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 12675 * do a drag, and so no drag operation is in progress. 12676 */ 12677 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 12678 Object myLocalState, int flags) { 12679 if (ViewDebug.DEBUG_DRAG) { 12680 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 12681 } 12682 boolean okay = false; 12683 12684 Point shadowSize = new Point(); 12685 Point shadowTouchPoint = new Point(); 12686 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 12687 12688 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 12689 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 12690 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 12691 } 12692 12693 if (ViewDebug.DEBUG_DRAG) { 12694 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 12695 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 12696 } 12697 Surface surface = new Surface(); 12698 try { 12699 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 12700 flags, shadowSize.x, shadowSize.y, surface); 12701 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 12702 + " surface=" + surface); 12703 if (token != null) { 12704 Canvas canvas = surface.lockCanvas(null); 12705 try { 12706 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 12707 shadowBuilder.onDrawShadow(canvas); 12708 } finally { 12709 surface.unlockCanvasAndPost(canvas); 12710 } 12711 12712 final ViewRootImpl root = getViewRootImpl(); 12713 12714 // Cache the local state object for delivery with DragEvents 12715 root.setLocalDragState(myLocalState); 12716 12717 // repurpose 'shadowSize' for the last touch point 12718 root.getLastTouchPoint(shadowSize); 12719 12720 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 12721 shadowSize.x, shadowSize.y, 12722 shadowTouchPoint.x, shadowTouchPoint.y, data); 12723 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 12724 } 12725 } catch (Exception e) { 12726 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 12727 surface.destroy(); 12728 } 12729 12730 return okay; 12731 } 12732 12733 /** 12734 * Handles drag events sent by the system following a call to 12735 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 12736 *<p> 12737 * When the system calls this method, it passes a 12738 * {@link android.view.DragEvent} object. A call to 12739 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 12740 * in DragEvent. The method uses these to determine what is happening in the drag and drop 12741 * operation. 12742 * @param event The {@link android.view.DragEvent} sent by the system. 12743 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 12744 * in DragEvent, indicating the type of drag event represented by this object. 12745 * @return {@code true} if the method was successful, otherwise {@code false}. 12746 * <p> 12747 * The method should return {@code true} in response to an action type of 12748 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 12749 * operation. 12750 * </p> 12751 * <p> 12752 * The method should also return {@code true} in response to an action type of 12753 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 12754 * {@code false} if it didn't. 12755 * </p> 12756 */ 12757 public boolean onDragEvent(DragEvent event) { 12758 return false; 12759 } 12760 12761 /** 12762 * Detects if this View is enabled and has a drag event listener. 12763 * If both are true, then it calls the drag event listener with the 12764 * {@link android.view.DragEvent} it received. If the drag event listener returns 12765 * {@code true}, then dispatchDragEvent() returns {@code true}. 12766 * <p> 12767 * For all other cases, the method calls the 12768 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 12769 * method and returns its result. 12770 * </p> 12771 * <p> 12772 * This ensures that a drag event is always consumed, even if the View does not have a drag 12773 * event listener. However, if the View has a listener and the listener returns true, then 12774 * onDragEvent() is not called. 12775 * </p> 12776 */ 12777 public boolean dispatchDragEvent(DragEvent event) { 12778 //noinspection SimplifiableIfStatement 12779 if (mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 12780 && mOnDragListener.onDrag(this, event)) { 12781 return true; 12782 } 12783 return onDragEvent(event); 12784 } 12785 12786 boolean canAcceptDrag() { 12787 return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0; 12788 } 12789 12790 /** 12791 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 12792 * it is ever exposed at all. 12793 * @hide 12794 */ 12795 public void onCloseSystemDialogs(String reason) { 12796 } 12797 12798 /** 12799 * Given a Drawable whose bounds have been set to draw into this view, 12800 * update a Region being computed for 12801 * {@link #gatherTransparentRegion(android.graphics.Region)} so 12802 * that any non-transparent parts of the Drawable are removed from the 12803 * given transparent region. 12804 * 12805 * @param dr The Drawable whose transparency is to be applied to the region. 12806 * @param region A Region holding the current transparency information, 12807 * where any parts of the region that are set are considered to be 12808 * transparent. On return, this region will be modified to have the 12809 * transparency information reduced by the corresponding parts of the 12810 * Drawable that are not transparent. 12811 * {@hide} 12812 */ 12813 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 12814 if (DBG) { 12815 Log.i("View", "Getting transparent region for: " + this); 12816 } 12817 final Region r = dr.getTransparentRegion(); 12818 final Rect db = dr.getBounds(); 12819 final AttachInfo attachInfo = mAttachInfo; 12820 if (r != null && attachInfo != null) { 12821 final int w = getRight()-getLeft(); 12822 final int h = getBottom()-getTop(); 12823 if (db.left > 0) { 12824 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 12825 r.op(0, 0, db.left, h, Region.Op.UNION); 12826 } 12827 if (db.right < w) { 12828 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 12829 r.op(db.right, 0, w, h, Region.Op.UNION); 12830 } 12831 if (db.top > 0) { 12832 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 12833 r.op(0, 0, w, db.top, Region.Op.UNION); 12834 } 12835 if (db.bottom < h) { 12836 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 12837 r.op(0, db.bottom, w, h, Region.Op.UNION); 12838 } 12839 final int[] location = attachInfo.mTransparentLocation; 12840 getLocationInWindow(location); 12841 r.translate(location[0], location[1]); 12842 region.op(r, Region.Op.INTERSECT); 12843 } else { 12844 region.op(db, Region.Op.DIFFERENCE); 12845 } 12846 } 12847 12848 private void checkForLongClick(int delayOffset) { 12849 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 12850 mHasPerformedLongPress = false; 12851 12852 if (mPendingCheckForLongPress == null) { 12853 mPendingCheckForLongPress = new CheckForLongPress(); 12854 } 12855 mPendingCheckForLongPress.rememberWindowAttachCount(); 12856 postDelayed(mPendingCheckForLongPress, 12857 ViewConfiguration.getLongPressTimeout() - delayOffset); 12858 } 12859 } 12860 12861 /** 12862 * Inflate a view from an XML resource. This convenience method wraps the {@link 12863 * LayoutInflater} class, which provides a full range of options for view inflation. 12864 * 12865 * @param context The Context object for your activity or application. 12866 * @param resource The resource ID to inflate 12867 * @param root A view group that will be the parent. Used to properly inflate the 12868 * layout_* parameters. 12869 * @see LayoutInflater 12870 */ 12871 public static View inflate(Context context, int resource, ViewGroup root) { 12872 LayoutInflater factory = LayoutInflater.from(context); 12873 return factory.inflate(resource, root); 12874 } 12875 12876 /** 12877 * Scroll the view with standard behavior for scrolling beyond the normal 12878 * content boundaries. Views that call this method should override 12879 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 12880 * results of an over-scroll operation. 12881 * 12882 * Views can use this method to handle any touch or fling-based scrolling. 12883 * 12884 * @param deltaX Change in X in pixels 12885 * @param deltaY Change in Y in pixels 12886 * @param scrollX Current X scroll value in pixels before applying deltaX 12887 * @param scrollY Current Y scroll value in pixels before applying deltaY 12888 * @param scrollRangeX Maximum content scroll range along the X axis 12889 * @param scrollRangeY Maximum content scroll range along the Y axis 12890 * @param maxOverScrollX Number of pixels to overscroll by in either direction 12891 * along the X axis. 12892 * @param maxOverScrollY Number of pixels to overscroll by in either direction 12893 * along the Y axis. 12894 * @param isTouchEvent true if this scroll operation is the result of a touch event. 12895 * @return true if scrolling was clamped to an over-scroll boundary along either 12896 * axis, false otherwise. 12897 */ 12898 @SuppressWarnings({"UnusedParameters"}) 12899 protected boolean overScrollBy(int deltaX, int deltaY, 12900 int scrollX, int scrollY, 12901 int scrollRangeX, int scrollRangeY, 12902 int maxOverScrollX, int maxOverScrollY, 12903 boolean isTouchEvent) { 12904 final int overScrollMode = mOverScrollMode; 12905 final boolean canScrollHorizontal = 12906 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 12907 final boolean canScrollVertical = 12908 computeVerticalScrollRange() > computeVerticalScrollExtent(); 12909 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 12910 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 12911 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 12912 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 12913 12914 int newScrollX = scrollX + deltaX; 12915 if (!overScrollHorizontal) { 12916 maxOverScrollX = 0; 12917 } 12918 12919 int newScrollY = scrollY + deltaY; 12920 if (!overScrollVertical) { 12921 maxOverScrollY = 0; 12922 } 12923 12924 // Clamp values if at the limits and record 12925 final int left = -maxOverScrollX; 12926 final int right = maxOverScrollX + scrollRangeX; 12927 final int top = -maxOverScrollY; 12928 final int bottom = maxOverScrollY + scrollRangeY; 12929 12930 boolean clampedX = false; 12931 if (newScrollX > right) { 12932 newScrollX = right; 12933 clampedX = true; 12934 } else if (newScrollX < left) { 12935 newScrollX = left; 12936 clampedX = true; 12937 } 12938 12939 boolean clampedY = false; 12940 if (newScrollY > bottom) { 12941 newScrollY = bottom; 12942 clampedY = true; 12943 } else if (newScrollY < top) { 12944 newScrollY = top; 12945 clampedY = true; 12946 } 12947 12948 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 12949 12950 return clampedX || clampedY; 12951 } 12952 12953 /** 12954 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 12955 * respond to the results of an over-scroll operation. 12956 * 12957 * @param scrollX New X scroll value in pixels 12958 * @param scrollY New Y scroll value in pixels 12959 * @param clampedX True if scrollX was clamped to an over-scroll boundary 12960 * @param clampedY True if scrollY was clamped to an over-scroll boundary 12961 */ 12962 protected void onOverScrolled(int scrollX, int scrollY, 12963 boolean clampedX, boolean clampedY) { 12964 // Intentionally empty. 12965 } 12966 12967 /** 12968 * Returns the over-scroll mode for this view. The result will be 12969 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 12970 * (allow over-scrolling only if the view content is larger than the container), 12971 * or {@link #OVER_SCROLL_NEVER}. 12972 * 12973 * @return This view's over-scroll mode. 12974 */ 12975 public int getOverScrollMode() { 12976 return mOverScrollMode; 12977 } 12978 12979 /** 12980 * Set the over-scroll mode for this view. Valid over-scroll modes are 12981 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 12982 * (allow over-scrolling only if the view content is larger than the container), 12983 * or {@link #OVER_SCROLL_NEVER}. 12984 * 12985 * Setting the over-scroll mode of a view will have an effect only if the 12986 * view is capable of scrolling. 12987 * 12988 * @param overScrollMode The new over-scroll mode for this view. 12989 */ 12990 public void setOverScrollMode(int overScrollMode) { 12991 if (overScrollMode != OVER_SCROLL_ALWAYS && 12992 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 12993 overScrollMode != OVER_SCROLL_NEVER) { 12994 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 12995 } 12996 mOverScrollMode = overScrollMode; 12997 } 12998 12999 /** 13000 * Gets a scale factor that determines the distance the view should scroll 13001 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 13002 * @return The vertical scroll scale factor. 13003 * @hide 13004 */ 13005 protected float getVerticalScrollFactor() { 13006 if (mVerticalScrollFactor == 0) { 13007 TypedValue outValue = new TypedValue(); 13008 if (!mContext.getTheme().resolveAttribute( 13009 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 13010 throw new IllegalStateException( 13011 "Expected theme to define listPreferredItemHeight."); 13012 } 13013 mVerticalScrollFactor = outValue.getDimension( 13014 mContext.getResources().getDisplayMetrics()); 13015 } 13016 return mVerticalScrollFactor; 13017 } 13018 13019 /** 13020 * Gets a scale factor that determines the distance the view should scroll 13021 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 13022 * @return The horizontal scroll scale factor. 13023 * @hide 13024 */ 13025 protected float getHorizontalScrollFactor() { 13026 // TODO: Should use something else. 13027 return getVerticalScrollFactor(); 13028 } 13029 13030 /** 13031 * Return the value specifying the text direction or policy that was set with 13032 * {@link #setTextDirection(int)}. 13033 * 13034 * @return the defined text direction. It can be one of: 13035 * 13036 * {@link #TEXT_DIRECTION_INHERIT}, 13037 * {@link #TEXT_DIRECTION_FIRST_STRONG} 13038 * {@link #TEXT_DIRECTION_ANY_RTL}, 13039 * {@link #TEXT_DIRECTION_CHAR_COUNT}, 13040 * {@link #TEXT_DIRECTION_LTR}, 13041 * {@link #TEXT_DIRECTION_RTL}, 13042 * 13043 * @hide 13044 */ 13045 public int getTextDirection() { 13046 return mTextDirection; 13047 } 13048 13049 /** 13050 * Set the text direction. 13051 * 13052 * @param textDirection the direction to set. Should be one of: 13053 * 13054 * {@link #TEXT_DIRECTION_INHERIT}, 13055 * {@link #TEXT_DIRECTION_FIRST_STRONG} 13056 * {@link #TEXT_DIRECTION_ANY_RTL}, 13057 * {@link #TEXT_DIRECTION_CHAR_COUNT}, 13058 * {@link #TEXT_DIRECTION_LTR}, 13059 * {@link #TEXT_DIRECTION_RTL}, 13060 * 13061 * @hide 13062 */ 13063 public void setTextDirection(int textDirection) { 13064 if (textDirection != mTextDirection) { 13065 mTextDirection = textDirection; 13066 resetResolvedTextDirection(); 13067 requestLayout(); 13068 } 13069 } 13070 13071 /** 13072 * Return the resolved text direction. 13073 * 13074 * @return the resolved text direction. Return one of: 13075 * 13076 * {@link #TEXT_DIRECTION_FIRST_STRONG} 13077 * {@link #TEXT_DIRECTION_ANY_RTL}, 13078 * {@link #TEXT_DIRECTION_CHAR_COUNT}, 13079 * {@link #TEXT_DIRECTION_LTR}, 13080 * {@link #TEXT_DIRECTION_RTL}, 13081 * 13082 * @hide 13083 */ 13084 public int getResolvedTextDirection() { 13085 if (mResolvedTextDirection == TEXT_DIRECTION_INHERIT) { 13086 resolveTextDirection(); 13087 } 13088 return mResolvedTextDirection; 13089 } 13090 13091 /** 13092 * Resolve the text direction. 13093 */ 13094 protected void resolveTextDirection() { 13095 if (mTextDirection != TEXT_DIRECTION_INHERIT) { 13096 mResolvedTextDirection = mTextDirection; 13097 return; 13098 } 13099 if (mParent != null && mParent instanceof ViewGroup) { 13100 mResolvedTextDirection = ((ViewGroup) mParent).getResolvedTextDirection(); 13101 return; 13102 } 13103 mResolvedTextDirection = TEXT_DIRECTION_FIRST_STRONG; 13104 } 13105 13106 /** 13107 * Reset resolved text direction. Will be resolved during a call to getResolvedTextDirection(). 13108 */ 13109 protected void resetResolvedTextDirection() { 13110 mResolvedTextDirection = TEXT_DIRECTION_INHERIT; 13111 } 13112 13113 // 13114 // Properties 13115 // 13116 /** 13117 * A Property wrapper around the <code>alpha</code> functionality handled by the 13118 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 13119 */ 13120 public static Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 13121 @Override 13122 public void setValue(View object, float value) { 13123 object.setAlpha(value); 13124 } 13125 13126 @Override 13127 public Float get(View object) { 13128 return object.getAlpha(); 13129 } 13130 }; 13131 13132 /** 13133 * A Property wrapper around the <code>translationX</code> functionality handled by the 13134 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 13135 */ 13136 public static Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 13137 @Override 13138 public void setValue(View object, float value) { 13139 object.setTranslationX(value); 13140 } 13141 13142 @Override 13143 public Float get(View object) { 13144 return object.getTranslationX(); 13145 } 13146 }; 13147 13148 /** 13149 * A Property wrapper around the <code>translationY</code> functionality handled by the 13150 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 13151 */ 13152 public static Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 13153 @Override 13154 public void setValue(View object, float value) { 13155 object.setTranslationY(value); 13156 } 13157 13158 @Override 13159 public Float get(View object) { 13160 return object.getTranslationY(); 13161 } 13162 }; 13163 13164 /** 13165 * A Property wrapper around the <code>x</code> functionality handled by the 13166 * {@link View#setX(float)} and {@link View#getX()} methods. 13167 */ 13168 public static Property<View, Float> X = new FloatProperty<View>("x") { 13169 @Override 13170 public void setValue(View object, float value) { 13171 object.setX(value); 13172 } 13173 13174 @Override 13175 public Float get(View object) { 13176 return object.getX(); 13177 } 13178 }; 13179 13180 /** 13181 * A Property wrapper around the <code>y</code> functionality handled by the 13182 * {@link View#setY(float)} and {@link View#getY()} methods. 13183 */ 13184 public static Property<View, Float> Y = new FloatProperty<View>("y") { 13185 @Override 13186 public void setValue(View object, float value) { 13187 object.setY(value); 13188 } 13189 13190 @Override 13191 public Float get(View object) { 13192 return object.getY(); 13193 } 13194 }; 13195 13196 /** 13197 * A Property wrapper around the <code>rotation</code> functionality handled by the 13198 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 13199 */ 13200 public static Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 13201 @Override 13202 public void setValue(View object, float value) { 13203 object.setRotation(value); 13204 } 13205 13206 @Override 13207 public Float get(View object) { 13208 return object.getRotation(); 13209 } 13210 }; 13211 13212 /** 13213 * A Property wrapper around the <code>rotationX</code> functionality handled by the 13214 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 13215 */ 13216 public static Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 13217 @Override 13218 public void setValue(View object, float value) { 13219 object.setRotationX(value); 13220 } 13221 13222 @Override 13223 public Float get(View object) { 13224 return object.getRotationX(); 13225 } 13226 }; 13227 13228 /** 13229 * A Property wrapper around the <code>rotationY</code> functionality handled by the 13230 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 13231 */ 13232 public static Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 13233 @Override 13234 public void setValue(View object, float value) { 13235 object.setRotationY(value); 13236 } 13237 13238 @Override 13239 public Float get(View object) { 13240 return object.getRotationY(); 13241 } 13242 }; 13243 13244 /** 13245 * A Property wrapper around the <code>scaleX</code> functionality handled by the 13246 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 13247 */ 13248 public static Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 13249 @Override 13250 public void setValue(View object, float value) { 13251 object.setScaleX(value); 13252 } 13253 13254 @Override 13255 public Float get(View object) { 13256 return object.getScaleX(); 13257 } 13258 }; 13259 13260 /** 13261 * A Property wrapper around the <code>scaleY</code> functionality handled by the 13262 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 13263 */ 13264 public static Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 13265 @Override 13266 public void setValue(View object, float value) { 13267 object.setScaleY(value); 13268 } 13269 13270 @Override 13271 public Float get(View object) { 13272 return object.getScaleY(); 13273 } 13274 }; 13275 13276 /** 13277 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 13278 * Each MeasureSpec represents a requirement for either the width or the height. 13279 * A MeasureSpec is comprised of a size and a mode. There are three possible 13280 * modes: 13281 * <dl> 13282 * <dt>UNSPECIFIED</dt> 13283 * <dd> 13284 * The parent has not imposed any constraint on the child. It can be whatever size 13285 * it wants. 13286 * </dd> 13287 * 13288 * <dt>EXACTLY</dt> 13289 * <dd> 13290 * The parent has determined an exact size for the child. The child is going to be 13291 * given those bounds regardless of how big it wants to be. 13292 * </dd> 13293 * 13294 * <dt>AT_MOST</dt> 13295 * <dd> 13296 * The child can be as large as it wants up to the specified size. 13297 * </dd> 13298 * </dl> 13299 * 13300 * MeasureSpecs are implemented as ints to reduce object allocation. This class 13301 * is provided to pack and unpack the <size, mode> tuple into the int. 13302 */ 13303 public static class MeasureSpec { 13304 private static final int MODE_SHIFT = 30; 13305 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 13306 13307 /** 13308 * Measure specification mode: The parent has not imposed any constraint 13309 * on the child. It can be whatever size it wants. 13310 */ 13311 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 13312 13313 /** 13314 * Measure specification mode: The parent has determined an exact size 13315 * for the child. The child is going to be given those bounds regardless 13316 * of how big it wants to be. 13317 */ 13318 public static final int EXACTLY = 1 << MODE_SHIFT; 13319 13320 /** 13321 * Measure specification mode: The child can be as large as it wants up 13322 * to the specified size. 13323 */ 13324 public static final int AT_MOST = 2 << MODE_SHIFT; 13325 13326 /** 13327 * Creates a measure specification based on the supplied size and mode. 13328 * 13329 * The mode must always be one of the following: 13330 * <ul> 13331 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 13332 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 13333 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 13334 * </ul> 13335 * 13336 * @param size the size of the measure specification 13337 * @param mode the mode of the measure specification 13338 * @return the measure specification based on size and mode 13339 */ 13340 public static int makeMeasureSpec(int size, int mode) { 13341 return size + mode; 13342 } 13343 13344 /** 13345 * Extracts the mode from the supplied measure specification. 13346 * 13347 * @param measureSpec the measure specification to extract the mode from 13348 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 13349 * {@link android.view.View.MeasureSpec#AT_MOST} or 13350 * {@link android.view.View.MeasureSpec#EXACTLY} 13351 */ 13352 public static int getMode(int measureSpec) { 13353 return (measureSpec & MODE_MASK); 13354 } 13355 13356 /** 13357 * Extracts the size from the supplied measure specification. 13358 * 13359 * @param measureSpec the measure specification to extract the size from 13360 * @return the size in pixels defined in the supplied measure specification 13361 */ 13362 public static int getSize(int measureSpec) { 13363 return (measureSpec & ~MODE_MASK); 13364 } 13365 13366 /** 13367 * Returns a String representation of the specified measure 13368 * specification. 13369 * 13370 * @param measureSpec the measure specification to convert to a String 13371 * @return a String with the following format: "MeasureSpec: MODE SIZE" 13372 */ 13373 public static String toString(int measureSpec) { 13374 int mode = getMode(measureSpec); 13375 int size = getSize(measureSpec); 13376 13377 StringBuilder sb = new StringBuilder("MeasureSpec: "); 13378 13379 if (mode == UNSPECIFIED) 13380 sb.append("UNSPECIFIED "); 13381 else if (mode == EXACTLY) 13382 sb.append("EXACTLY "); 13383 else if (mode == AT_MOST) 13384 sb.append("AT_MOST "); 13385 else 13386 sb.append(mode).append(" "); 13387 13388 sb.append(size); 13389 return sb.toString(); 13390 } 13391 } 13392 13393 class CheckForLongPress implements Runnable { 13394 13395 private int mOriginalWindowAttachCount; 13396 13397 public void run() { 13398 if (isPressed() && (mParent != null) 13399 && mOriginalWindowAttachCount == mWindowAttachCount) { 13400 if (performLongClick()) { 13401 mHasPerformedLongPress = true; 13402 } 13403 } 13404 } 13405 13406 public void rememberWindowAttachCount() { 13407 mOriginalWindowAttachCount = mWindowAttachCount; 13408 } 13409 } 13410 13411 private final class CheckForTap implements Runnable { 13412 public void run() { 13413 mPrivateFlags &= ~PREPRESSED; 13414 mPrivateFlags |= PRESSED; 13415 refreshDrawableState(); 13416 checkForLongClick(ViewConfiguration.getTapTimeout()); 13417 } 13418 } 13419 13420 private final class PerformClick implements Runnable { 13421 public void run() { 13422 performClick(); 13423 } 13424 } 13425 13426 /** @hide */ 13427 public void hackTurnOffWindowResizeAnim(boolean off) { 13428 mAttachInfo.mTurnOffWindowResizeAnim = off; 13429 } 13430 13431 /** 13432 * This method returns a ViewPropertyAnimator object, which can be used to animate 13433 * specific properties on this View. 13434 * 13435 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 13436 */ 13437 public ViewPropertyAnimator animate() { 13438 if (mAnimator == null) { 13439 mAnimator = new ViewPropertyAnimator(this); 13440 } 13441 return mAnimator; 13442 } 13443 13444 /** 13445 * Interface definition for a callback to be invoked when a key event is 13446 * dispatched to this view. The callback will be invoked before the key 13447 * event is given to the view. 13448 */ 13449 public interface OnKeyListener { 13450 /** 13451 * Called when a key is dispatched to a view. This allows listeners to 13452 * get a chance to respond before the target view. 13453 * 13454 * @param v The view the key has been dispatched to. 13455 * @param keyCode The code for the physical key that was pressed 13456 * @param event The KeyEvent object containing full information about 13457 * the event. 13458 * @return True if the listener has consumed the event, false otherwise. 13459 */ 13460 boolean onKey(View v, int keyCode, KeyEvent event); 13461 } 13462 13463 /** 13464 * Interface definition for a callback to be invoked when a touch event is 13465 * dispatched to this view. The callback will be invoked before the touch 13466 * event is given to the view. 13467 */ 13468 public interface OnTouchListener { 13469 /** 13470 * Called when a touch event is dispatched to a view. This allows listeners to 13471 * get a chance to respond before the target view. 13472 * 13473 * @param v The view the touch event has been dispatched to. 13474 * @param event The MotionEvent object containing full information about 13475 * the event. 13476 * @return True if the listener has consumed the event, false otherwise. 13477 */ 13478 boolean onTouch(View v, MotionEvent event); 13479 } 13480 13481 /** 13482 * Interface definition for a callback to be invoked when a hover event is 13483 * dispatched to this view. The callback will be invoked before the hover 13484 * event is given to the view. 13485 */ 13486 public interface OnHoverListener { 13487 /** 13488 * Called when a hover event is dispatched to a view. This allows listeners to 13489 * get a chance to respond before the target view. 13490 * 13491 * @param v The view the hover event has been dispatched to. 13492 * @param event The MotionEvent object containing full information about 13493 * the event. 13494 * @return True if the listener has consumed the event, false otherwise. 13495 */ 13496 boolean onHover(View v, MotionEvent event); 13497 } 13498 13499 /** 13500 * Interface definition for a callback to be invoked when a generic motion event is 13501 * dispatched to this view. The callback will be invoked before the generic motion 13502 * event is given to the view. 13503 */ 13504 public interface OnGenericMotionListener { 13505 /** 13506 * Called when a generic motion event is dispatched to a view. This allows listeners to 13507 * get a chance to respond before the target view. 13508 * 13509 * @param v The view the generic motion event has been dispatched to. 13510 * @param event The MotionEvent object containing full information about 13511 * the event. 13512 * @return True if the listener has consumed the event, false otherwise. 13513 */ 13514 boolean onGenericMotion(View v, MotionEvent event); 13515 } 13516 13517 /** 13518 * Interface definition for a callback to be invoked when a view has been clicked and held. 13519 */ 13520 public interface OnLongClickListener { 13521 /** 13522 * Called when a view has been clicked and held. 13523 * 13524 * @param v The view that was clicked and held. 13525 * 13526 * @return true if the callback consumed the long click, false otherwise. 13527 */ 13528 boolean onLongClick(View v); 13529 } 13530 13531 /** 13532 * Interface definition for a callback to be invoked when a drag is being dispatched 13533 * to this view. The callback will be invoked before the hosting view's own 13534 * onDrag(event) method. If the listener wants to fall back to the hosting view's 13535 * onDrag(event) behavior, it should return 'false' from this callback. 13536 */ 13537 public interface OnDragListener { 13538 /** 13539 * Called when a drag event is dispatched to a view. This allows listeners 13540 * to get a chance to override base View behavior. 13541 * 13542 * @param v The View that received the drag event. 13543 * @param event The {@link android.view.DragEvent} object for the drag event. 13544 * @return {@code true} if the drag event was handled successfully, or {@code false} 13545 * if the drag event was not handled. Note that {@code false} will trigger the View 13546 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 13547 */ 13548 boolean onDrag(View v, DragEvent event); 13549 } 13550 13551 /** 13552 * Interface definition for a callback to be invoked when the focus state of 13553 * a view changed. 13554 */ 13555 public interface OnFocusChangeListener { 13556 /** 13557 * Called when the focus state of a view has changed. 13558 * 13559 * @param v The view whose state has changed. 13560 * @param hasFocus The new focus state of v. 13561 */ 13562 void onFocusChange(View v, boolean hasFocus); 13563 } 13564 13565 /** 13566 * Interface definition for a callback to be invoked when a view is clicked. 13567 */ 13568 public interface OnClickListener { 13569 /** 13570 * Called when a view has been clicked. 13571 * 13572 * @param v The view that was clicked. 13573 */ 13574 void onClick(View v); 13575 } 13576 13577 /** 13578 * Interface definition for a callback to be invoked when the context menu 13579 * for this view is being built. 13580 */ 13581 public interface OnCreateContextMenuListener { 13582 /** 13583 * Called when the context menu for this view is being built. It is not 13584 * safe to hold onto the menu after this method returns. 13585 * 13586 * @param menu The context menu that is being built 13587 * @param v The view for which the context menu is being built 13588 * @param menuInfo Extra information about the item for which the 13589 * context menu should be shown. This information will vary 13590 * depending on the class of v. 13591 */ 13592 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 13593 } 13594 13595 /** 13596 * Interface definition for a callback to be invoked when the status bar changes 13597 * visibility. 13598 * 13599 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 13600 */ 13601 public interface OnSystemUiVisibilityChangeListener { 13602 /** 13603 * Called when the status bar changes visibility because of a call to 13604 * {@link View#setSystemUiVisibility(int)}. 13605 * 13606 * @param visibility {@link #STATUS_BAR_VISIBLE} or {@link #STATUS_BAR_HIDDEN}. 13607 */ 13608 public void onSystemUiVisibilityChange(int visibility); 13609 } 13610 13611 /** 13612 * Interface definition for a callback to be invoked when this view is attached 13613 * or detached from its window. 13614 */ 13615 public interface OnAttachStateChangeListener { 13616 /** 13617 * Called when the view is attached to a window. 13618 * @param v The view that was attached 13619 */ 13620 public void onViewAttachedToWindow(View v); 13621 /** 13622 * Called when the view is detached from a window. 13623 * @param v The view that was detached 13624 */ 13625 public void onViewDetachedFromWindow(View v); 13626 } 13627 13628 private final class UnsetPressedState implements Runnable { 13629 public void run() { 13630 setPressed(false); 13631 } 13632 } 13633 13634 /** 13635 * Base class for derived classes that want to save and restore their own 13636 * state in {@link android.view.View#onSaveInstanceState()}. 13637 */ 13638 public static class BaseSavedState extends AbsSavedState { 13639 /** 13640 * Constructor used when reading from a parcel. Reads the state of the superclass. 13641 * 13642 * @param source 13643 */ 13644 public BaseSavedState(Parcel source) { 13645 super(source); 13646 } 13647 13648 /** 13649 * Constructor called by derived classes when creating their SavedState objects 13650 * 13651 * @param superState The state of the superclass of this view 13652 */ 13653 public BaseSavedState(Parcelable superState) { 13654 super(superState); 13655 } 13656 13657 public static final Parcelable.Creator<BaseSavedState> CREATOR = 13658 new Parcelable.Creator<BaseSavedState>() { 13659 public BaseSavedState createFromParcel(Parcel in) { 13660 return new BaseSavedState(in); 13661 } 13662 13663 public BaseSavedState[] newArray(int size) { 13664 return new BaseSavedState[size]; 13665 } 13666 }; 13667 } 13668 13669 /** 13670 * A set of information given to a view when it is attached to its parent 13671 * window. 13672 */ 13673 static class AttachInfo { 13674 interface Callbacks { 13675 void playSoundEffect(int effectId); 13676 boolean performHapticFeedback(int effectId, boolean always); 13677 } 13678 13679 /** 13680 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 13681 * to a Handler. This class contains the target (View) to invalidate and 13682 * the coordinates of the dirty rectangle. 13683 * 13684 * For performance purposes, this class also implements a pool of up to 13685 * POOL_LIMIT objects that get reused. This reduces memory allocations 13686 * whenever possible. 13687 */ 13688 static class InvalidateInfo implements Poolable<InvalidateInfo> { 13689 private static final int POOL_LIMIT = 10; 13690 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool( 13691 Pools.finitePool(new PoolableManager<InvalidateInfo>() { 13692 public InvalidateInfo newInstance() { 13693 return new InvalidateInfo(); 13694 } 13695 13696 public void onAcquired(InvalidateInfo element) { 13697 } 13698 13699 public void onReleased(InvalidateInfo element) { 13700 } 13701 }, POOL_LIMIT) 13702 ); 13703 13704 private InvalidateInfo mNext; 13705 private boolean mIsPooled; 13706 13707 View target; 13708 13709 int left; 13710 int top; 13711 int right; 13712 int bottom; 13713 13714 public void setNextPoolable(InvalidateInfo element) { 13715 mNext = element; 13716 } 13717 13718 public InvalidateInfo getNextPoolable() { 13719 return mNext; 13720 } 13721 13722 static InvalidateInfo acquire() { 13723 return sPool.acquire(); 13724 } 13725 13726 void release() { 13727 sPool.release(this); 13728 } 13729 13730 public boolean isPooled() { 13731 return mIsPooled; 13732 } 13733 13734 public void setPooled(boolean isPooled) { 13735 mIsPooled = isPooled; 13736 } 13737 } 13738 13739 final IWindowSession mSession; 13740 13741 final IWindow mWindow; 13742 13743 final IBinder mWindowToken; 13744 13745 final Callbacks mRootCallbacks; 13746 13747 HardwareCanvas mHardwareCanvas; 13748 13749 /** 13750 * The top view of the hierarchy. 13751 */ 13752 View mRootView; 13753 13754 IBinder mPanelParentWindowToken; 13755 Surface mSurface; 13756 13757 boolean mHardwareAccelerated; 13758 boolean mHardwareAccelerationRequested; 13759 HardwareRenderer mHardwareRenderer; 13760 13761 /** 13762 * Scale factor used by the compatibility mode 13763 */ 13764 float mApplicationScale; 13765 13766 /** 13767 * Indicates whether the application is in compatibility mode 13768 */ 13769 boolean mScalingRequired; 13770 13771 /** 13772 * If set, ViewAncestor doesn't use its lame animation for when the window resizes. 13773 */ 13774 boolean mTurnOffWindowResizeAnim; 13775 13776 /** 13777 * Left position of this view's window 13778 */ 13779 int mWindowLeft; 13780 13781 /** 13782 * Top position of this view's window 13783 */ 13784 int mWindowTop; 13785 13786 /** 13787 * Indicates whether views need to use 32-bit drawing caches 13788 */ 13789 boolean mUse32BitDrawingCache; 13790 13791 /** 13792 * For windows that are full-screen but using insets to layout inside 13793 * of the screen decorations, these are the current insets for the 13794 * content of the window. 13795 */ 13796 final Rect mContentInsets = new Rect(); 13797 13798 /** 13799 * For windows that are full-screen but using insets to layout inside 13800 * of the screen decorations, these are the current insets for the 13801 * actual visible parts of the window. 13802 */ 13803 final Rect mVisibleInsets = new Rect(); 13804 13805 /** 13806 * The internal insets given by this window. This value is 13807 * supplied by the client (through 13808 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 13809 * be given to the window manager when changed to be used in laying 13810 * out windows behind it. 13811 */ 13812 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 13813 = new ViewTreeObserver.InternalInsetsInfo(); 13814 13815 /** 13816 * All views in the window's hierarchy that serve as scroll containers, 13817 * used to determine if the window can be resized or must be panned 13818 * to adjust for a soft input area. 13819 */ 13820 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 13821 13822 final KeyEvent.DispatcherState mKeyDispatchState 13823 = new KeyEvent.DispatcherState(); 13824 13825 /** 13826 * Indicates whether the view's window currently has the focus. 13827 */ 13828 boolean mHasWindowFocus; 13829 13830 /** 13831 * The current visibility of the window. 13832 */ 13833 int mWindowVisibility; 13834 13835 /** 13836 * Indicates the time at which drawing started to occur. 13837 */ 13838 long mDrawingTime; 13839 13840 /** 13841 * Indicates whether or not ignoring the DIRTY_MASK flags. 13842 */ 13843 boolean mIgnoreDirtyState; 13844 13845 /** 13846 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 13847 * to avoid clearing that flag prematurely. 13848 */ 13849 boolean mSetIgnoreDirtyState = false; 13850 13851 /** 13852 * Indicates whether the view's window is currently in touch mode. 13853 */ 13854 boolean mInTouchMode; 13855 13856 /** 13857 * Indicates that ViewAncestor should trigger a global layout change 13858 * the next time it performs a traversal 13859 */ 13860 boolean mRecomputeGlobalAttributes; 13861 13862 /** 13863 * Set during a traveral if any views want to keep the screen on. 13864 */ 13865 boolean mKeepScreenOn; 13866 13867 /** 13868 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 13869 */ 13870 int mSystemUiVisibility; 13871 13872 /** 13873 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 13874 * attached. 13875 */ 13876 boolean mHasSystemUiListeners; 13877 13878 /** 13879 * Set if the visibility of any views has changed. 13880 */ 13881 boolean mViewVisibilityChanged; 13882 13883 /** 13884 * Set to true if a view has been scrolled. 13885 */ 13886 boolean mViewScrollChanged; 13887 13888 /** 13889 * Global to the view hierarchy used as a temporary for dealing with 13890 * x/y points in the transparent region computations. 13891 */ 13892 final int[] mTransparentLocation = new int[2]; 13893 13894 /** 13895 * Global to the view hierarchy used as a temporary for dealing with 13896 * x/y points in the ViewGroup.invalidateChild implementation. 13897 */ 13898 final int[] mInvalidateChildLocation = new int[2]; 13899 13900 13901 /** 13902 * Global to the view hierarchy used as a temporary for dealing with 13903 * x/y location when view is transformed. 13904 */ 13905 final float[] mTmpTransformLocation = new float[2]; 13906 13907 /** 13908 * The view tree observer used to dispatch global events like 13909 * layout, pre-draw, touch mode change, etc. 13910 */ 13911 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 13912 13913 /** 13914 * A Canvas used by the view hierarchy to perform bitmap caching. 13915 */ 13916 Canvas mCanvas; 13917 13918 /** 13919 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 13920 * handler can be used to pump events in the UI events queue. 13921 */ 13922 final Handler mHandler; 13923 13924 /** 13925 * Identifier for messages requesting the view to be invalidated. 13926 * Such messages should be sent to {@link #mHandler}. 13927 */ 13928 static final int INVALIDATE_MSG = 0x1; 13929 13930 /** 13931 * Identifier for messages requesting the view to invalidate a region. 13932 * Such messages should be sent to {@link #mHandler}. 13933 */ 13934 static final int INVALIDATE_RECT_MSG = 0x2; 13935 13936 /** 13937 * Temporary for use in computing invalidate rectangles while 13938 * calling up the hierarchy. 13939 */ 13940 final Rect mTmpInvalRect = new Rect(); 13941 13942 /** 13943 * Temporary for use in computing hit areas with transformed views 13944 */ 13945 final RectF mTmpTransformRect = new RectF(); 13946 13947 /** 13948 * Temporary list for use in collecting focusable descendents of a view. 13949 */ 13950 final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24); 13951 13952 /** 13953 * The id of the window for accessibility purposes. 13954 */ 13955 int mAccessibilityWindowId = View.NO_ID; 13956 13957 /** 13958 * Creates a new set of attachment information with the specified 13959 * events handler and thread. 13960 * 13961 * @param handler the events handler the view must use 13962 */ 13963 AttachInfo(IWindowSession session, IWindow window, 13964 Handler handler, Callbacks effectPlayer) { 13965 mSession = session; 13966 mWindow = window; 13967 mWindowToken = window.asBinder(); 13968 mHandler = handler; 13969 mRootCallbacks = effectPlayer; 13970 } 13971 } 13972 13973 /** 13974 * <p>ScrollabilityCache holds various fields used by a View when scrolling 13975 * is supported. This avoids keeping too many unused fields in most 13976 * instances of View.</p> 13977 */ 13978 private static class ScrollabilityCache implements Runnable { 13979 13980 /** 13981 * Scrollbars are not visible 13982 */ 13983 public static final int OFF = 0; 13984 13985 /** 13986 * Scrollbars are visible 13987 */ 13988 public static final int ON = 1; 13989 13990 /** 13991 * Scrollbars are fading away 13992 */ 13993 public static final int FADING = 2; 13994 13995 public boolean fadeScrollBars; 13996 13997 public int fadingEdgeLength; 13998 public int scrollBarDefaultDelayBeforeFade; 13999 public int scrollBarFadeDuration; 14000 14001 public int scrollBarSize; 14002 public ScrollBarDrawable scrollBar; 14003 public float[] interpolatorValues; 14004 public View host; 14005 14006 public final Paint paint; 14007 public final Matrix matrix; 14008 public Shader shader; 14009 14010 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 14011 14012 private static final float[] OPAQUE = { 255 }; 14013 private static final float[] TRANSPARENT = { 0.0f }; 14014 14015 /** 14016 * When fading should start. This time moves into the future every time 14017 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 14018 */ 14019 public long fadeStartTime; 14020 14021 14022 /** 14023 * The current state of the scrollbars: ON, OFF, or FADING 14024 */ 14025 public int state = OFF; 14026 14027 private int mLastColor; 14028 14029 public ScrollabilityCache(ViewConfiguration configuration, View host) { 14030 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 14031 scrollBarSize = configuration.getScaledScrollBarSize(); 14032 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 14033 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 14034 14035 paint = new Paint(); 14036 matrix = new Matrix(); 14037 // use use a height of 1, and then wack the matrix each time we 14038 // actually use it. 14039 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 14040 14041 paint.setShader(shader); 14042 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 14043 this.host = host; 14044 } 14045 14046 public void setFadeColor(int color) { 14047 if (color != 0 && color != mLastColor) { 14048 mLastColor = color; 14049 color |= 0xFF000000; 14050 14051 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 14052 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 14053 14054 paint.setShader(shader); 14055 // Restore the default transfer mode (src_over) 14056 paint.setXfermode(null); 14057 } 14058 } 14059 14060 public void run() { 14061 long now = AnimationUtils.currentAnimationTimeMillis(); 14062 if (now >= fadeStartTime) { 14063 14064 // the animation fades the scrollbars out by changing 14065 // the opacity (alpha) from fully opaque to fully 14066 // transparent 14067 int nextFrame = (int) now; 14068 int framesCount = 0; 14069 14070 Interpolator interpolator = scrollBarInterpolator; 14071 14072 // Start opaque 14073 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 14074 14075 // End transparent 14076 nextFrame += scrollBarFadeDuration; 14077 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 14078 14079 state = FADING; 14080 14081 // Kick off the fade animation 14082 host.invalidate(true); 14083 } 14084 } 14085 } 14086 14087 /** 14088 * Resuable callback for sending 14089 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 14090 */ 14091 private class SendViewScrolledAccessibilityEvent implements Runnable { 14092 public volatile boolean mIsPending; 14093 14094 public void run() { 14095 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 14096 mIsPending = false; 14097 } 14098 } 14099} 14100