View.java revision 031d9c1389de2b9dac7f175af0b962e24b21d5be
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_saveEnabled 611 * @attr ref android.R.styleable#View_rotation 612 * @attr ref android.R.styleable#View_rotationX 613 * @attr ref android.R.styleable#View_rotationY 614 * @attr ref android.R.styleable#View_scaleX 615 * @attr ref android.R.styleable#View_scaleY 616 * @attr ref android.R.styleable#View_scrollX 617 * @attr ref android.R.styleable#View_scrollY 618 * @attr ref android.R.styleable#View_scrollbarSize 619 * @attr ref android.R.styleable#View_scrollbarStyle 620 * @attr ref android.R.styleable#View_scrollbars 621 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 622 * @attr ref android.R.styleable#View_scrollbarFadeDuration 623 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 624 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 625 * @attr ref android.R.styleable#View_scrollbarThumbVertical 626 * @attr ref android.R.styleable#View_scrollbarTrackVertical 627 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 628 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 629 * @attr ref android.R.styleable#View_soundEffectsEnabled 630 * @attr ref android.R.styleable#View_tag 631 * @attr ref android.R.styleable#View_transformPivotX 632 * @attr ref android.R.styleable#View_transformPivotY 633 * @attr ref android.R.styleable#View_translationX 634 * @attr ref android.R.styleable#View_translationY 635 * @attr ref android.R.styleable#View_visibility 636 * 637 * @see android.view.ViewGroup 638 */ 639public class View implements Drawable.Callback, Drawable.Callback2, KeyEvent.Callback, 640 AccessibilityEventSource { 641 private static final boolean DBG = false; 642 643 /** 644 * The logging tag used by this class with android.util.Log. 645 */ 646 protected static final String VIEW_LOG_TAG = "View"; 647 648 /** 649 * Used to mark a View that has no ID. 650 */ 651 public static final int NO_ID = -1; 652 653 /** 654 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 655 * calling setFlags. 656 */ 657 private static final int NOT_FOCUSABLE = 0x00000000; 658 659 /** 660 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 661 * setFlags. 662 */ 663 private static final int FOCUSABLE = 0x00000001; 664 665 /** 666 * Mask for use with setFlags indicating bits used for focus. 667 */ 668 private static final int FOCUSABLE_MASK = 0x00000001; 669 670 /** 671 * This view will adjust its padding to fit sytem windows (e.g. status bar) 672 */ 673 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 674 675 /** 676 * This view is visible. 677 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 678 * android:visibility}. 679 */ 680 public static final int VISIBLE = 0x00000000; 681 682 /** 683 * This view is invisible, but it still takes up space for layout purposes. 684 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 685 * android:visibility}. 686 */ 687 public static final int INVISIBLE = 0x00000004; 688 689 /** 690 * This view is invisible, and it doesn't take any space for layout 691 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 692 * android:visibility}. 693 */ 694 public static final int GONE = 0x00000008; 695 696 /** 697 * Mask for use with setFlags indicating bits used for visibility. 698 * {@hide} 699 */ 700 static final int VISIBILITY_MASK = 0x0000000C; 701 702 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 703 704 /** 705 * This view is enabled. Intrepretation varies by subclass. 706 * Use with ENABLED_MASK when calling setFlags. 707 * {@hide} 708 */ 709 static final int ENABLED = 0x00000000; 710 711 /** 712 * This view is disabled. Intrepretation varies by subclass. 713 * Use with ENABLED_MASK when calling setFlags. 714 * {@hide} 715 */ 716 static final int DISABLED = 0x00000020; 717 718 /** 719 * Mask for use with setFlags indicating bits used for indicating whether 720 * this view is enabled 721 * {@hide} 722 */ 723 static final int ENABLED_MASK = 0x00000020; 724 725 /** 726 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 727 * called and further optimizations will be performed. It is okay to have 728 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 729 * {@hide} 730 */ 731 static final int WILL_NOT_DRAW = 0x00000080; 732 733 /** 734 * Mask for use with setFlags indicating bits used for indicating whether 735 * this view is will draw 736 * {@hide} 737 */ 738 static final int DRAW_MASK = 0x00000080; 739 740 /** 741 * <p>This view doesn't show scrollbars.</p> 742 * {@hide} 743 */ 744 static final int SCROLLBARS_NONE = 0x00000000; 745 746 /** 747 * <p>This view shows horizontal scrollbars.</p> 748 * {@hide} 749 */ 750 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 751 752 /** 753 * <p>This view shows vertical scrollbars.</p> 754 * {@hide} 755 */ 756 static final int SCROLLBARS_VERTICAL = 0x00000200; 757 758 /** 759 * <p>Mask for use with setFlags indicating bits used for indicating which 760 * scrollbars are enabled.</p> 761 * {@hide} 762 */ 763 static final int SCROLLBARS_MASK = 0x00000300; 764 765 /** 766 * Indicates that the view should filter touches when its window is obscured. 767 * Refer to the class comments for more information about this security feature. 768 * {@hide} 769 */ 770 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 771 772 // note flag value 0x00000800 is now available for next flags... 773 774 /** 775 * <p>This view doesn't show fading edges.</p> 776 * {@hide} 777 */ 778 static final int FADING_EDGE_NONE = 0x00000000; 779 780 /** 781 * <p>This view shows horizontal fading edges.</p> 782 * {@hide} 783 */ 784 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 785 786 /** 787 * <p>This view shows vertical fading edges.</p> 788 * {@hide} 789 */ 790 static final int FADING_EDGE_VERTICAL = 0x00002000; 791 792 /** 793 * <p>Mask for use with setFlags indicating bits used for indicating which 794 * fading edges are enabled.</p> 795 * {@hide} 796 */ 797 static final int FADING_EDGE_MASK = 0x00003000; 798 799 /** 800 * <p>Indicates this view can be clicked. When clickable, a View reacts 801 * to clicks by notifying the OnClickListener.<p> 802 * {@hide} 803 */ 804 static final int CLICKABLE = 0x00004000; 805 806 /** 807 * <p>Indicates this view is caching its drawing into a bitmap.</p> 808 * {@hide} 809 */ 810 static final int DRAWING_CACHE_ENABLED = 0x00008000; 811 812 /** 813 * <p>Indicates that no icicle should be saved for this view.<p> 814 * {@hide} 815 */ 816 static final int SAVE_DISABLED = 0x000010000; 817 818 /** 819 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 820 * property.</p> 821 * {@hide} 822 */ 823 static final int SAVE_DISABLED_MASK = 0x000010000; 824 825 /** 826 * <p>Indicates that no drawing cache should ever be created for this view.<p> 827 * {@hide} 828 */ 829 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 830 831 /** 832 * <p>Indicates this view can take / keep focus when int touch mode.</p> 833 * {@hide} 834 */ 835 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 836 837 /** 838 * <p>Enables low quality mode for the drawing cache.</p> 839 */ 840 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 841 842 /** 843 * <p>Enables high quality mode for the drawing cache.</p> 844 */ 845 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 846 847 /** 848 * <p>Enables automatic quality mode for the drawing cache.</p> 849 */ 850 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 851 852 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 853 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 854 }; 855 856 /** 857 * <p>Mask for use with setFlags indicating bits used for the cache 858 * quality property.</p> 859 * {@hide} 860 */ 861 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 862 863 /** 864 * <p> 865 * Indicates this view can be long clicked. When long clickable, a View 866 * reacts to long clicks by notifying the OnLongClickListener or showing a 867 * context menu. 868 * </p> 869 * {@hide} 870 */ 871 static final int LONG_CLICKABLE = 0x00200000; 872 873 /** 874 * <p>Indicates that this view gets its drawable states from its direct parent 875 * and ignores its original internal states.</p> 876 * 877 * @hide 878 */ 879 static final int DUPLICATE_PARENT_STATE = 0x00400000; 880 881 /** 882 * The scrollbar style to display the scrollbars inside the content area, 883 * without increasing the padding. The scrollbars will be overlaid with 884 * translucency on the view's content. 885 */ 886 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 887 888 /** 889 * The scrollbar style to display the scrollbars inside the padded area, 890 * increasing the padding of the view. The scrollbars will not overlap the 891 * content area of the view. 892 */ 893 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 894 895 /** 896 * The scrollbar style to display the scrollbars at the edge of the view, 897 * without increasing the padding. The scrollbars will be overlaid with 898 * translucency. 899 */ 900 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 901 902 /** 903 * The scrollbar style to display the scrollbars at the edge of the view, 904 * increasing the padding of the view. The scrollbars will only overlap the 905 * background, if any. 906 */ 907 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 908 909 /** 910 * Mask to check if the scrollbar style is overlay or inset. 911 * {@hide} 912 */ 913 static final int SCROLLBARS_INSET_MASK = 0x01000000; 914 915 /** 916 * Mask to check if the scrollbar style is inside or outside. 917 * {@hide} 918 */ 919 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 920 921 /** 922 * Mask for scrollbar style. 923 * {@hide} 924 */ 925 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 926 927 /** 928 * View flag indicating that the screen should remain on while the 929 * window containing this view is visible to the user. This effectively 930 * takes care of automatically setting the WindowManager's 931 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 932 */ 933 public static final int KEEP_SCREEN_ON = 0x04000000; 934 935 /** 936 * View flag indicating whether this view should have sound effects enabled 937 * for events such as clicking and touching. 938 */ 939 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 940 941 /** 942 * View flag indicating whether this view should have haptic feedback 943 * enabled for events such as long presses. 944 */ 945 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 946 947 /** 948 * <p>Indicates that the view hierarchy should stop saving state when 949 * it reaches this view. If state saving is initiated immediately at 950 * the view, it will be allowed. 951 * {@hide} 952 */ 953 static final int PARENT_SAVE_DISABLED = 0x20000000; 954 955 /** 956 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 957 * {@hide} 958 */ 959 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 960 961 /** 962 * Horizontal direction of this view is from Left to Right. 963 * Use with {@link #setLayoutDirection}. 964 * {@hide} 965 */ 966 public static final int LAYOUT_DIRECTION_LTR = 0x00000000; 967 968 /** 969 * Horizontal direction of this view is from Right to Left. 970 * Use with {@link #setLayoutDirection}. 971 * {@hide} 972 */ 973 public static final int LAYOUT_DIRECTION_RTL = 0x40000000; 974 975 /** 976 * Horizontal direction of this view is inherited from its parent. 977 * Use with {@link #setLayoutDirection}. 978 * {@hide} 979 */ 980 public static final int LAYOUT_DIRECTION_INHERIT = 0x80000000; 981 982 /** 983 * Horizontal direction of this view is from deduced from the default language 984 * script for the locale. Use with {@link #setLayoutDirection}. 985 * {@hide} 986 */ 987 public static final int LAYOUT_DIRECTION_LOCALE = 0xC0000000; 988 989 /** 990 * Mask for use with setFlags indicating bits used for horizontalDirection. 991 * {@hide} 992 */ 993 static final int LAYOUT_DIRECTION_MASK = 0xC0000000; 994 995 /* 996 * Array of horizontal direction flags for mapping attribute "horizontalDirection" to correct 997 * flag value. 998 * {@hide} 999 */ 1000 private static final int[] LAYOUT_DIRECTION_FLAGS = {LAYOUT_DIRECTION_LTR, 1001 LAYOUT_DIRECTION_RTL, LAYOUT_DIRECTION_INHERIT, LAYOUT_DIRECTION_LOCALE}; 1002 1003 /** 1004 * Default horizontalDirection. 1005 * {@hide} 1006 */ 1007 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 1008 1009 /** 1010 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1011 * should add all focusable Views regardless if they are focusable in touch mode. 1012 */ 1013 public static final int FOCUSABLES_ALL = 0x00000000; 1014 1015 /** 1016 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1017 * should add only Views focusable in touch mode. 1018 */ 1019 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1020 1021 /** 1022 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1023 * item. 1024 */ 1025 public static final int FOCUS_BACKWARD = 0x00000001; 1026 1027 /** 1028 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1029 * item. 1030 */ 1031 public static final int FOCUS_FORWARD = 0x00000002; 1032 1033 /** 1034 * Use with {@link #focusSearch(int)}. Move focus to the left. 1035 */ 1036 public static final int FOCUS_LEFT = 0x00000011; 1037 1038 /** 1039 * Use with {@link #focusSearch(int)}. Move focus up. 1040 */ 1041 public static final int FOCUS_UP = 0x00000021; 1042 1043 /** 1044 * Use with {@link #focusSearch(int)}. Move focus to the right. 1045 */ 1046 public static final int FOCUS_RIGHT = 0x00000042; 1047 1048 /** 1049 * Use with {@link #focusSearch(int)}. Move focus down. 1050 */ 1051 public static final int FOCUS_DOWN = 0x00000082; 1052 1053 /** 1054 * Bits of {@link #getMeasuredWidthAndState()} and 1055 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1056 */ 1057 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1058 1059 /** 1060 * Bits of {@link #getMeasuredWidthAndState()} and 1061 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1062 */ 1063 public static final int MEASURED_STATE_MASK = 0xff000000; 1064 1065 /** 1066 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1067 * for functions that combine both width and height into a single int, 1068 * such as {@link #getMeasuredState()} and the childState argument of 1069 * {@link #resolveSizeAndState(int, int, int)}. 1070 */ 1071 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1072 1073 /** 1074 * Bit of {@link #getMeasuredWidthAndState()} and 1075 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1076 * is smaller that the space the view would like to have. 1077 */ 1078 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1079 1080 /** 1081 * Base View state sets 1082 */ 1083 // Singles 1084 /** 1085 * Indicates the view has no states set. States are used with 1086 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1087 * view depending on its state. 1088 * 1089 * @see android.graphics.drawable.Drawable 1090 * @see #getDrawableState() 1091 */ 1092 protected static final int[] EMPTY_STATE_SET; 1093 /** 1094 * Indicates the view is enabled. States are used with 1095 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1096 * view depending on its state. 1097 * 1098 * @see android.graphics.drawable.Drawable 1099 * @see #getDrawableState() 1100 */ 1101 protected static final int[] ENABLED_STATE_SET; 1102 /** 1103 * Indicates the view is focused. States are used with 1104 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1105 * view depending on its state. 1106 * 1107 * @see android.graphics.drawable.Drawable 1108 * @see #getDrawableState() 1109 */ 1110 protected static final int[] FOCUSED_STATE_SET; 1111 /** 1112 * Indicates the view is selected. States are used with 1113 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1114 * view depending on its state. 1115 * 1116 * @see android.graphics.drawable.Drawable 1117 * @see #getDrawableState() 1118 */ 1119 protected static final int[] SELECTED_STATE_SET; 1120 /** 1121 * Indicates the view is pressed. States are used with 1122 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1123 * view depending on its state. 1124 * 1125 * @see android.graphics.drawable.Drawable 1126 * @see #getDrawableState() 1127 * @hide 1128 */ 1129 protected static final int[] PRESSED_STATE_SET; 1130 /** 1131 * Indicates the view's window has focus. States are used with 1132 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1133 * view depending on its state. 1134 * 1135 * @see android.graphics.drawable.Drawable 1136 * @see #getDrawableState() 1137 */ 1138 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1139 // Doubles 1140 /** 1141 * Indicates the view is enabled and has the focus. 1142 * 1143 * @see #ENABLED_STATE_SET 1144 * @see #FOCUSED_STATE_SET 1145 */ 1146 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1147 /** 1148 * Indicates the view is enabled and selected. 1149 * 1150 * @see #ENABLED_STATE_SET 1151 * @see #SELECTED_STATE_SET 1152 */ 1153 protected static final int[] ENABLED_SELECTED_STATE_SET; 1154 /** 1155 * Indicates the view is enabled and that its window has focus. 1156 * 1157 * @see #ENABLED_STATE_SET 1158 * @see #WINDOW_FOCUSED_STATE_SET 1159 */ 1160 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1161 /** 1162 * Indicates the view is focused and selected. 1163 * 1164 * @see #FOCUSED_STATE_SET 1165 * @see #SELECTED_STATE_SET 1166 */ 1167 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1168 /** 1169 * Indicates the view has the focus and that its window has the focus. 1170 * 1171 * @see #FOCUSED_STATE_SET 1172 * @see #WINDOW_FOCUSED_STATE_SET 1173 */ 1174 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1175 /** 1176 * Indicates the view is selected and that its window has the focus. 1177 * 1178 * @see #SELECTED_STATE_SET 1179 * @see #WINDOW_FOCUSED_STATE_SET 1180 */ 1181 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1182 // Triples 1183 /** 1184 * Indicates the view is enabled, focused and selected. 1185 * 1186 * @see #ENABLED_STATE_SET 1187 * @see #FOCUSED_STATE_SET 1188 * @see #SELECTED_STATE_SET 1189 */ 1190 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1191 /** 1192 * Indicates the view is enabled, focused and its window has the focus. 1193 * 1194 * @see #ENABLED_STATE_SET 1195 * @see #FOCUSED_STATE_SET 1196 * @see #WINDOW_FOCUSED_STATE_SET 1197 */ 1198 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1199 /** 1200 * Indicates the view is enabled, selected and its window has the focus. 1201 * 1202 * @see #ENABLED_STATE_SET 1203 * @see #SELECTED_STATE_SET 1204 * @see #WINDOW_FOCUSED_STATE_SET 1205 */ 1206 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1207 /** 1208 * Indicates the view is focused, selected and its window has the focus. 1209 * 1210 * @see #FOCUSED_STATE_SET 1211 * @see #SELECTED_STATE_SET 1212 * @see #WINDOW_FOCUSED_STATE_SET 1213 */ 1214 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1215 /** 1216 * Indicates the view is enabled, focused, selected and its window 1217 * has the focus. 1218 * 1219 * @see #ENABLED_STATE_SET 1220 * @see #FOCUSED_STATE_SET 1221 * @see #SELECTED_STATE_SET 1222 * @see #WINDOW_FOCUSED_STATE_SET 1223 */ 1224 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1225 /** 1226 * Indicates the view is pressed and its window has the focus. 1227 * 1228 * @see #PRESSED_STATE_SET 1229 * @see #WINDOW_FOCUSED_STATE_SET 1230 */ 1231 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1232 /** 1233 * Indicates the view is pressed and selected. 1234 * 1235 * @see #PRESSED_STATE_SET 1236 * @see #SELECTED_STATE_SET 1237 */ 1238 protected static final int[] PRESSED_SELECTED_STATE_SET; 1239 /** 1240 * Indicates the view is pressed, selected and its window has the focus. 1241 * 1242 * @see #PRESSED_STATE_SET 1243 * @see #SELECTED_STATE_SET 1244 * @see #WINDOW_FOCUSED_STATE_SET 1245 */ 1246 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1247 /** 1248 * Indicates the view is pressed and focused. 1249 * 1250 * @see #PRESSED_STATE_SET 1251 * @see #FOCUSED_STATE_SET 1252 */ 1253 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1254 /** 1255 * Indicates the view is pressed, focused and its window has the focus. 1256 * 1257 * @see #PRESSED_STATE_SET 1258 * @see #FOCUSED_STATE_SET 1259 * @see #WINDOW_FOCUSED_STATE_SET 1260 */ 1261 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1262 /** 1263 * Indicates the view is pressed, focused and selected. 1264 * 1265 * @see #PRESSED_STATE_SET 1266 * @see #SELECTED_STATE_SET 1267 * @see #FOCUSED_STATE_SET 1268 */ 1269 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1270 /** 1271 * Indicates the view is pressed, focused, selected and its window has the focus. 1272 * 1273 * @see #PRESSED_STATE_SET 1274 * @see #FOCUSED_STATE_SET 1275 * @see #SELECTED_STATE_SET 1276 * @see #WINDOW_FOCUSED_STATE_SET 1277 */ 1278 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1279 /** 1280 * Indicates the view is pressed and enabled. 1281 * 1282 * @see #PRESSED_STATE_SET 1283 * @see #ENABLED_STATE_SET 1284 */ 1285 protected static final int[] PRESSED_ENABLED_STATE_SET; 1286 /** 1287 * Indicates the view is pressed, enabled and its window has the focus. 1288 * 1289 * @see #PRESSED_STATE_SET 1290 * @see #ENABLED_STATE_SET 1291 * @see #WINDOW_FOCUSED_STATE_SET 1292 */ 1293 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1294 /** 1295 * Indicates the view is pressed, enabled and selected. 1296 * 1297 * @see #PRESSED_STATE_SET 1298 * @see #ENABLED_STATE_SET 1299 * @see #SELECTED_STATE_SET 1300 */ 1301 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1302 /** 1303 * Indicates the view is pressed, enabled, selected and its window has the 1304 * focus. 1305 * 1306 * @see #PRESSED_STATE_SET 1307 * @see #ENABLED_STATE_SET 1308 * @see #SELECTED_STATE_SET 1309 * @see #WINDOW_FOCUSED_STATE_SET 1310 */ 1311 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1312 /** 1313 * Indicates the view is pressed, enabled and focused. 1314 * 1315 * @see #PRESSED_STATE_SET 1316 * @see #ENABLED_STATE_SET 1317 * @see #FOCUSED_STATE_SET 1318 */ 1319 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1320 /** 1321 * Indicates the view is pressed, enabled, focused and its window has the 1322 * focus. 1323 * 1324 * @see #PRESSED_STATE_SET 1325 * @see #ENABLED_STATE_SET 1326 * @see #FOCUSED_STATE_SET 1327 * @see #WINDOW_FOCUSED_STATE_SET 1328 */ 1329 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1330 /** 1331 * Indicates the view is pressed, enabled, focused and selected. 1332 * 1333 * @see #PRESSED_STATE_SET 1334 * @see #ENABLED_STATE_SET 1335 * @see #SELECTED_STATE_SET 1336 * @see #FOCUSED_STATE_SET 1337 */ 1338 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1339 /** 1340 * Indicates the view is pressed, enabled, focused, selected and its window 1341 * has the focus. 1342 * 1343 * @see #PRESSED_STATE_SET 1344 * @see #ENABLED_STATE_SET 1345 * @see #SELECTED_STATE_SET 1346 * @see #FOCUSED_STATE_SET 1347 * @see #WINDOW_FOCUSED_STATE_SET 1348 */ 1349 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1350 1351 /** 1352 * The order here is very important to {@link #getDrawableState()} 1353 */ 1354 private static final int[][] VIEW_STATE_SETS; 1355 1356 static final int VIEW_STATE_WINDOW_FOCUSED = 1; 1357 static final int VIEW_STATE_SELECTED = 1 << 1; 1358 static final int VIEW_STATE_FOCUSED = 1 << 2; 1359 static final int VIEW_STATE_ENABLED = 1 << 3; 1360 static final int VIEW_STATE_PRESSED = 1 << 4; 1361 static final int VIEW_STATE_ACTIVATED = 1 << 5; 1362 static final int VIEW_STATE_ACCELERATED = 1 << 6; 1363 static final int VIEW_STATE_HOVERED = 1 << 7; 1364 static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8; 1365 static final int VIEW_STATE_DRAG_HOVERED = 1 << 9; 1366 1367 static final int[] VIEW_STATE_IDS = new int[] { 1368 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED, 1369 R.attr.state_selected, VIEW_STATE_SELECTED, 1370 R.attr.state_focused, VIEW_STATE_FOCUSED, 1371 R.attr.state_enabled, VIEW_STATE_ENABLED, 1372 R.attr.state_pressed, VIEW_STATE_PRESSED, 1373 R.attr.state_activated, VIEW_STATE_ACTIVATED, 1374 R.attr.state_accelerated, VIEW_STATE_ACCELERATED, 1375 R.attr.state_hovered, VIEW_STATE_HOVERED, 1376 R.attr.state_drag_can_accept, VIEW_STATE_DRAG_CAN_ACCEPT, 1377 R.attr.state_drag_hovered, VIEW_STATE_DRAG_HOVERED, 1378 }; 1379 1380 static { 1381 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) { 1382 throw new IllegalStateException( 1383 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array"); 1384 } 1385 int[] orderedIds = new int[VIEW_STATE_IDS.length]; 1386 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) { 1387 int viewState = R.styleable.ViewDrawableStates[i]; 1388 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) { 1389 if (VIEW_STATE_IDS[j] == viewState) { 1390 orderedIds[i * 2] = viewState; 1391 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1]; 1392 } 1393 } 1394 } 1395 final int NUM_BITS = VIEW_STATE_IDS.length / 2; 1396 VIEW_STATE_SETS = new int[1 << NUM_BITS][]; 1397 for (int i = 0; i < VIEW_STATE_SETS.length; i++) { 1398 int numBits = Integer.bitCount(i); 1399 int[] set = new int[numBits]; 1400 int pos = 0; 1401 for (int j = 0; j < orderedIds.length; j += 2) { 1402 if ((i & orderedIds[j+1]) != 0) { 1403 set[pos++] = orderedIds[j]; 1404 } 1405 } 1406 VIEW_STATE_SETS[i] = set; 1407 } 1408 1409 EMPTY_STATE_SET = VIEW_STATE_SETS[0]; 1410 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED]; 1411 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED]; 1412 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1413 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED]; 1414 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED]; 1415 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1416 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED]; 1417 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1418 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED]; 1419 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1420 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1421 | VIEW_STATE_FOCUSED]; 1422 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED]; 1423 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1424 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED]; 1425 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1426 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED]; 1427 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1428 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1429 | VIEW_STATE_ENABLED]; 1430 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1431 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED]; 1432 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1433 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1434 | VIEW_STATE_ENABLED]; 1435 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1436 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1437 | VIEW_STATE_ENABLED]; 1438 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1439 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1440 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED]; 1441 1442 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED]; 1443 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1444 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED]; 1445 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1446 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED]; 1447 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1448 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1449 | VIEW_STATE_PRESSED]; 1450 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1451 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1452 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1453 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1454 | VIEW_STATE_PRESSED]; 1455 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1456 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1457 | VIEW_STATE_PRESSED]; 1458 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1459 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1460 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1461 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[ 1462 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1463 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1464 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED 1465 | VIEW_STATE_PRESSED]; 1466 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1467 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED 1468 | VIEW_STATE_PRESSED]; 1469 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1470 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1471 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1472 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1473 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED 1474 | VIEW_STATE_PRESSED]; 1475 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1476 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1477 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1478 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1479 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1480 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1481 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1482 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1483 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED 1484 | VIEW_STATE_PRESSED]; 1485 } 1486 1487 /** 1488 * Temporary Rect currently for use in setBackground(). This will probably 1489 * be extended in the future to hold our own class with more than just 1490 * a Rect. :) 1491 */ 1492 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1493 1494 /** 1495 * Map used to store views' tags. 1496 */ 1497 private static WeakHashMap<View, SparseArray<Object>> sTags; 1498 1499 /** 1500 * Lock used to access sTags. 1501 */ 1502 private static final Object sTagsLock = new Object(); 1503 1504 /** 1505 * The next available accessiiblity id. 1506 */ 1507 private static int sNextAccessibilityViewId; 1508 1509 /** 1510 * The animation currently associated with this view. 1511 * @hide 1512 */ 1513 protected Animation mCurrentAnimation = null; 1514 1515 /** 1516 * Width as measured during measure pass. 1517 * {@hide} 1518 */ 1519 @ViewDebug.ExportedProperty(category = "measurement") 1520 int mMeasuredWidth; 1521 1522 /** 1523 * Height as measured during measure pass. 1524 * {@hide} 1525 */ 1526 @ViewDebug.ExportedProperty(category = "measurement") 1527 int mMeasuredHeight; 1528 1529 /** 1530 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1531 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1532 * its display list. This flag, used only when hw accelerated, allows us to clear the 1533 * flag while retaining this information until it's needed (at getDisplayList() time and 1534 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1535 * 1536 * {@hide} 1537 */ 1538 boolean mRecreateDisplayList = false; 1539 1540 /** 1541 * The view's identifier. 1542 * {@hide} 1543 * 1544 * @see #setId(int) 1545 * @see #getId() 1546 */ 1547 @ViewDebug.ExportedProperty(resolveId = true) 1548 int mID = NO_ID; 1549 1550 /** 1551 * The stable ID of this view for accessibility porposes. 1552 */ 1553 int mAccessibilityViewId = NO_ID; 1554 1555 /** 1556 * The view's tag. 1557 * {@hide} 1558 * 1559 * @see #setTag(Object) 1560 * @see #getTag() 1561 */ 1562 protected Object mTag; 1563 1564 // for mPrivateFlags: 1565 /** {@hide} */ 1566 static final int WANTS_FOCUS = 0x00000001; 1567 /** {@hide} */ 1568 static final int FOCUSED = 0x00000002; 1569 /** {@hide} */ 1570 static final int SELECTED = 0x00000004; 1571 /** {@hide} */ 1572 static final int IS_ROOT_NAMESPACE = 0x00000008; 1573 /** {@hide} */ 1574 static final int HAS_BOUNDS = 0x00000010; 1575 /** {@hide} */ 1576 static final int DRAWN = 0x00000020; 1577 /** 1578 * When this flag is set, this view is running an animation on behalf of its 1579 * children and should therefore not cancel invalidate requests, even if they 1580 * lie outside of this view's bounds. 1581 * 1582 * {@hide} 1583 */ 1584 static final int DRAW_ANIMATION = 0x00000040; 1585 /** {@hide} */ 1586 static final int SKIP_DRAW = 0x00000080; 1587 /** {@hide} */ 1588 static final int ONLY_DRAWS_BACKGROUND = 0x00000100; 1589 /** {@hide} */ 1590 static final int REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1591 /** {@hide} */ 1592 static final int DRAWABLE_STATE_DIRTY = 0x00000400; 1593 /** {@hide} */ 1594 static final int MEASURED_DIMENSION_SET = 0x00000800; 1595 /** {@hide} */ 1596 static final int FORCE_LAYOUT = 0x00001000; 1597 /** {@hide} */ 1598 static final int LAYOUT_REQUIRED = 0x00002000; 1599 1600 private static final int PRESSED = 0x00004000; 1601 1602 /** {@hide} */ 1603 static final int DRAWING_CACHE_VALID = 0x00008000; 1604 /** 1605 * Flag used to indicate that this view should be drawn once more (and only once 1606 * more) after its animation has completed. 1607 * {@hide} 1608 */ 1609 static final int ANIMATION_STARTED = 0x00010000; 1610 1611 private static final int SAVE_STATE_CALLED = 0x00020000; 1612 1613 /** 1614 * Indicates that the View returned true when onSetAlpha() was called and that 1615 * the alpha must be restored. 1616 * {@hide} 1617 */ 1618 static final int ALPHA_SET = 0x00040000; 1619 1620 /** 1621 * Set by {@link #setScrollContainer(boolean)}. 1622 */ 1623 static final int SCROLL_CONTAINER = 0x00080000; 1624 1625 /** 1626 * Set by {@link #setScrollContainer(boolean)}. 1627 */ 1628 static final int SCROLL_CONTAINER_ADDED = 0x00100000; 1629 1630 /** 1631 * View flag indicating whether this view was invalidated (fully or partially.) 1632 * 1633 * @hide 1634 */ 1635 static final int DIRTY = 0x00200000; 1636 1637 /** 1638 * View flag indicating whether this view was invalidated by an opaque 1639 * invalidate request. 1640 * 1641 * @hide 1642 */ 1643 static final int DIRTY_OPAQUE = 0x00400000; 1644 1645 /** 1646 * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}. 1647 * 1648 * @hide 1649 */ 1650 static final int DIRTY_MASK = 0x00600000; 1651 1652 /** 1653 * Indicates whether the background is opaque. 1654 * 1655 * @hide 1656 */ 1657 static final int OPAQUE_BACKGROUND = 0x00800000; 1658 1659 /** 1660 * Indicates whether the scrollbars are opaque. 1661 * 1662 * @hide 1663 */ 1664 static final int OPAQUE_SCROLLBARS = 0x01000000; 1665 1666 /** 1667 * Indicates whether the view is opaque. 1668 * 1669 * @hide 1670 */ 1671 static final int OPAQUE_MASK = 0x01800000; 1672 1673 /** 1674 * Indicates a prepressed state; 1675 * the short time between ACTION_DOWN and recognizing 1676 * a 'real' press. Prepressed is used to recognize quick taps 1677 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1678 * 1679 * @hide 1680 */ 1681 private static final int PREPRESSED = 0x02000000; 1682 1683 /** 1684 * Indicates whether the view is temporarily detached. 1685 * 1686 * @hide 1687 */ 1688 static final int CANCEL_NEXT_UP_EVENT = 0x04000000; 1689 1690 /** 1691 * Indicates that we should awaken scroll bars once attached 1692 * 1693 * @hide 1694 */ 1695 private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1696 1697 /** 1698 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1699 * @hide 1700 */ 1701 private static final int HOVERED = 0x10000000; 1702 1703 /** 1704 * Indicates that pivotX or pivotY were explicitly set and we should not assume the center 1705 * for transform operations 1706 * 1707 * @hide 1708 */ 1709 private static final int PIVOT_EXPLICITLY_SET = 0x20000000; 1710 1711 /** {@hide} */ 1712 static final int ACTIVATED = 0x40000000; 1713 1714 /** 1715 * Indicates that this view was specifically invalidated, not just dirtied because some 1716 * child view was invalidated. The flag is used to determine when we need to recreate 1717 * a view's display list (as opposed to just returning a reference to its existing 1718 * display list). 1719 * 1720 * @hide 1721 */ 1722 static final int INVALIDATED = 0x80000000; 1723 1724 /* Masks for mPrivateFlags2 */ 1725 1726 /** 1727 * Indicates that this view has reported that it can accept the current drag's content. 1728 * Cleared when the drag operation concludes. 1729 * @hide 1730 */ 1731 static final int DRAG_CAN_ACCEPT = 0x00000001; 1732 1733 /** 1734 * Indicates that this view is currently directly under the drag location in a 1735 * drag-and-drop operation involving content that it can accept. Cleared when 1736 * the drag exits the view, or when the drag operation concludes. 1737 * @hide 1738 */ 1739 static final int DRAG_HOVERED = 0x00000002; 1740 1741 /** 1742 * Indicates whether the view layout direction has been resolved and drawn to the 1743 * right-to-left direction. 1744 * 1745 * @hide 1746 */ 1747 static final int LAYOUT_DIRECTION_RESOLVED_RTL = 0x00000004; 1748 1749 /** 1750 * Indicates whether the view layout direction has been resolved. 1751 * 1752 * @hide 1753 */ 1754 static final int LAYOUT_DIRECTION_RESOLVED = 0x00000008; 1755 1756 1757 /* End of masks for mPrivateFlags2 */ 1758 1759 static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED; 1760 1761 /** 1762 * Always allow a user to over-scroll this view, provided it is a 1763 * view that can scroll. 1764 * 1765 * @see #getOverScrollMode() 1766 * @see #setOverScrollMode(int) 1767 */ 1768 public static final int OVER_SCROLL_ALWAYS = 0; 1769 1770 /** 1771 * Allow a user to over-scroll this view only if the content is large 1772 * enough to meaningfully scroll, provided it is a view that can scroll. 1773 * 1774 * @see #getOverScrollMode() 1775 * @see #setOverScrollMode(int) 1776 */ 1777 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 1778 1779 /** 1780 * Never allow a user to over-scroll this view. 1781 * 1782 * @see #getOverScrollMode() 1783 * @see #setOverScrollMode(int) 1784 */ 1785 public static final int OVER_SCROLL_NEVER = 2; 1786 1787 /** 1788 * View has requested the system UI (status bar) to be visible (the default). 1789 * 1790 * @see #setSystemUiVisibility(int) 1791 */ 1792 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 1793 1794 /** 1795 * View has requested the system UI to enter an unobtrusive "low profile" mode. 1796 * 1797 * This is for use in games, book readers, video players, or any other "immersive" application 1798 * where the usual system chrome is deemed too distracting. 1799 * 1800 * In low profile mode, the status bar and/or navigation icons may dim. 1801 * 1802 * @see #setSystemUiVisibility(int) 1803 */ 1804 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 1805 1806 /** 1807 * View has requested that the system navigation be temporarily hidden. 1808 * 1809 * This is an even less obtrusive state than that called for by 1810 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 1811 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 1812 * those to disappear. This is useful (in conjunction with the 1813 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 1814 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 1815 * window flags) for displaying content using every last pixel on the display. 1816 * 1817 * There is a limitation: because navigation controls are so important, the least user 1818 * interaction will cause them to reappear immediately. 1819 * 1820 * @see #setSystemUiVisibility(int) 1821 */ 1822 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 1823 1824 /** 1825 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 1826 */ 1827 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 1828 1829 /** 1830 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 1831 */ 1832 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 1833 1834 /** 1835 * @hide 1836 * 1837 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1838 * out of the public fields to keep the undefined bits out of the developer's way. 1839 * 1840 * Flag to make the status bar not expandable. Unless you also 1841 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 1842 */ 1843 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 1844 1845 /** 1846 * @hide 1847 * 1848 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1849 * out of the public fields to keep the undefined bits out of the developer's way. 1850 * 1851 * Flag to hide notification icons and scrolling ticker text. 1852 */ 1853 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 1854 1855 /** 1856 * @hide 1857 * 1858 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1859 * out of the public fields to keep the undefined bits out of the developer's way. 1860 * 1861 * Flag to disable incoming notification alerts. This will not block 1862 * icons, but it will block sound, vibrating and other visual or aural notifications. 1863 */ 1864 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 1865 1866 /** 1867 * @hide 1868 * 1869 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1870 * out of the public fields to keep the undefined bits out of the developer's way. 1871 * 1872 * Flag to hide only the scrolling ticker. Note that 1873 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 1874 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 1875 */ 1876 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 1877 1878 /** 1879 * @hide 1880 * 1881 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1882 * out of the public fields to keep the undefined bits out of the developer's way. 1883 * 1884 * Flag to hide the center system info area. 1885 */ 1886 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 1887 1888 /** 1889 * @hide 1890 * 1891 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1892 * out of the public fields to keep the undefined bits out of the developer's way. 1893 * 1894 * Flag to hide only the navigation buttons. Don't use this 1895 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 1896 * 1897 * THIS DOES NOT DISABLE THE BACK BUTTON 1898 */ 1899 public static final int STATUS_BAR_DISABLE_NAVIGATION = 0x00200000; 1900 1901 /** 1902 * @hide 1903 * 1904 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1905 * out of the public fields to keep the undefined bits out of the developer's way. 1906 * 1907 * Flag to hide only the back button. Don't use this 1908 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 1909 */ 1910 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 1911 1912 /** 1913 * @hide 1914 * 1915 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1916 * out of the public fields to keep the undefined bits out of the developer's way. 1917 * 1918 * Flag to hide only the clock. You might use this if your activity has 1919 * its own clock making the status bar's clock redundant. 1920 */ 1921 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 1922 1923 /** 1924 * @hide 1925 */ 1926 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF; 1927 1928 /** 1929 * Controls the over-scroll mode for this view. 1930 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 1931 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 1932 * and {@link #OVER_SCROLL_NEVER}. 1933 */ 1934 private int mOverScrollMode; 1935 1936 /** 1937 * The parent this view is attached to. 1938 * {@hide} 1939 * 1940 * @see #getParent() 1941 */ 1942 protected ViewParent mParent; 1943 1944 /** 1945 * {@hide} 1946 */ 1947 AttachInfo mAttachInfo; 1948 1949 /** 1950 * {@hide} 1951 */ 1952 @ViewDebug.ExportedProperty(flagMapping = { 1953 @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT, 1954 name = "FORCE_LAYOUT"), 1955 @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED, 1956 name = "LAYOUT_REQUIRED"), 1957 @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID, 1958 name = "DRAWING_CACHE_INVALID", outputIf = false), 1959 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true), 1960 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false), 1961 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 1962 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY") 1963 }) 1964 int mPrivateFlags; 1965 int mPrivateFlags2; 1966 1967 /** 1968 * This view's request for the visibility of the status bar. 1969 * @hide 1970 */ 1971 @ViewDebug.ExportedProperty(flagMapping = { 1972 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 1973 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 1974 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 1975 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 1976 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 1977 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 1978 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 1979 equals = SYSTEM_UI_FLAG_VISIBLE, 1980 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 1981 }) 1982 int mSystemUiVisibility; 1983 1984 /** 1985 * Count of how many windows this view has been attached to. 1986 */ 1987 int mWindowAttachCount; 1988 1989 /** 1990 * The layout parameters associated with this view and used by the parent 1991 * {@link android.view.ViewGroup} to determine how this view should be 1992 * laid out. 1993 * {@hide} 1994 */ 1995 protected ViewGroup.LayoutParams mLayoutParams; 1996 1997 /** 1998 * The view flags hold various views states. 1999 * {@hide} 2000 */ 2001 @ViewDebug.ExportedProperty 2002 int mViewFlags; 2003 2004 /** 2005 * The transform matrix for the View. This transform is calculated internally 2006 * based on the rotation, scaleX, and scaleY properties. The identity matrix 2007 * is used by default. Do *not* use this variable directly; instead call 2008 * getMatrix(), which will automatically recalculate the matrix if necessary 2009 * to get the correct matrix based on the latest rotation and scale properties. 2010 */ 2011 private final Matrix mMatrix = new Matrix(); 2012 2013 /** 2014 * The transform matrix for the View. This transform is calculated internally 2015 * based on the rotation, scaleX, and scaleY properties. The identity matrix 2016 * is used by default. Do *not* use this variable directly; instead call 2017 * getInverseMatrix(), which will automatically recalculate the matrix if necessary 2018 * to get the correct matrix based on the latest rotation and scale properties. 2019 */ 2020 private Matrix mInverseMatrix; 2021 2022 /** 2023 * An internal variable that tracks whether we need to recalculate the 2024 * transform matrix, based on whether the rotation or scaleX/Y properties 2025 * have changed since the matrix was last calculated. 2026 */ 2027 boolean mMatrixDirty = false; 2028 2029 /** 2030 * An internal variable that tracks whether we need to recalculate the 2031 * transform matrix, based on whether the rotation or scaleX/Y properties 2032 * have changed since the matrix was last calculated. 2033 */ 2034 private boolean mInverseMatrixDirty = true; 2035 2036 /** 2037 * A variable that tracks whether we need to recalculate the 2038 * transform matrix, based on whether the rotation or scaleX/Y properties 2039 * have changed since the matrix was last calculated. This variable 2040 * is only valid after a call to updateMatrix() or to a function that 2041 * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix(). 2042 */ 2043 private boolean mMatrixIsIdentity = true; 2044 2045 /** 2046 * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set. 2047 */ 2048 private Camera mCamera = null; 2049 2050 /** 2051 * This matrix is used when computing the matrix for 3D rotations. 2052 */ 2053 private Matrix matrix3D = null; 2054 2055 /** 2056 * These prev values are used to recalculate a centered pivot point when necessary. The 2057 * pivot point is only used in matrix operations (when rotation, scale, or translation are 2058 * set), so thes values are only used then as well. 2059 */ 2060 private int mPrevWidth = -1; 2061 private int mPrevHeight = -1; 2062 2063 private boolean mLastIsOpaque; 2064 2065 /** 2066 * Convenience value to check for float values that are close enough to zero to be considered 2067 * zero. 2068 */ 2069 private static final float NONZERO_EPSILON = .001f; 2070 2071 /** 2072 * The degrees rotation around the vertical axis through the pivot point. 2073 */ 2074 @ViewDebug.ExportedProperty 2075 float mRotationY = 0f; 2076 2077 /** 2078 * The degrees rotation around the horizontal axis through the pivot point. 2079 */ 2080 @ViewDebug.ExportedProperty 2081 float mRotationX = 0f; 2082 2083 /** 2084 * The degrees rotation around the pivot point. 2085 */ 2086 @ViewDebug.ExportedProperty 2087 float mRotation = 0f; 2088 2089 /** 2090 * The amount of translation of the object away from its left property (post-layout). 2091 */ 2092 @ViewDebug.ExportedProperty 2093 float mTranslationX = 0f; 2094 2095 /** 2096 * The amount of translation of the object away from its top property (post-layout). 2097 */ 2098 @ViewDebug.ExportedProperty 2099 float mTranslationY = 0f; 2100 2101 /** 2102 * The amount of scale in the x direction around the pivot point. A 2103 * value of 1 means no scaling is applied. 2104 */ 2105 @ViewDebug.ExportedProperty 2106 float mScaleX = 1f; 2107 2108 /** 2109 * The amount of scale in the y direction around the pivot point. A 2110 * value of 1 means no scaling is applied. 2111 */ 2112 @ViewDebug.ExportedProperty 2113 float mScaleY = 1f; 2114 2115 /** 2116 * The amount of scale in the x direction around the pivot point. A 2117 * value of 1 means no scaling is applied. 2118 */ 2119 @ViewDebug.ExportedProperty 2120 float mPivotX = 0f; 2121 2122 /** 2123 * The amount of scale in the y direction around the pivot point. A 2124 * value of 1 means no scaling is applied. 2125 */ 2126 @ViewDebug.ExportedProperty 2127 float mPivotY = 0f; 2128 2129 /** 2130 * The opacity of the View. This is a value from 0 to 1, where 0 means 2131 * completely transparent and 1 means completely opaque. 2132 */ 2133 @ViewDebug.ExportedProperty 2134 float mAlpha = 1f; 2135 2136 /** 2137 * The distance in pixels from the left edge of this view's parent 2138 * to the left edge of this view. 2139 * {@hide} 2140 */ 2141 @ViewDebug.ExportedProperty(category = "layout") 2142 protected int mLeft; 2143 /** 2144 * The distance in pixels from the left edge of this view's parent 2145 * to the right edge of this view. 2146 * {@hide} 2147 */ 2148 @ViewDebug.ExportedProperty(category = "layout") 2149 protected int mRight; 2150 /** 2151 * The distance in pixels from the top edge of this view's parent 2152 * to the top edge of this view. 2153 * {@hide} 2154 */ 2155 @ViewDebug.ExportedProperty(category = "layout") 2156 protected int mTop; 2157 /** 2158 * The distance in pixels from the top edge of this view's parent 2159 * to the bottom edge of this view. 2160 * {@hide} 2161 */ 2162 @ViewDebug.ExportedProperty(category = "layout") 2163 protected int mBottom; 2164 2165 /** 2166 * The offset, in pixels, by which the content of this view is scrolled 2167 * horizontally. 2168 * {@hide} 2169 */ 2170 @ViewDebug.ExportedProperty(category = "scrolling") 2171 protected int mScrollX; 2172 /** 2173 * The offset, in pixels, by which the content of this view is scrolled 2174 * vertically. 2175 * {@hide} 2176 */ 2177 @ViewDebug.ExportedProperty(category = "scrolling") 2178 protected int mScrollY; 2179 2180 /** 2181 * The left padding in pixels, that is the distance in pixels between the 2182 * left edge of this view and the left edge of its content. 2183 * {@hide} 2184 */ 2185 @ViewDebug.ExportedProperty(category = "padding") 2186 protected int mPaddingLeft; 2187 /** 2188 * The right padding in pixels, that is the distance in pixels between the 2189 * right edge of this view and the right edge of its content. 2190 * {@hide} 2191 */ 2192 @ViewDebug.ExportedProperty(category = "padding") 2193 protected int mPaddingRight; 2194 /** 2195 * The top padding in pixels, that is the distance in pixels between the 2196 * top edge of this view and the top edge of its content. 2197 * {@hide} 2198 */ 2199 @ViewDebug.ExportedProperty(category = "padding") 2200 protected int mPaddingTop; 2201 /** 2202 * The bottom padding in pixels, that is the distance in pixels between the 2203 * bottom edge of this view and the bottom edge of its content. 2204 * {@hide} 2205 */ 2206 @ViewDebug.ExportedProperty(category = "padding") 2207 protected int mPaddingBottom; 2208 2209 /** 2210 * Briefly describes the view and is primarily used for accessibility support. 2211 */ 2212 private CharSequence mContentDescription; 2213 2214 /** 2215 * Cache the paddingRight set by the user to append to the scrollbar's size. 2216 * 2217 * @hide 2218 */ 2219 @ViewDebug.ExportedProperty(category = "padding") 2220 protected int mUserPaddingRight; 2221 2222 /** 2223 * Cache the paddingBottom set by the user to append to the scrollbar's size. 2224 * 2225 * @hide 2226 */ 2227 @ViewDebug.ExportedProperty(category = "padding") 2228 protected int mUserPaddingBottom; 2229 2230 /** 2231 * Cache the paddingLeft set by the user to append to the scrollbar's size. 2232 * 2233 * @hide 2234 */ 2235 @ViewDebug.ExportedProperty(category = "padding") 2236 protected int mUserPaddingLeft; 2237 2238 /** 2239 * Cache if the user padding is relative. 2240 * 2241 */ 2242 @ViewDebug.ExportedProperty(category = "padding") 2243 boolean mUserPaddingRelative; 2244 2245 /** 2246 * Cache the paddingStart set by the user to append to the scrollbar's size. 2247 * 2248 */ 2249 @ViewDebug.ExportedProperty(category = "padding") 2250 int mUserPaddingStart; 2251 2252 /** 2253 * Cache the paddingEnd set by the user to append to the scrollbar's size. 2254 * 2255 */ 2256 @ViewDebug.ExportedProperty(category = "padding") 2257 int mUserPaddingEnd; 2258 2259 /** 2260 * @hide 2261 */ 2262 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 2263 /** 2264 * @hide 2265 */ 2266 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 2267 2268 private Resources mResources = null; 2269 2270 private Drawable mBGDrawable; 2271 2272 private int mBackgroundResource; 2273 private boolean mBackgroundSizeChanged; 2274 2275 /** 2276 * Listener used to dispatch focus change events. 2277 * This field should be made private, so it is hidden from the SDK. 2278 * {@hide} 2279 */ 2280 protected OnFocusChangeListener mOnFocusChangeListener; 2281 2282 /** 2283 * Listeners for layout change events. 2284 */ 2285 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 2286 2287 /** 2288 * Listeners for attach events. 2289 */ 2290 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 2291 2292 /** 2293 * Listener used to dispatch click events. 2294 * This field should be made private, so it is hidden from the SDK. 2295 * {@hide} 2296 */ 2297 protected OnClickListener mOnClickListener; 2298 2299 /** 2300 * Listener used to dispatch long click events. 2301 * This field should be made private, so it is hidden from the SDK. 2302 * {@hide} 2303 */ 2304 protected OnLongClickListener mOnLongClickListener; 2305 2306 /** 2307 * Listener used to build the context menu. 2308 * This field should be made private, so it is hidden from the SDK. 2309 * {@hide} 2310 */ 2311 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 2312 2313 private OnKeyListener mOnKeyListener; 2314 2315 private OnTouchListener mOnTouchListener; 2316 2317 private OnHoverListener mOnHoverListener; 2318 2319 private OnGenericMotionListener mOnGenericMotionListener; 2320 2321 private OnDragListener mOnDragListener; 2322 2323 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 2324 2325 /** 2326 * The application environment this view lives in. 2327 * This field should be made private, so it is hidden from the SDK. 2328 * {@hide} 2329 */ 2330 protected Context mContext; 2331 2332 private ScrollabilityCache mScrollCache; 2333 2334 private int[] mDrawableState = null; 2335 2336 /** 2337 * Set to true when drawing cache is enabled and cannot be created. 2338 * 2339 * @hide 2340 */ 2341 public boolean mCachingFailed; 2342 2343 private Bitmap mDrawingCache; 2344 private Bitmap mUnscaledDrawingCache; 2345 private HardwareLayer mHardwareLayer; 2346 DisplayList mDisplayList; 2347 2348 /** 2349 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 2350 * the user may specify which view to go to next. 2351 */ 2352 private int mNextFocusLeftId = View.NO_ID; 2353 2354 /** 2355 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 2356 * the user may specify which view to go to next. 2357 */ 2358 private int mNextFocusRightId = View.NO_ID; 2359 2360 /** 2361 * When this view has focus and the next focus is {@link #FOCUS_UP}, 2362 * the user may specify which view to go to next. 2363 */ 2364 private int mNextFocusUpId = View.NO_ID; 2365 2366 /** 2367 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 2368 * the user may specify which view to go to next. 2369 */ 2370 private int mNextFocusDownId = View.NO_ID; 2371 2372 /** 2373 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 2374 * the user may specify which view to go to next. 2375 */ 2376 int mNextFocusForwardId = View.NO_ID; 2377 2378 private CheckForLongPress mPendingCheckForLongPress; 2379 private CheckForTap mPendingCheckForTap = null; 2380 private PerformClick mPerformClick; 2381 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 2382 2383 private UnsetPressedState mUnsetPressedState; 2384 2385 /** 2386 * Whether the long press's action has been invoked. The tap's action is invoked on the 2387 * up event while a long press is invoked as soon as the long press duration is reached, so 2388 * a long press could be performed before the tap is checked, in which case the tap's action 2389 * should not be invoked. 2390 */ 2391 private boolean mHasPerformedLongPress; 2392 2393 /** 2394 * The minimum height of the view. We'll try our best to have the height 2395 * of this view to at least this amount. 2396 */ 2397 @ViewDebug.ExportedProperty(category = "measurement") 2398 private int mMinHeight; 2399 2400 /** 2401 * The minimum width of the view. We'll try our best to have the width 2402 * of this view to at least this amount. 2403 */ 2404 @ViewDebug.ExportedProperty(category = "measurement") 2405 private int mMinWidth; 2406 2407 /** 2408 * The delegate to handle touch events that are physically in this view 2409 * but should be handled by another view. 2410 */ 2411 private TouchDelegate mTouchDelegate = null; 2412 2413 /** 2414 * Solid color to use as a background when creating the drawing cache. Enables 2415 * the cache to use 16 bit bitmaps instead of 32 bit. 2416 */ 2417 private int mDrawingCacheBackgroundColor = 0; 2418 2419 /** 2420 * Special tree observer used when mAttachInfo is null. 2421 */ 2422 private ViewTreeObserver mFloatingTreeObserver; 2423 2424 /** 2425 * Cache the touch slop from the context that created the view. 2426 */ 2427 private int mTouchSlop; 2428 2429 /** 2430 * Object that handles automatic animation of view properties. 2431 */ 2432 private ViewPropertyAnimator mAnimator = null; 2433 2434 /** 2435 * Flag indicating that a drag can cross window boundaries. When 2436 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 2437 * with this flag set, all visible applications will be able to participate 2438 * in the drag operation and receive the dragged content. 2439 * 2440 * @hide 2441 */ 2442 public static final int DRAG_FLAG_GLOBAL = 1; 2443 2444 /** 2445 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 2446 */ 2447 private float mVerticalScrollFactor; 2448 2449 /** 2450 * Position of the vertical scroll bar. 2451 */ 2452 private int mVerticalScrollbarPosition; 2453 2454 /** 2455 * Position the scroll bar at the default position as determined by the system. 2456 */ 2457 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 2458 2459 /** 2460 * Position the scroll bar along the left edge. 2461 */ 2462 public static final int SCROLLBAR_POSITION_LEFT = 1; 2463 2464 /** 2465 * Position the scroll bar along the right edge. 2466 */ 2467 public static final int SCROLLBAR_POSITION_RIGHT = 2; 2468 2469 /** 2470 * Indicates that the view does not have a layer. 2471 * 2472 * @see #getLayerType() 2473 * @see #setLayerType(int, android.graphics.Paint) 2474 * @see #LAYER_TYPE_SOFTWARE 2475 * @see #LAYER_TYPE_HARDWARE 2476 */ 2477 public static final int LAYER_TYPE_NONE = 0; 2478 2479 /** 2480 * <p>Indicates that the view has a software layer. A software layer is backed 2481 * by a bitmap and causes the view to be rendered using Android's software 2482 * rendering pipeline, even if hardware acceleration is enabled.</p> 2483 * 2484 * <p>Software layers have various usages:</p> 2485 * <p>When the application is not using hardware acceleration, a software layer 2486 * is useful to apply a specific color filter and/or blending mode and/or 2487 * translucency to a view and all its children.</p> 2488 * <p>When the application is using hardware acceleration, a software layer 2489 * is useful to render drawing primitives not supported by the hardware 2490 * accelerated pipeline. It can also be used to cache a complex view tree 2491 * into a texture and reduce the complexity of drawing operations. For instance, 2492 * when animating a complex view tree with a translation, a software layer can 2493 * be used to render the view tree only once.</p> 2494 * <p>Software layers should be avoided when the affected view tree updates 2495 * often. Every update will require to re-render the software layer, which can 2496 * potentially be slow (particularly when hardware acceleration is turned on 2497 * since the layer will have to be uploaded into a hardware texture after every 2498 * update.)</p> 2499 * 2500 * @see #getLayerType() 2501 * @see #setLayerType(int, android.graphics.Paint) 2502 * @see #LAYER_TYPE_NONE 2503 * @see #LAYER_TYPE_HARDWARE 2504 */ 2505 public static final int LAYER_TYPE_SOFTWARE = 1; 2506 2507 /** 2508 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 2509 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 2510 * OpenGL hardware) and causes the view to be rendered using Android's hardware 2511 * rendering pipeline, but only if hardware acceleration is turned on for the 2512 * view hierarchy. When hardware acceleration is turned off, hardware layers 2513 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 2514 * 2515 * <p>A hardware layer is useful to apply a specific color filter and/or 2516 * blending mode and/or translucency to a view and all its children.</p> 2517 * <p>A hardware layer can be used to cache a complex view tree into a 2518 * texture and reduce the complexity of drawing operations. For instance, 2519 * when animating a complex view tree with a translation, a hardware layer can 2520 * be used to render the view tree only once.</p> 2521 * <p>A hardware layer can also be used to increase the rendering quality when 2522 * rotation transformations are applied on a view. It can also be used to 2523 * prevent potential clipping issues when applying 3D transforms on a view.</p> 2524 * 2525 * @see #getLayerType() 2526 * @see #setLayerType(int, android.graphics.Paint) 2527 * @see #LAYER_TYPE_NONE 2528 * @see #LAYER_TYPE_SOFTWARE 2529 */ 2530 public static final int LAYER_TYPE_HARDWARE = 2; 2531 2532 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 2533 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 2534 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 2535 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 2536 }) 2537 int mLayerType = LAYER_TYPE_NONE; 2538 Paint mLayerPaint; 2539 Rect mLocalDirtyRect; 2540 2541 /** 2542 * Set to true when the view is sending hover accessibility events because it 2543 * is the innermost hovered view. 2544 */ 2545 private boolean mSendingHoverAccessibilityEvents; 2546 2547 /** 2548 * Delegate for injecting accessiblity functionality. 2549 */ 2550 AccessibilityDelegate mAccessibilityDelegate; 2551 2552 /** 2553 * Text direction is inherited thru {@link ViewGroup} 2554 * @hide 2555 */ 2556 public static final int TEXT_DIRECTION_INHERIT = 0; 2557 2558 /** 2559 * Text direction is using "first strong algorithm". The first strong directional character 2560 * determines the paragraph direction. If there is no strong directional character, the 2561 * paragraph direction is the view's resolved ayout direction. 2562 * 2563 * @hide 2564 */ 2565 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 2566 2567 /** 2568 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 2569 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 2570 * If there are neither, the paragraph direction is the view's resolved layout direction. 2571 * 2572 * @hide 2573 */ 2574 public static final int TEXT_DIRECTION_ANY_RTL = 2; 2575 2576 /** 2577 * Text direction is forced to LTR. 2578 * 2579 * @hide 2580 */ 2581 public static final int TEXT_DIRECTION_LTR = 3; 2582 2583 /** 2584 * Text direction is forced to RTL. 2585 * 2586 * @hide 2587 */ 2588 public static final int TEXT_DIRECTION_RTL = 4; 2589 2590 /** 2591 * Default text direction is inherited 2592 * 2593 * @hide 2594 */ 2595 protected static int DEFAULT_TEXT_DIRECTION = TEXT_DIRECTION_INHERIT; 2596 2597 /** 2598 * The text direction that has been defined by {@link #setTextDirection(int)}. 2599 * 2600 * {@hide} 2601 */ 2602 @ViewDebug.ExportedProperty(category = "text", mapping = { 2603 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 2604 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 2605 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 2606 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 2607 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL") 2608 }) 2609 private int mTextDirection = DEFAULT_TEXT_DIRECTION; 2610 2611 /** 2612 * The resolved text direction. This needs resolution if the value is 2613 * TEXT_DIRECTION_INHERIT. The resolution matches mTextDirection if that is 2614 * not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds up the parent 2615 * chain of the view. 2616 * 2617 * {@hide} 2618 */ 2619 @ViewDebug.ExportedProperty(category = "text", mapping = { 2620 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 2621 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 2622 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 2623 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 2624 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL") 2625 }) 2626 private int mResolvedTextDirection = TEXT_DIRECTION_INHERIT; 2627 2628 /** 2629 * Consistency verifier for debugging purposes. 2630 * @hide 2631 */ 2632 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 2633 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 2634 new InputEventConsistencyVerifier(this, 0) : null; 2635 2636 /** 2637 * Simple constructor to use when creating a view from code. 2638 * 2639 * @param context The Context the view is running in, through which it can 2640 * access the current theme, resources, etc. 2641 */ 2642 public View(Context context) { 2643 mContext = context; 2644 mResources = context != null ? context.getResources() : null; 2645 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED | LAYOUT_DIRECTION_INHERIT; 2646 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 2647 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 2648 mUserPaddingStart = -1; 2649 mUserPaddingEnd = -1; 2650 mUserPaddingRelative = false; 2651 } 2652 2653 /** 2654 * Constructor that is called when inflating a view from XML. This is called 2655 * when a view is being constructed from an XML file, supplying attributes 2656 * that were specified in the XML file. This version uses a default style of 2657 * 0, so the only attribute values applied are those in the Context's Theme 2658 * and the given AttributeSet. 2659 * 2660 * <p> 2661 * The method onFinishInflate() will be called after all children have been 2662 * added. 2663 * 2664 * @param context The Context the view is running in, through which it can 2665 * access the current theme, resources, etc. 2666 * @param attrs The attributes of the XML tag that is inflating the view. 2667 * @see #View(Context, AttributeSet, int) 2668 */ 2669 public View(Context context, AttributeSet attrs) { 2670 this(context, attrs, 0); 2671 } 2672 2673 /** 2674 * Perform inflation from XML and apply a class-specific base style. This 2675 * constructor of View allows subclasses to use their own base style when 2676 * they are inflating. For example, a Button class's constructor would call 2677 * this version of the super class constructor and supply 2678 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows 2679 * the theme's button style to modify all of the base view attributes (in 2680 * particular its background) as well as the Button class's attributes. 2681 * 2682 * @param context The Context the view is running in, through which it can 2683 * access the current theme, resources, etc. 2684 * @param attrs The attributes of the XML tag that is inflating the view. 2685 * @param defStyle The default style to apply to this view. If 0, no style 2686 * will be applied (beyond what is included in the theme). This may 2687 * either be an attribute resource, whose value will be retrieved 2688 * from the current theme, or an explicit style resource. 2689 * @see #View(Context, AttributeSet) 2690 */ 2691 public View(Context context, AttributeSet attrs, int defStyle) { 2692 this(context); 2693 2694 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View, 2695 defStyle, 0); 2696 2697 Drawable background = null; 2698 2699 int leftPadding = -1; 2700 int topPadding = -1; 2701 int rightPadding = -1; 2702 int bottomPadding = -1; 2703 int startPadding = -1; 2704 int endPadding = -1; 2705 2706 int padding = -1; 2707 2708 int viewFlagValues = 0; 2709 int viewFlagMasks = 0; 2710 2711 boolean setScrollContainer = false; 2712 2713 int x = 0; 2714 int y = 0; 2715 2716 float tx = 0; 2717 float ty = 0; 2718 float rotation = 0; 2719 float rotationX = 0; 2720 float rotationY = 0; 2721 float sx = 1f; 2722 float sy = 1f; 2723 boolean transformSet = false; 2724 2725 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 2726 2727 int overScrollMode = mOverScrollMode; 2728 final int N = a.getIndexCount(); 2729 for (int i = 0; i < N; i++) { 2730 int attr = a.getIndex(i); 2731 switch (attr) { 2732 case com.android.internal.R.styleable.View_background: 2733 background = a.getDrawable(attr); 2734 break; 2735 case com.android.internal.R.styleable.View_padding: 2736 padding = a.getDimensionPixelSize(attr, -1); 2737 break; 2738 case com.android.internal.R.styleable.View_paddingLeft: 2739 leftPadding = a.getDimensionPixelSize(attr, -1); 2740 break; 2741 case com.android.internal.R.styleable.View_paddingTop: 2742 topPadding = a.getDimensionPixelSize(attr, -1); 2743 break; 2744 case com.android.internal.R.styleable.View_paddingRight: 2745 rightPadding = a.getDimensionPixelSize(attr, -1); 2746 break; 2747 case com.android.internal.R.styleable.View_paddingBottom: 2748 bottomPadding = a.getDimensionPixelSize(attr, -1); 2749 break; 2750 case com.android.internal.R.styleable.View_paddingStart: 2751 startPadding = a.getDimensionPixelSize(attr, -1); 2752 break; 2753 case com.android.internal.R.styleable.View_paddingEnd: 2754 endPadding = a.getDimensionPixelSize(attr, -1); 2755 break; 2756 case com.android.internal.R.styleable.View_scrollX: 2757 x = a.getDimensionPixelOffset(attr, 0); 2758 break; 2759 case com.android.internal.R.styleable.View_scrollY: 2760 y = a.getDimensionPixelOffset(attr, 0); 2761 break; 2762 case com.android.internal.R.styleable.View_alpha: 2763 setAlpha(a.getFloat(attr, 1f)); 2764 break; 2765 case com.android.internal.R.styleable.View_transformPivotX: 2766 setPivotX(a.getDimensionPixelOffset(attr, 0)); 2767 break; 2768 case com.android.internal.R.styleable.View_transformPivotY: 2769 setPivotY(a.getDimensionPixelOffset(attr, 0)); 2770 break; 2771 case com.android.internal.R.styleable.View_translationX: 2772 tx = a.getDimensionPixelOffset(attr, 0); 2773 transformSet = true; 2774 break; 2775 case com.android.internal.R.styleable.View_translationY: 2776 ty = a.getDimensionPixelOffset(attr, 0); 2777 transformSet = true; 2778 break; 2779 case com.android.internal.R.styleable.View_rotation: 2780 rotation = a.getFloat(attr, 0); 2781 transformSet = true; 2782 break; 2783 case com.android.internal.R.styleable.View_rotationX: 2784 rotationX = a.getFloat(attr, 0); 2785 transformSet = true; 2786 break; 2787 case com.android.internal.R.styleable.View_rotationY: 2788 rotationY = a.getFloat(attr, 0); 2789 transformSet = true; 2790 break; 2791 case com.android.internal.R.styleable.View_scaleX: 2792 sx = a.getFloat(attr, 1f); 2793 transformSet = true; 2794 break; 2795 case com.android.internal.R.styleable.View_scaleY: 2796 sy = a.getFloat(attr, 1f); 2797 transformSet = true; 2798 break; 2799 case com.android.internal.R.styleable.View_id: 2800 mID = a.getResourceId(attr, NO_ID); 2801 break; 2802 case com.android.internal.R.styleable.View_tag: 2803 mTag = a.getText(attr); 2804 break; 2805 case com.android.internal.R.styleable.View_fitsSystemWindows: 2806 if (a.getBoolean(attr, false)) { 2807 viewFlagValues |= FITS_SYSTEM_WINDOWS; 2808 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 2809 } 2810 break; 2811 case com.android.internal.R.styleable.View_focusable: 2812 if (a.getBoolean(attr, false)) { 2813 viewFlagValues |= FOCUSABLE; 2814 viewFlagMasks |= FOCUSABLE_MASK; 2815 } 2816 break; 2817 case com.android.internal.R.styleable.View_focusableInTouchMode: 2818 if (a.getBoolean(attr, false)) { 2819 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 2820 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 2821 } 2822 break; 2823 case com.android.internal.R.styleable.View_clickable: 2824 if (a.getBoolean(attr, false)) { 2825 viewFlagValues |= CLICKABLE; 2826 viewFlagMasks |= CLICKABLE; 2827 } 2828 break; 2829 case com.android.internal.R.styleable.View_longClickable: 2830 if (a.getBoolean(attr, false)) { 2831 viewFlagValues |= LONG_CLICKABLE; 2832 viewFlagMasks |= LONG_CLICKABLE; 2833 } 2834 break; 2835 case com.android.internal.R.styleable.View_saveEnabled: 2836 if (!a.getBoolean(attr, true)) { 2837 viewFlagValues |= SAVE_DISABLED; 2838 viewFlagMasks |= SAVE_DISABLED_MASK; 2839 } 2840 break; 2841 case com.android.internal.R.styleable.View_duplicateParentState: 2842 if (a.getBoolean(attr, false)) { 2843 viewFlagValues |= DUPLICATE_PARENT_STATE; 2844 viewFlagMasks |= DUPLICATE_PARENT_STATE; 2845 } 2846 break; 2847 case com.android.internal.R.styleable.View_visibility: 2848 final int visibility = a.getInt(attr, 0); 2849 if (visibility != 0) { 2850 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 2851 viewFlagMasks |= VISIBILITY_MASK; 2852 } 2853 break; 2854 case com.android.internal.R.styleable.View_layoutDirection: 2855 // Clear any HORIZONTAL_DIRECTION flag already set 2856 viewFlagValues &= ~LAYOUT_DIRECTION_MASK; 2857 // Set the HORIZONTAL_DIRECTION flags depending on the value of the attribute 2858 final int layoutDirection = a.getInt(attr, -1); 2859 if (layoutDirection != -1) { 2860 viewFlagValues |= LAYOUT_DIRECTION_FLAGS[layoutDirection]; 2861 } else { 2862 // Set to default (LAYOUT_DIRECTION_INHERIT) 2863 viewFlagValues |= LAYOUT_DIRECTION_DEFAULT; 2864 } 2865 viewFlagMasks |= LAYOUT_DIRECTION_MASK; 2866 break; 2867 case com.android.internal.R.styleable.View_drawingCacheQuality: 2868 final int cacheQuality = a.getInt(attr, 0); 2869 if (cacheQuality != 0) { 2870 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 2871 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 2872 } 2873 break; 2874 case com.android.internal.R.styleable.View_contentDescription: 2875 mContentDescription = a.getString(attr); 2876 break; 2877 case com.android.internal.R.styleable.View_soundEffectsEnabled: 2878 if (!a.getBoolean(attr, true)) { 2879 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 2880 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 2881 } 2882 break; 2883 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 2884 if (!a.getBoolean(attr, true)) { 2885 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 2886 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 2887 } 2888 break; 2889 case R.styleable.View_scrollbars: 2890 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 2891 if (scrollbars != SCROLLBARS_NONE) { 2892 viewFlagValues |= scrollbars; 2893 viewFlagMasks |= SCROLLBARS_MASK; 2894 initializeScrollbars(a); 2895 } 2896 break; 2897 case R.styleable.View_fadingEdge: 2898 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 2899 if (fadingEdge != FADING_EDGE_NONE) { 2900 viewFlagValues |= fadingEdge; 2901 viewFlagMasks |= FADING_EDGE_MASK; 2902 initializeFadingEdge(a); 2903 } 2904 break; 2905 case R.styleable.View_scrollbarStyle: 2906 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 2907 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 2908 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 2909 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 2910 } 2911 break; 2912 case R.styleable.View_isScrollContainer: 2913 setScrollContainer = true; 2914 if (a.getBoolean(attr, false)) { 2915 setScrollContainer(true); 2916 } 2917 break; 2918 case com.android.internal.R.styleable.View_keepScreenOn: 2919 if (a.getBoolean(attr, false)) { 2920 viewFlagValues |= KEEP_SCREEN_ON; 2921 viewFlagMasks |= KEEP_SCREEN_ON; 2922 } 2923 break; 2924 case R.styleable.View_filterTouchesWhenObscured: 2925 if (a.getBoolean(attr, false)) { 2926 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 2927 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 2928 } 2929 break; 2930 case R.styleable.View_nextFocusLeft: 2931 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 2932 break; 2933 case R.styleable.View_nextFocusRight: 2934 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 2935 break; 2936 case R.styleable.View_nextFocusUp: 2937 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 2938 break; 2939 case R.styleable.View_nextFocusDown: 2940 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 2941 break; 2942 case R.styleable.View_nextFocusForward: 2943 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 2944 break; 2945 case R.styleable.View_minWidth: 2946 mMinWidth = a.getDimensionPixelSize(attr, 0); 2947 break; 2948 case R.styleable.View_minHeight: 2949 mMinHeight = a.getDimensionPixelSize(attr, 0); 2950 break; 2951 case R.styleable.View_onClick: 2952 if (context.isRestricted()) { 2953 throw new IllegalStateException("The android:onClick attribute cannot " 2954 + "be used within a restricted context"); 2955 } 2956 2957 final String handlerName = a.getString(attr); 2958 if (handlerName != null) { 2959 setOnClickListener(new OnClickListener() { 2960 private Method mHandler; 2961 2962 public void onClick(View v) { 2963 if (mHandler == null) { 2964 try { 2965 mHandler = getContext().getClass().getMethod(handlerName, 2966 View.class); 2967 } catch (NoSuchMethodException e) { 2968 int id = getId(); 2969 String idText = id == NO_ID ? "" : " with id '" 2970 + getContext().getResources().getResourceEntryName( 2971 id) + "'"; 2972 throw new IllegalStateException("Could not find a method " + 2973 handlerName + "(View) in the activity " 2974 + getContext().getClass() + " for onClick handler" 2975 + " on view " + View.this.getClass() + idText, e); 2976 } 2977 } 2978 2979 try { 2980 mHandler.invoke(getContext(), View.this); 2981 } catch (IllegalAccessException e) { 2982 throw new IllegalStateException("Could not execute non " 2983 + "public method of the activity", e); 2984 } catch (InvocationTargetException e) { 2985 throw new IllegalStateException("Could not execute " 2986 + "method of the activity", e); 2987 } 2988 } 2989 }); 2990 } 2991 break; 2992 case R.styleable.View_overScrollMode: 2993 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 2994 break; 2995 case R.styleable.View_verticalScrollbarPosition: 2996 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 2997 break; 2998 case R.styleable.View_layerType: 2999 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 3000 break; 3001 case R.styleable.View_textDirection: 3002 mTextDirection = a.getInt(attr, DEFAULT_TEXT_DIRECTION); 3003 break; 3004 } 3005 } 3006 3007 setOverScrollMode(overScrollMode); 3008 3009 if (background != null) { 3010 setBackgroundDrawable(background); 3011 } 3012 3013 mUserPaddingRelative = (startPadding >= 0 || endPadding >= 0); 3014 3015 // Cache user padding as we cannot fully resolve padding here (we dont have yet the resolved 3016 // layout direction). Those cached values will be used later during padding resolution. 3017 mUserPaddingStart = startPadding; 3018 mUserPaddingEnd = endPadding; 3019 3020 if (padding >= 0) { 3021 leftPadding = padding; 3022 topPadding = padding; 3023 rightPadding = padding; 3024 bottomPadding = padding; 3025 } 3026 3027 // If the user specified the padding (either with android:padding or 3028 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise 3029 // use the default padding or the padding from the background drawable 3030 // (stored at this point in mPadding*) 3031 setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft, 3032 topPadding >= 0 ? topPadding : mPaddingTop, 3033 rightPadding >= 0 ? rightPadding : mPaddingRight, 3034 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 3035 3036 if (viewFlagMasks != 0) { 3037 setFlags(viewFlagValues, viewFlagMasks); 3038 } 3039 3040 // Needs to be called after mViewFlags is set 3041 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3042 recomputePadding(); 3043 } 3044 3045 if (x != 0 || y != 0) { 3046 scrollTo(x, y); 3047 } 3048 3049 if (transformSet) { 3050 setTranslationX(tx); 3051 setTranslationY(ty); 3052 setRotation(rotation); 3053 setRotationX(rotationX); 3054 setRotationY(rotationY); 3055 setScaleX(sx); 3056 setScaleY(sy); 3057 } 3058 3059 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 3060 setScrollContainer(true); 3061 } 3062 3063 computeOpaqueFlags(); 3064 3065 a.recycle(); 3066 } 3067 3068 /** 3069 * Non-public constructor for use in testing 3070 */ 3071 View() { 3072 } 3073 3074 /** 3075 * <p> 3076 * Initializes the fading edges from a given set of styled attributes. This 3077 * method should be called by subclasses that need fading edges and when an 3078 * instance of these subclasses is created programmatically rather than 3079 * being inflated from XML. This method is automatically called when the XML 3080 * is inflated. 3081 * </p> 3082 * 3083 * @param a the styled attributes set to initialize the fading edges from 3084 */ 3085 protected void initializeFadingEdge(TypedArray a) { 3086 initScrollCache(); 3087 3088 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 3089 R.styleable.View_fadingEdgeLength, 3090 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 3091 } 3092 3093 /** 3094 * Returns the size of the vertical faded edges used to indicate that more 3095 * content in this view is visible. 3096 * 3097 * @return The size in pixels of the vertical faded edge or 0 if vertical 3098 * faded edges are not enabled for this view. 3099 * @attr ref android.R.styleable#View_fadingEdgeLength 3100 */ 3101 public int getVerticalFadingEdgeLength() { 3102 if (isVerticalFadingEdgeEnabled()) { 3103 ScrollabilityCache cache = mScrollCache; 3104 if (cache != null) { 3105 return cache.fadingEdgeLength; 3106 } 3107 } 3108 return 0; 3109 } 3110 3111 /** 3112 * Set the size of the faded edge used to indicate that more content in this 3113 * view is available. Will not change whether the fading edge is enabled; use 3114 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 3115 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 3116 * for the vertical or horizontal fading edges. 3117 * 3118 * @param length The size in pixels of the faded edge used to indicate that more 3119 * content in this view is visible. 3120 */ 3121 public void setFadingEdgeLength(int length) { 3122 initScrollCache(); 3123 mScrollCache.fadingEdgeLength = length; 3124 } 3125 3126 /** 3127 * Returns the size of the horizontal faded edges used to indicate that more 3128 * content in this view is visible. 3129 * 3130 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 3131 * faded edges are not enabled for this view. 3132 * @attr ref android.R.styleable#View_fadingEdgeLength 3133 */ 3134 public int getHorizontalFadingEdgeLength() { 3135 if (isHorizontalFadingEdgeEnabled()) { 3136 ScrollabilityCache cache = mScrollCache; 3137 if (cache != null) { 3138 return cache.fadingEdgeLength; 3139 } 3140 } 3141 return 0; 3142 } 3143 3144 /** 3145 * Returns the width of the vertical scrollbar. 3146 * 3147 * @return The width in pixels of the vertical scrollbar or 0 if there 3148 * is no vertical scrollbar. 3149 */ 3150 public int getVerticalScrollbarWidth() { 3151 ScrollabilityCache cache = mScrollCache; 3152 if (cache != null) { 3153 ScrollBarDrawable scrollBar = cache.scrollBar; 3154 if (scrollBar != null) { 3155 int size = scrollBar.getSize(true); 3156 if (size <= 0) { 3157 size = cache.scrollBarSize; 3158 } 3159 return size; 3160 } 3161 return 0; 3162 } 3163 return 0; 3164 } 3165 3166 /** 3167 * Returns the height of the horizontal scrollbar. 3168 * 3169 * @return The height in pixels of the horizontal scrollbar or 0 if 3170 * there is no horizontal scrollbar. 3171 */ 3172 protected int getHorizontalScrollbarHeight() { 3173 ScrollabilityCache cache = mScrollCache; 3174 if (cache != null) { 3175 ScrollBarDrawable scrollBar = cache.scrollBar; 3176 if (scrollBar != null) { 3177 int size = scrollBar.getSize(false); 3178 if (size <= 0) { 3179 size = cache.scrollBarSize; 3180 } 3181 return size; 3182 } 3183 return 0; 3184 } 3185 return 0; 3186 } 3187 3188 /** 3189 * <p> 3190 * Initializes the scrollbars from a given set of styled attributes. This 3191 * method should be called by subclasses that need scrollbars and when an 3192 * instance of these subclasses is created programmatically rather than 3193 * being inflated from XML. This method is automatically called when the XML 3194 * is inflated. 3195 * </p> 3196 * 3197 * @param a the styled attributes set to initialize the scrollbars from 3198 */ 3199 protected void initializeScrollbars(TypedArray a) { 3200 initScrollCache(); 3201 3202 final ScrollabilityCache scrollabilityCache = mScrollCache; 3203 3204 if (scrollabilityCache.scrollBar == null) { 3205 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 3206 } 3207 3208 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 3209 3210 if (!fadeScrollbars) { 3211 scrollabilityCache.state = ScrollabilityCache.ON; 3212 } 3213 scrollabilityCache.fadeScrollBars = fadeScrollbars; 3214 3215 3216 scrollabilityCache.scrollBarFadeDuration = a.getInt( 3217 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 3218 .getScrollBarFadeDuration()); 3219 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 3220 R.styleable.View_scrollbarDefaultDelayBeforeFade, 3221 ViewConfiguration.getScrollDefaultDelay()); 3222 3223 3224 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 3225 com.android.internal.R.styleable.View_scrollbarSize, 3226 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 3227 3228 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 3229 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 3230 3231 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 3232 if (thumb != null) { 3233 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 3234 } 3235 3236 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 3237 false); 3238 if (alwaysDraw) { 3239 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 3240 } 3241 3242 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 3243 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 3244 3245 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 3246 if (thumb != null) { 3247 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 3248 } 3249 3250 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 3251 false); 3252 if (alwaysDraw) { 3253 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 3254 } 3255 3256 // Re-apply user/background padding so that scrollbar(s) get added 3257 resolvePadding(); 3258 } 3259 3260 /** 3261 * <p> 3262 * Initalizes the scrollability cache if necessary. 3263 * </p> 3264 */ 3265 private void initScrollCache() { 3266 if (mScrollCache == null) { 3267 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 3268 } 3269 } 3270 3271 /** 3272 * Set the position of the vertical scroll bar. Should be one of 3273 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 3274 * {@link #SCROLLBAR_POSITION_RIGHT}. 3275 * 3276 * @param position Where the vertical scroll bar should be positioned. 3277 */ 3278 public void setVerticalScrollbarPosition(int position) { 3279 if (mVerticalScrollbarPosition != position) { 3280 mVerticalScrollbarPosition = position; 3281 computeOpaqueFlags(); 3282 resolvePadding(); 3283 } 3284 } 3285 3286 /** 3287 * @return The position where the vertical scroll bar will show, if applicable. 3288 * @see #setVerticalScrollbarPosition(int) 3289 */ 3290 public int getVerticalScrollbarPosition() { 3291 return mVerticalScrollbarPosition; 3292 } 3293 3294 /** 3295 * Register a callback to be invoked when focus of this view changed. 3296 * 3297 * @param l The callback that will run. 3298 */ 3299 public void setOnFocusChangeListener(OnFocusChangeListener l) { 3300 mOnFocusChangeListener = l; 3301 } 3302 3303 /** 3304 * Add a listener that will be called when the bounds of the view change due to 3305 * layout processing. 3306 * 3307 * @param listener The listener that will be called when layout bounds change. 3308 */ 3309 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 3310 if (mOnLayoutChangeListeners == null) { 3311 mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 3312 } 3313 mOnLayoutChangeListeners.add(listener); 3314 } 3315 3316 /** 3317 * Remove a listener for layout changes. 3318 * 3319 * @param listener The listener for layout bounds change. 3320 */ 3321 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 3322 if (mOnLayoutChangeListeners == null) { 3323 return; 3324 } 3325 mOnLayoutChangeListeners.remove(listener); 3326 } 3327 3328 /** 3329 * Add a listener for attach state changes. 3330 * 3331 * This listener will be called whenever this view is attached or detached 3332 * from a window. Remove the listener using 3333 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 3334 * 3335 * @param listener Listener to attach 3336 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 3337 */ 3338 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 3339 if (mOnAttachStateChangeListeners == null) { 3340 mOnAttachStateChangeListeners = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 3341 } 3342 mOnAttachStateChangeListeners.add(listener); 3343 } 3344 3345 /** 3346 * Remove a listener for attach state changes. The listener will receive no further 3347 * notification of window attach/detach events. 3348 * 3349 * @param listener Listener to remove 3350 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 3351 */ 3352 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 3353 if (mOnAttachStateChangeListeners == null) { 3354 return; 3355 } 3356 mOnAttachStateChangeListeners.remove(listener); 3357 } 3358 3359 /** 3360 * Returns the focus-change callback registered for this view. 3361 * 3362 * @return The callback, or null if one is not registered. 3363 */ 3364 public OnFocusChangeListener getOnFocusChangeListener() { 3365 return mOnFocusChangeListener; 3366 } 3367 3368 /** 3369 * Register a callback to be invoked when this view is clicked. If this view is not 3370 * clickable, it becomes clickable. 3371 * 3372 * @param l The callback that will run 3373 * 3374 * @see #setClickable(boolean) 3375 */ 3376 public void setOnClickListener(OnClickListener l) { 3377 if (!isClickable()) { 3378 setClickable(true); 3379 } 3380 mOnClickListener = l; 3381 } 3382 3383 /** 3384 * Register a callback to be invoked when this view is clicked and held. If this view is not 3385 * long clickable, it becomes long clickable. 3386 * 3387 * @param l The callback that will run 3388 * 3389 * @see #setLongClickable(boolean) 3390 */ 3391 public void setOnLongClickListener(OnLongClickListener l) { 3392 if (!isLongClickable()) { 3393 setLongClickable(true); 3394 } 3395 mOnLongClickListener = l; 3396 } 3397 3398 /** 3399 * Register a callback to be invoked when the context menu for this view is 3400 * being built. If this view is not long clickable, it becomes long clickable. 3401 * 3402 * @param l The callback that will run 3403 * 3404 */ 3405 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 3406 if (!isLongClickable()) { 3407 setLongClickable(true); 3408 } 3409 mOnCreateContextMenuListener = l; 3410 } 3411 3412 /** 3413 * Call this view's OnClickListener, if it is defined. 3414 * 3415 * @return True there was an assigned OnClickListener that was called, false 3416 * otherwise is returned. 3417 */ 3418 public boolean performClick() { 3419 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 3420 3421 if (mOnClickListener != null) { 3422 playSoundEffect(SoundEffectConstants.CLICK); 3423 mOnClickListener.onClick(this); 3424 return true; 3425 } 3426 3427 return false; 3428 } 3429 3430 /** 3431 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 3432 * OnLongClickListener did not consume the event. 3433 * 3434 * @return True if one of the above receivers consumed the event, false otherwise. 3435 */ 3436 public boolean performLongClick() { 3437 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 3438 3439 boolean handled = false; 3440 if (mOnLongClickListener != null) { 3441 handled = mOnLongClickListener.onLongClick(View.this); 3442 } 3443 if (!handled) { 3444 handled = showContextMenu(); 3445 } 3446 if (handled) { 3447 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 3448 } 3449 return handled; 3450 } 3451 3452 /** 3453 * Performs button-related actions during a touch down event. 3454 * 3455 * @param event The event. 3456 * @return True if the down was consumed. 3457 * 3458 * @hide 3459 */ 3460 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 3461 if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 3462 if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) { 3463 return true; 3464 } 3465 } 3466 return false; 3467 } 3468 3469 /** 3470 * Bring up the context menu for this view. 3471 * 3472 * @return Whether a context menu was displayed. 3473 */ 3474 public boolean showContextMenu() { 3475 return getParent().showContextMenuForChild(this); 3476 } 3477 3478 /** 3479 * Bring up the context menu for this view, referring to the item under the specified point. 3480 * 3481 * @param x The referenced x coordinate. 3482 * @param y The referenced y coordinate. 3483 * @param metaState The keyboard modifiers that were pressed. 3484 * @return Whether a context menu was displayed. 3485 * 3486 * @hide 3487 */ 3488 public boolean showContextMenu(float x, float y, int metaState) { 3489 return showContextMenu(); 3490 } 3491 3492 /** 3493 * Start an action mode. 3494 * 3495 * @param callback Callback that will control the lifecycle of the action mode 3496 * @return The new action mode if it is started, null otherwise 3497 * 3498 * @see ActionMode 3499 */ 3500 public ActionMode startActionMode(ActionMode.Callback callback) { 3501 return getParent().startActionModeForChild(this, callback); 3502 } 3503 3504 /** 3505 * Register a callback to be invoked when a key is pressed in this view. 3506 * @param l the key listener to attach to this view 3507 */ 3508 public void setOnKeyListener(OnKeyListener l) { 3509 mOnKeyListener = l; 3510 } 3511 3512 /** 3513 * Register a callback to be invoked when a touch event is sent to this view. 3514 * @param l the touch listener to attach to this view 3515 */ 3516 public void setOnTouchListener(OnTouchListener l) { 3517 mOnTouchListener = l; 3518 } 3519 3520 /** 3521 * Register a callback to be invoked when a generic motion event is sent to this view. 3522 * @param l the generic motion listener to attach to this view 3523 */ 3524 public void setOnGenericMotionListener(OnGenericMotionListener l) { 3525 mOnGenericMotionListener = l; 3526 } 3527 3528 /** 3529 * Register a callback to be invoked when a hover event is sent to this view. 3530 * @param l the hover listener to attach to this view 3531 */ 3532 public void setOnHoverListener(OnHoverListener l) { 3533 mOnHoverListener = l; 3534 } 3535 3536 /** 3537 * Register a drag event listener callback object for this View. The parameter is 3538 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 3539 * View, the system calls the 3540 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 3541 * @param l An implementation of {@link android.view.View.OnDragListener}. 3542 */ 3543 public void setOnDragListener(OnDragListener l) { 3544 mOnDragListener = l; 3545 } 3546 3547 /** 3548 * Give this view focus. This will cause 3549 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 3550 * 3551 * Note: this does not check whether this {@link View} should get focus, it just 3552 * gives it focus no matter what. It should only be called internally by framework 3553 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 3554 * 3555 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 3556 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 3557 * focus moved when requestFocus() is called. It may not always 3558 * apply, in which case use the default View.FOCUS_DOWN. 3559 * @param previouslyFocusedRect The rectangle of the view that had focus 3560 * prior in this View's coordinate system. 3561 */ 3562 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) { 3563 if (DBG) { 3564 System.out.println(this + " requestFocus()"); 3565 } 3566 3567 if ((mPrivateFlags & FOCUSED) == 0) { 3568 mPrivateFlags |= FOCUSED; 3569 3570 if (mParent != null) { 3571 mParent.requestChildFocus(this, this); 3572 } 3573 3574 onFocusChanged(true, direction, previouslyFocusedRect); 3575 refreshDrawableState(); 3576 } 3577 } 3578 3579 /** 3580 * Request that a rectangle of this view be visible on the screen, 3581 * scrolling if necessary just enough. 3582 * 3583 * <p>A View should call this if it maintains some notion of which part 3584 * of its content is interesting. For example, a text editing view 3585 * should call this when its cursor moves. 3586 * 3587 * @param rectangle The rectangle. 3588 * @return Whether any parent scrolled. 3589 */ 3590 public boolean requestRectangleOnScreen(Rect rectangle) { 3591 return requestRectangleOnScreen(rectangle, false); 3592 } 3593 3594 /** 3595 * Request that a rectangle of this view be visible on the screen, 3596 * scrolling if necessary just enough. 3597 * 3598 * <p>A View should call this if it maintains some notion of which part 3599 * of its content is interesting. For example, a text editing view 3600 * should call this when its cursor moves. 3601 * 3602 * <p>When <code>immediate</code> is set to true, scrolling will not be 3603 * animated. 3604 * 3605 * @param rectangle The rectangle. 3606 * @param immediate True to forbid animated scrolling, false otherwise 3607 * @return Whether any parent scrolled. 3608 */ 3609 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 3610 View child = this; 3611 ViewParent parent = mParent; 3612 boolean scrolled = false; 3613 while (parent != null) { 3614 scrolled |= parent.requestChildRectangleOnScreen(child, 3615 rectangle, immediate); 3616 3617 // offset rect so next call has the rectangle in the 3618 // coordinate system of its direct child. 3619 rectangle.offset(child.getLeft(), child.getTop()); 3620 rectangle.offset(-child.getScrollX(), -child.getScrollY()); 3621 3622 if (!(parent instanceof View)) { 3623 break; 3624 } 3625 3626 child = (View) parent; 3627 parent = child.getParent(); 3628 } 3629 return scrolled; 3630 } 3631 3632 /** 3633 * Called when this view wants to give up focus. This will cause 3634 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 3635 */ 3636 public void clearFocus() { 3637 if (DBG) { 3638 System.out.println(this + " clearFocus()"); 3639 } 3640 3641 if ((mPrivateFlags & FOCUSED) != 0) { 3642 mPrivateFlags &= ~FOCUSED; 3643 3644 if (mParent != null) { 3645 mParent.clearChildFocus(this); 3646 } 3647 3648 onFocusChanged(false, 0, null); 3649 refreshDrawableState(); 3650 } 3651 } 3652 3653 /** 3654 * Called to clear the focus of a view that is about to be removed. 3655 * Doesn't call clearChildFocus, which prevents this view from taking 3656 * focus again before it has been removed from the parent 3657 */ 3658 void clearFocusForRemoval() { 3659 if ((mPrivateFlags & FOCUSED) != 0) { 3660 mPrivateFlags &= ~FOCUSED; 3661 3662 onFocusChanged(false, 0, null); 3663 refreshDrawableState(); 3664 } 3665 } 3666 3667 /** 3668 * Called internally by the view system when a new view is getting focus. 3669 * This is what clears the old focus. 3670 */ 3671 void unFocus() { 3672 if (DBG) { 3673 System.out.println(this + " unFocus()"); 3674 } 3675 3676 if ((mPrivateFlags & FOCUSED) != 0) { 3677 mPrivateFlags &= ~FOCUSED; 3678 3679 onFocusChanged(false, 0, null); 3680 refreshDrawableState(); 3681 } 3682 } 3683 3684 /** 3685 * Returns true if this view has focus iteself, or is the ancestor of the 3686 * view that has focus. 3687 * 3688 * @return True if this view has or contains focus, false otherwise. 3689 */ 3690 @ViewDebug.ExportedProperty(category = "focus") 3691 public boolean hasFocus() { 3692 return (mPrivateFlags & FOCUSED) != 0; 3693 } 3694 3695 /** 3696 * Returns true if this view is focusable or if it contains a reachable View 3697 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 3698 * is a View whose parents do not block descendants focus. 3699 * 3700 * Only {@link #VISIBLE} views are considered focusable. 3701 * 3702 * @return True if the view is focusable or if the view contains a focusable 3703 * View, false otherwise. 3704 * 3705 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 3706 */ 3707 public boolean hasFocusable() { 3708 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 3709 } 3710 3711 /** 3712 * Called by the view system when the focus state of this view changes. 3713 * When the focus change event is caused by directional navigation, direction 3714 * and previouslyFocusedRect provide insight into where the focus is coming from. 3715 * When overriding, be sure to call up through to the super class so that 3716 * the standard focus handling will occur. 3717 * 3718 * @param gainFocus True if the View has focus; false otherwise. 3719 * @param direction The direction focus has moved when requestFocus() 3720 * is called to give this view focus. Values are 3721 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 3722 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 3723 * It may not always apply, in which case use the default. 3724 * @param previouslyFocusedRect The rectangle, in this view's coordinate 3725 * system, of the previously focused view. If applicable, this will be 3726 * passed in as finer grained information about where the focus is coming 3727 * from (in addition to direction). Will be <code>null</code> otherwise. 3728 */ 3729 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) { 3730 if (gainFocus) { 3731 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 3732 } 3733 3734 InputMethodManager imm = InputMethodManager.peekInstance(); 3735 if (!gainFocus) { 3736 if (isPressed()) { 3737 setPressed(false); 3738 } 3739 if (imm != null && mAttachInfo != null 3740 && mAttachInfo.mHasWindowFocus) { 3741 imm.focusOut(this); 3742 } 3743 onFocusLost(); 3744 } else if (imm != null && mAttachInfo != null 3745 && mAttachInfo.mHasWindowFocus) { 3746 imm.focusIn(this); 3747 } 3748 3749 invalidate(true); 3750 if (mOnFocusChangeListener != null) { 3751 mOnFocusChangeListener.onFocusChange(this, gainFocus); 3752 } 3753 3754 if (mAttachInfo != null) { 3755 mAttachInfo.mKeyDispatchState.reset(this); 3756 } 3757 } 3758 3759 /** 3760 * Sends an accessibility event of the given type. If accessiiblity is 3761 * not enabled this method has no effect. The default implementation calls 3762 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 3763 * to populate information about the event source (this View), then calls 3764 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 3765 * populate the text content of the event source including its descendants, 3766 * and last calls 3767 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 3768 * on its parent to resuest sending of the event to interested parties. 3769 * <p> 3770 * If an {@link AccessibilityDelegate} has been specified via calling 3771 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 3772 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 3773 * responsible for handling this call. 3774 * </p> 3775 * 3776 * @param eventType The type of the event to send. 3777 * 3778 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 3779 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 3780 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 3781 * @see AccessibilityDelegate 3782 */ 3783 public void sendAccessibilityEvent(int eventType) { 3784 if (mAccessibilityDelegate != null) { 3785 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 3786 } else { 3787 sendAccessibilityEventInternal(eventType); 3788 } 3789 } 3790 3791 /** 3792 * @see #sendAccessibilityEvent(int) 3793 * 3794 * Note: Called from the default {@link AccessibilityDelegate}. 3795 */ 3796 void sendAccessibilityEventInternal(int eventType) { 3797 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 3798 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 3799 } 3800 } 3801 3802 /** 3803 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 3804 * takes as an argument an empty {@link AccessibilityEvent} and does not 3805 * perform a check whether accessibility is enabled. 3806 * <p> 3807 * If an {@link AccessibilityDelegate} has been specified via calling 3808 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 3809 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 3810 * is responsible for handling this call. 3811 * </p> 3812 * 3813 * @param event The event to send. 3814 * 3815 * @see #sendAccessibilityEvent(int) 3816 */ 3817 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 3818 if (mAccessibilityDelegate != null) { 3819 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 3820 } else { 3821 sendAccessibilityEventUncheckedInternal(event); 3822 } 3823 } 3824 3825 /** 3826 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 3827 * 3828 * Note: Called from the default {@link AccessibilityDelegate}. 3829 */ 3830 void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 3831 if (!isShown()) { 3832 return; 3833 } 3834 onInitializeAccessibilityEvent(event); 3835 dispatchPopulateAccessibilityEvent(event); 3836 // In the beginning we called #isShown(), so we know that getParent() is not null. 3837 getParent().requestSendAccessibilityEvent(this, event); 3838 } 3839 3840 /** 3841 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 3842 * to its children for adding their text content to the event. Note that the 3843 * event text is populated in a separate dispatch path since we add to the 3844 * event not only the text of the source but also the text of all its descendants. 3845 * A typical implementation will call 3846 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 3847 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 3848 * on each child. Override this method if custom population of the event text 3849 * content is required. 3850 * <p> 3851 * If an {@link AccessibilityDelegate} has been specified via calling 3852 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 3853 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 3854 * is responsible for handling this call. 3855 * </p> 3856 * 3857 * @param event The event. 3858 * 3859 * @return True if the event population was completed. 3860 */ 3861 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 3862 if (mAccessibilityDelegate != null) { 3863 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 3864 } else { 3865 return dispatchPopulateAccessibilityEventInternal(event); 3866 } 3867 } 3868 3869 /** 3870 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 3871 * 3872 * Note: Called from the default {@link AccessibilityDelegate}. 3873 */ 3874 boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 3875 onPopulateAccessibilityEvent(event); 3876 return false; 3877 } 3878 3879 /** 3880 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 3881 * giving a chance to this View to populate the accessibility event with its 3882 * text content. While the implementation is free to modify other event 3883 * attributes this should be performed in 3884 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 3885 * <p> 3886 * Example: Adding formatted date string to an accessibility event in addition 3887 * to the text added by the super implementation. 3888 * </p><p><pre><code> 3889 * public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 3890 * super.onPopulateAccessibilityEvent(event); 3891 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 3892 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 3893 * mCurrentDate.getTimeInMillis(), flags); 3894 * event.getText().add(selectedDateUtterance); 3895 * } 3896 * </code></pre></p> 3897 * <p> 3898 * If an {@link AccessibilityDelegate} has been specified via calling 3899 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 3900 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 3901 * is responsible for handling this call. 3902 * </p> 3903 * 3904 * @param event The accessibility event which to populate. 3905 * 3906 * @see #sendAccessibilityEvent(int) 3907 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 3908 */ 3909 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 3910 if (mAccessibilityDelegate != null) { 3911 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 3912 } else { 3913 onPopulateAccessibilityEventInternal(event); 3914 } 3915 } 3916 3917 /** 3918 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 3919 * 3920 * Note: Called from the default {@link AccessibilityDelegate}. 3921 */ 3922 void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 3923 3924 } 3925 3926 /** 3927 * Initializes an {@link AccessibilityEvent} with information about 3928 * this View which is the event source. In other words, the source of 3929 * an accessibility event is the view whose state change triggered firing 3930 * the event. 3931 * <p> 3932 * Example: Setting the password property of an event in addition 3933 * to properties set by the super implementation. 3934 * </p><p><pre><code> 3935 * public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 3936 * super.onInitializeAccessibilityEvent(event); 3937 * event.setPassword(true); 3938 * } 3939 * </code></pre></p> 3940 * <p> 3941 * If an {@link AccessibilityDelegate} has been specified via calling 3942 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 3943 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 3944 * is responsible for handling this call. 3945 * </p> 3946 * 3947 * @param event The event to initialize. 3948 * 3949 * @see #sendAccessibilityEvent(int) 3950 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 3951 */ 3952 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 3953 if (mAccessibilityDelegate != null) { 3954 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 3955 } else { 3956 onInitializeAccessibilityEventInternal(event); 3957 } 3958 } 3959 3960 /** 3961 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 3962 * 3963 * Note: Called from the default {@link AccessibilityDelegate}. 3964 */ 3965 void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 3966 event.setSource(this); 3967 event.setClassName(getClass().getName()); 3968 event.setPackageName(getContext().getPackageName()); 3969 event.setEnabled(isEnabled()); 3970 event.setContentDescription(mContentDescription); 3971 3972 final int eventType = event.getEventType(); 3973 switch (eventType) { 3974 case AccessibilityEvent.TYPE_VIEW_FOCUSED: { 3975 if (mAttachInfo != null) { 3976 ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList; 3977 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, 3978 FOCUSABLES_ALL); 3979 event.setItemCount(focusablesTempList.size()); 3980 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 3981 focusablesTempList.clear(); 3982 } 3983 } break; 3984 case AccessibilityEvent.TYPE_VIEW_SCROLLED: { 3985 event.setScrollX(mScrollX); 3986 event.setScrollY(mScrollY); 3987 event.setItemCount(getHeight()); 3988 } break; 3989 } 3990 } 3991 3992 /** 3993 * Returns an {@link AccessibilityNodeInfo} representing this view from the 3994 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 3995 * This method is responsible for obtaining an accessibility node info from a 3996 * pool of reusable instances and calling 3997 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 3998 * initialize the former. 3999 * <p> 4000 * Note: The client is responsible for recycling the obtained instance by calling 4001 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 4002 * </p> 4003 * @return A populated {@link AccessibilityNodeInfo}. 4004 * 4005 * @see AccessibilityNodeInfo 4006 */ 4007 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 4008 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 4009 onInitializeAccessibilityNodeInfo(info); 4010 return info; 4011 } 4012 4013 /** 4014 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 4015 * The base implementation sets: 4016 * <ul> 4017 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 4018 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 4019 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 4020 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 4021 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 4022 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 4023 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 4024 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 4025 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 4026 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 4027 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 4028 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 4029 * </ul> 4030 * <p> 4031 * Subclasses should override this method, call the super implementation, 4032 * and set additional attributes. 4033 * </p> 4034 * <p> 4035 * If an {@link AccessibilityDelegate} has been specified via calling 4036 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4037 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 4038 * is responsible for handling this call. 4039 * </p> 4040 * 4041 * @param info The instance to initialize. 4042 */ 4043 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 4044 if (mAccessibilityDelegate != null) { 4045 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 4046 } else { 4047 onInitializeAccessibilityNodeInfoInternal(info); 4048 } 4049 } 4050 4051 /** 4052 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 4053 * 4054 * Note: Called from the default {@link AccessibilityDelegate}. 4055 */ 4056 void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 4057 Rect bounds = mAttachInfo.mTmpInvalRect; 4058 getDrawingRect(bounds); 4059 info.setBoundsInParent(bounds); 4060 4061 int[] locationOnScreen = mAttachInfo.mInvalidateChildLocation; 4062 getLocationOnScreen(locationOnScreen); 4063 bounds.offsetTo(0, 0); 4064 bounds.offset(locationOnScreen[0], locationOnScreen[1]); 4065 info.setBoundsInScreen(bounds); 4066 4067 ViewParent parent = getParent(); 4068 if (parent instanceof View) { 4069 View parentView = (View) parent; 4070 info.setParent(parentView); 4071 } 4072 4073 info.setPackageName(mContext.getPackageName()); 4074 info.setClassName(getClass().getName()); 4075 info.setContentDescription(getContentDescription()); 4076 4077 info.setEnabled(isEnabled()); 4078 info.setClickable(isClickable()); 4079 info.setFocusable(isFocusable()); 4080 info.setFocused(isFocused()); 4081 info.setSelected(isSelected()); 4082 info.setLongClickable(isLongClickable()); 4083 4084 // TODO: These make sense only if we are in an AdapterView but all 4085 // views can be selected. Maybe from accessiiblity perspective 4086 // we should report as selectable view in an AdapterView. 4087 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 4088 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 4089 4090 if (isFocusable()) { 4091 if (isFocused()) { 4092 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 4093 } else { 4094 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 4095 } 4096 } 4097 } 4098 4099 /** 4100 * Sets a delegate for implementing accessibility support via compositon as 4101 * opposed to inheritance. The delegate's primary use is for implementing 4102 * backwards compatible widgets. For more details see {@link AccessibilityDelegate}. 4103 * 4104 * @param delegate The delegate instance. 4105 * 4106 * @see AccessibilityDelegate 4107 */ 4108 public void setAccessibilityDelegate(AccessibilityDelegate delegate) { 4109 mAccessibilityDelegate = delegate; 4110 } 4111 4112 /** 4113 * Gets the unique identifier of this view on the screen for accessibility purposes. 4114 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 4115 * 4116 * @return The view accessibility id. 4117 * 4118 * @hide 4119 */ 4120 public int getAccessibilityViewId() { 4121 if (mAccessibilityViewId == NO_ID) { 4122 mAccessibilityViewId = sNextAccessibilityViewId++; 4123 } 4124 return mAccessibilityViewId; 4125 } 4126 4127 /** 4128 * Gets the unique identifier of the window in which this View reseides. 4129 * 4130 * @return The window accessibility id. 4131 * 4132 * @hide 4133 */ 4134 public int getAccessibilityWindowId() { 4135 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID; 4136 } 4137 4138 /** 4139 * Gets the {@link View} description. It briefly describes the view and is 4140 * primarily used for accessibility support. Set this property to enable 4141 * better accessibility support for your application. This is especially 4142 * true for views that do not have textual representation (For example, 4143 * ImageButton). 4144 * 4145 * @return The content descriptiopn. 4146 * 4147 * @attr ref android.R.styleable#View_contentDescription 4148 */ 4149 public CharSequence getContentDescription() { 4150 return mContentDescription; 4151 } 4152 4153 /** 4154 * Sets the {@link View} description. It briefly describes the view and is 4155 * primarily used for accessibility support. Set this property to enable 4156 * better accessibility support for your application. This is especially 4157 * true for views that do not have textual representation (For example, 4158 * ImageButton). 4159 * 4160 * @param contentDescription The content description. 4161 * 4162 * @attr ref android.R.styleable#View_contentDescription 4163 */ 4164 public void setContentDescription(CharSequence contentDescription) { 4165 mContentDescription = contentDescription; 4166 } 4167 4168 /** 4169 * Invoked whenever this view loses focus, either by losing window focus or by losing 4170 * focus within its window. This method can be used to clear any state tied to the 4171 * focus. For instance, if a button is held pressed with the trackball and the window 4172 * loses focus, this method can be used to cancel the press. 4173 * 4174 * Subclasses of View overriding this method should always call super.onFocusLost(). 4175 * 4176 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 4177 * @see #onWindowFocusChanged(boolean) 4178 * 4179 * @hide pending API council approval 4180 */ 4181 protected void onFocusLost() { 4182 resetPressedState(); 4183 } 4184 4185 private void resetPressedState() { 4186 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 4187 return; 4188 } 4189 4190 if (isPressed()) { 4191 setPressed(false); 4192 4193 if (!mHasPerformedLongPress) { 4194 removeLongPressCallback(); 4195 } 4196 } 4197 } 4198 4199 /** 4200 * Returns true if this view has focus 4201 * 4202 * @return True if this view has focus, false otherwise. 4203 */ 4204 @ViewDebug.ExportedProperty(category = "focus") 4205 public boolean isFocused() { 4206 return (mPrivateFlags & FOCUSED) != 0; 4207 } 4208 4209 /** 4210 * Find the view in the hierarchy rooted at this view that currently has 4211 * focus. 4212 * 4213 * @return The view that currently has focus, or null if no focused view can 4214 * be found. 4215 */ 4216 public View findFocus() { 4217 return (mPrivateFlags & FOCUSED) != 0 ? this : null; 4218 } 4219 4220 /** 4221 * Change whether this view is one of the set of scrollable containers in 4222 * its window. This will be used to determine whether the window can 4223 * resize or must pan when a soft input area is open -- scrollable 4224 * containers allow the window to use resize mode since the container 4225 * will appropriately shrink. 4226 */ 4227 public void setScrollContainer(boolean isScrollContainer) { 4228 if (isScrollContainer) { 4229 if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) { 4230 mAttachInfo.mScrollContainers.add(this); 4231 mPrivateFlags |= SCROLL_CONTAINER_ADDED; 4232 } 4233 mPrivateFlags |= SCROLL_CONTAINER; 4234 } else { 4235 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) { 4236 mAttachInfo.mScrollContainers.remove(this); 4237 } 4238 mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED); 4239 } 4240 } 4241 4242 /** 4243 * Returns the quality of the drawing cache. 4244 * 4245 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 4246 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 4247 * 4248 * @see #setDrawingCacheQuality(int) 4249 * @see #setDrawingCacheEnabled(boolean) 4250 * @see #isDrawingCacheEnabled() 4251 * 4252 * @attr ref android.R.styleable#View_drawingCacheQuality 4253 */ 4254 public int getDrawingCacheQuality() { 4255 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 4256 } 4257 4258 /** 4259 * Set the drawing cache quality of this view. This value is used only when the 4260 * drawing cache is enabled 4261 * 4262 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 4263 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 4264 * 4265 * @see #getDrawingCacheQuality() 4266 * @see #setDrawingCacheEnabled(boolean) 4267 * @see #isDrawingCacheEnabled() 4268 * 4269 * @attr ref android.R.styleable#View_drawingCacheQuality 4270 */ 4271 public void setDrawingCacheQuality(int quality) { 4272 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 4273 } 4274 4275 /** 4276 * Returns whether the screen should remain on, corresponding to the current 4277 * value of {@link #KEEP_SCREEN_ON}. 4278 * 4279 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 4280 * 4281 * @see #setKeepScreenOn(boolean) 4282 * 4283 * @attr ref android.R.styleable#View_keepScreenOn 4284 */ 4285 public boolean getKeepScreenOn() { 4286 return (mViewFlags & KEEP_SCREEN_ON) != 0; 4287 } 4288 4289 /** 4290 * Controls whether the screen should remain on, modifying the 4291 * value of {@link #KEEP_SCREEN_ON}. 4292 * 4293 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 4294 * 4295 * @see #getKeepScreenOn() 4296 * 4297 * @attr ref android.R.styleable#View_keepScreenOn 4298 */ 4299 public void setKeepScreenOn(boolean keepScreenOn) { 4300 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 4301 } 4302 4303 /** 4304 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 4305 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4306 * 4307 * @attr ref android.R.styleable#View_nextFocusLeft 4308 */ 4309 public int getNextFocusLeftId() { 4310 return mNextFocusLeftId; 4311 } 4312 4313 /** 4314 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 4315 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 4316 * decide automatically. 4317 * 4318 * @attr ref android.R.styleable#View_nextFocusLeft 4319 */ 4320 public void setNextFocusLeftId(int nextFocusLeftId) { 4321 mNextFocusLeftId = nextFocusLeftId; 4322 } 4323 4324 /** 4325 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 4326 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4327 * 4328 * @attr ref android.R.styleable#View_nextFocusRight 4329 */ 4330 public int getNextFocusRightId() { 4331 return mNextFocusRightId; 4332 } 4333 4334 /** 4335 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 4336 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 4337 * decide automatically. 4338 * 4339 * @attr ref android.R.styleable#View_nextFocusRight 4340 */ 4341 public void setNextFocusRightId(int nextFocusRightId) { 4342 mNextFocusRightId = nextFocusRightId; 4343 } 4344 4345 /** 4346 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 4347 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4348 * 4349 * @attr ref android.R.styleable#View_nextFocusUp 4350 */ 4351 public int getNextFocusUpId() { 4352 return mNextFocusUpId; 4353 } 4354 4355 /** 4356 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 4357 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 4358 * decide automatically. 4359 * 4360 * @attr ref android.R.styleable#View_nextFocusUp 4361 */ 4362 public void setNextFocusUpId(int nextFocusUpId) { 4363 mNextFocusUpId = nextFocusUpId; 4364 } 4365 4366 /** 4367 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 4368 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4369 * 4370 * @attr ref android.R.styleable#View_nextFocusDown 4371 */ 4372 public int getNextFocusDownId() { 4373 return mNextFocusDownId; 4374 } 4375 4376 /** 4377 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 4378 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 4379 * decide automatically. 4380 * 4381 * @attr ref android.R.styleable#View_nextFocusDown 4382 */ 4383 public void setNextFocusDownId(int nextFocusDownId) { 4384 mNextFocusDownId = nextFocusDownId; 4385 } 4386 4387 /** 4388 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 4389 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4390 * 4391 * @attr ref android.R.styleable#View_nextFocusForward 4392 */ 4393 public int getNextFocusForwardId() { 4394 return mNextFocusForwardId; 4395 } 4396 4397 /** 4398 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 4399 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 4400 * decide automatically. 4401 * 4402 * @attr ref android.R.styleable#View_nextFocusForward 4403 */ 4404 public void setNextFocusForwardId(int nextFocusForwardId) { 4405 mNextFocusForwardId = nextFocusForwardId; 4406 } 4407 4408 /** 4409 * Returns the visibility of this view and all of its ancestors 4410 * 4411 * @return True if this view and all of its ancestors are {@link #VISIBLE} 4412 */ 4413 public boolean isShown() { 4414 View current = this; 4415 //noinspection ConstantConditions 4416 do { 4417 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 4418 return false; 4419 } 4420 ViewParent parent = current.mParent; 4421 if (parent == null) { 4422 return false; // We are not attached to the view root 4423 } 4424 if (!(parent instanceof View)) { 4425 return true; 4426 } 4427 current = (View) parent; 4428 } while (current != null); 4429 4430 return false; 4431 } 4432 4433 /** 4434 * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag 4435 * is set 4436 * 4437 * @param insets Insets for system windows 4438 * 4439 * @return True if this view applied the insets, false otherwise 4440 */ 4441 protected boolean fitSystemWindows(Rect insets) { 4442 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 4443 mPaddingLeft = insets.left; 4444 mPaddingTop = insets.top; 4445 mPaddingRight = insets.right; 4446 mPaddingBottom = insets.bottom; 4447 requestLayout(); 4448 return true; 4449 } 4450 return false; 4451 } 4452 4453 /** 4454 * Set whether or not this view should account for system screen decorations 4455 * such as the status bar and inset its content. This allows this view to be 4456 * positioned in absolute screen coordinates and remain visible to the user. 4457 * 4458 * <p>This should only be used by top-level window decor views. 4459 * 4460 * @param fitSystemWindows true to inset content for system screen decorations, false for 4461 * default behavior. 4462 * 4463 * @attr ref android.R.styleable#View_fitsSystemWindows 4464 */ 4465 public void setFitsSystemWindows(boolean fitSystemWindows) { 4466 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 4467 } 4468 4469 /** 4470 * Check for the FITS_SYSTEM_WINDOWS flag. If this method returns true, this view 4471 * will account for system screen decorations such as the status bar and inset its 4472 * content. This allows the view to be positioned in absolute screen coordinates 4473 * and remain visible to the user. 4474 * 4475 * @return true if this view will adjust its content bounds for system screen decorations. 4476 * 4477 * @attr ref android.R.styleable#View_fitsSystemWindows 4478 */ 4479 public boolean fitsSystemWindows() { 4480 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 4481 } 4482 4483 /** 4484 * Returns the visibility status for this view. 4485 * 4486 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 4487 * @attr ref android.R.styleable#View_visibility 4488 */ 4489 @ViewDebug.ExportedProperty(mapping = { 4490 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 4491 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 4492 @ViewDebug.IntToString(from = GONE, to = "GONE") 4493 }) 4494 public int getVisibility() { 4495 return mViewFlags & VISIBILITY_MASK; 4496 } 4497 4498 /** 4499 * Set the enabled state of this view. 4500 * 4501 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 4502 * @attr ref android.R.styleable#View_visibility 4503 */ 4504 @RemotableViewMethod 4505 public void setVisibility(int visibility) { 4506 setFlags(visibility, VISIBILITY_MASK); 4507 if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false); 4508 } 4509 4510 /** 4511 * Returns the enabled status for this view. The interpretation of the 4512 * enabled state varies by subclass. 4513 * 4514 * @return True if this view is enabled, false otherwise. 4515 */ 4516 @ViewDebug.ExportedProperty 4517 public boolean isEnabled() { 4518 return (mViewFlags & ENABLED_MASK) == ENABLED; 4519 } 4520 4521 /** 4522 * Set the enabled state of this view. The interpretation of the enabled 4523 * state varies by subclass. 4524 * 4525 * @param enabled True if this view is enabled, false otherwise. 4526 */ 4527 @RemotableViewMethod 4528 public void setEnabled(boolean enabled) { 4529 if (enabled == isEnabled()) return; 4530 4531 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 4532 4533 /* 4534 * The View most likely has to change its appearance, so refresh 4535 * the drawable state. 4536 */ 4537 refreshDrawableState(); 4538 4539 // Invalidate too, since the default behavior for views is to be 4540 // be drawn at 50% alpha rather than to change the drawable. 4541 invalidate(true); 4542 } 4543 4544 /** 4545 * Set whether this view can receive the focus. 4546 * 4547 * Setting this to false will also ensure that this view is not focusable 4548 * in touch mode. 4549 * 4550 * @param focusable If true, this view can receive the focus. 4551 * 4552 * @see #setFocusableInTouchMode(boolean) 4553 * @attr ref android.R.styleable#View_focusable 4554 */ 4555 public void setFocusable(boolean focusable) { 4556 if (!focusable) { 4557 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 4558 } 4559 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 4560 } 4561 4562 /** 4563 * Set whether this view can receive focus while in touch mode. 4564 * 4565 * Setting this to true will also ensure that this view is focusable. 4566 * 4567 * @param focusableInTouchMode If true, this view can receive the focus while 4568 * in touch mode. 4569 * 4570 * @see #setFocusable(boolean) 4571 * @attr ref android.R.styleable#View_focusableInTouchMode 4572 */ 4573 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 4574 // Focusable in touch mode should always be set before the focusable flag 4575 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 4576 // which, in touch mode, will not successfully request focus on this view 4577 // because the focusable in touch mode flag is not set 4578 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 4579 if (focusableInTouchMode) { 4580 setFlags(FOCUSABLE, FOCUSABLE_MASK); 4581 } 4582 } 4583 4584 /** 4585 * Set whether this view should have sound effects enabled for events such as 4586 * clicking and touching. 4587 * 4588 * <p>You may wish to disable sound effects for a view if you already play sounds, 4589 * for instance, a dial key that plays dtmf tones. 4590 * 4591 * @param soundEffectsEnabled whether sound effects are enabled for this view. 4592 * @see #isSoundEffectsEnabled() 4593 * @see #playSoundEffect(int) 4594 * @attr ref android.R.styleable#View_soundEffectsEnabled 4595 */ 4596 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 4597 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 4598 } 4599 4600 /** 4601 * @return whether this view should have sound effects enabled for events such as 4602 * clicking and touching. 4603 * 4604 * @see #setSoundEffectsEnabled(boolean) 4605 * @see #playSoundEffect(int) 4606 * @attr ref android.R.styleable#View_soundEffectsEnabled 4607 */ 4608 @ViewDebug.ExportedProperty 4609 public boolean isSoundEffectsEnabled() { 4610 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 4611 } 4612 4613 /** 4614 * Set whether this view should have haptic feedback for events such as 4615 * long presses. 4616 * 4617 * <p>You may wish to disable haptic feedback if your view already controls 4618 * its own haptic feedback. 4619 * 4620 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 4621 * @see #isHapticFeedbackEnabled() 4622 * @see #performHapticFeedback(int) 4623 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 4624 */ 4625 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 4626 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 4627 } 4628 4629 /** 4630 * @return whether this view should have haptic feedback enabled for events 4631 * long presses. 4632 * 4633 * @see #setHapticFeedbackEnabled(boolean) 4634 * @see #performHapticFeedback(int) 4635 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 4636 */ 4637 @ViewDebug.ExportedProperty 4638 public boolean isHapticFeedbackEnabled() { 4639 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 4640 } 4641 4642 /** 4643 * Returns the layout direction for this view. 4644 * 4645 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 4646 * {@link #LAYOUT_DIRECTION_RTL}, 4647 * {@link #LAYOUT_DIRECTION_INHERIT} or 4648 * {@link #LAYOUT_DIRECTION_LOCALE}. 4649 * @attr ref android.R.styleable#View_layoutDirection 4650 * 4651 * @hide 4652 */ 4653 @ViewDebug.ExportedProperty(category = "layout", mapping = { 4654 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 4655 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 4656 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 4657 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 4658 }) 4659 public int getLayoutDirection() { 4660 return mViewFlags & LAYOUT_DIRECTION_MASK; 4661 } 4662 4663 /** 4664 * Set the layout direction for this view. This will propagate a reset of layout direction 4665 * resolution to the view's children and resolve layout direction for this view. 4666 * 4667 * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR}, 4668 * {@link #LAYOUT_DIRECTION_RTL}, 4669 * {@link #LAYOUT_DIRECTION_INHERIT} or 4670 * {@link #LAYOUT_DIRECTION_LOCALE}. 4671 * 4672 * @attr ref android.R.styleable#View_layoutDirection 4673 * 4674 * @hide 4675 */ 4676 @RemotableViewMethod 4677 public void setLayoutDirection(int layoutDirection) { 4678 if (getLayoutDirection() != layoutDirection) { 4679 resetResolvedLayoutDirection(); 4680 // Setting the flag will also request a layout. 4681 setFlags(layoutDirection, LAYOUT_DIRECTION_MASK); 4682 } 4683 } 4684 4685 /** 4686 * Returns the resolved layout direction for this view. 4687 * 4688 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 4689 * {@link #LAYOUT_DIRECTION_LTR} id the layout direction is not RTL. 4690 * 4691 * @hide 4692 */ 4693 @ViewDebug.ExportedProperty(category = "layout", mapping = { 4694 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 4695 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 4696 }) 4697 public int getResolvedLayoutDirection() { 4698 resolveLayoutDirectionIfNeeded(); 4699 return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ? 4700 LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 4701 } 4702 4703 /** 4704 * <p>Indicates whether or not this view's layout is right-to-left. This is resolved from 4705 * layout attribute and/or the inherited value from the parent.</p> 4706 * 4707 * @return true if the layout is right-to-left. 4708 * 4709 * @hide 4710 */ 4711 @ViewDebug.ExportedProperty(category = "layout") 4712 public boolean isLayoutRtl() { 4713 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL); 4714 } 4715 4716 /** 4717 * If this view doesn't do any drawing on its own, set this flag to 4718 * allow further optimizations. By default, this flag is not set on 4719 * View, but could be set on some View subclasses such as ViewGroup. 4720 * 4721 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 4722 * you should clear this flag. 4723 * 4724 * @param willNotDraw whether or not this View draw on its own 4725 */ 4726 public void setWillNotDraw(boolean willNotDraw) { 4727 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 4728 } 4729 4730 /** 4731 * Returns whether or not this View draws on its own. 4732 * 4733 * @return true if this view has nothing to draw, false otherwise 4734 */ 4735 @ViewDebug.ExportedProperty(category = "drawing") 4736 public boolean willNotDraw() { 4737 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 4738 } 4739 4740 /** 4741 * When a View's drawing cache is enabled, drawing is redirected to an 4742 * offscreen bitmap. Some views, like an ImageView, must be able to 4743 * bypass this mechanism if they already draw a single bitmap, to avoid 4744 * unnecessary usage of the memory. 4745 * 4746 * @param willNotCacheDrawing true if this view does not cache its 4747 * drawing, false otherwise 4748 */ 4749 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 4750 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 4751 } 4752 4753 /** 4754 * Returns whether or not this View can cache its drawing or not. 4755 * 4756 * @return true if this view does not cache its drawing, false otherwise 4757 */ 4758 @ViewDebug.ExportedProperty(category = "drawing") 4759 public boolean willNotCacheDrawing() { 4760 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 4761 } 4762 4763 /** 4764 * Indicates whether this view reacts to click events or not. 4765 * 4766 * @return true if the view is clickable, false otherwise 4767 * 4768 * @see #setClickable(boolean) 4769 * @attr ref android.R.styleable#View_clickable 4770 */ 4771 @ViewDebug.ExportedProperty 4772 public boolean isClickable() { 4773 return (mViewFlags & CLICKABLE) == CLICKABLE; 4774 } 4775 4776 /** 4777 * Enables or disables click events for this view. When a view 4778 * is clickable it will change its state to "pressed" on every click. 4779 * Subclasses should set the view clickable to visually react to 4780 * user's clicks. 4781 * 4782 * @param clickable true to make the view clickable, false otherwise 4783 * 4784 * @see #isClickable() 4785 * @attr ref android.R.styleable#View_clickable 4786 */ 4787 public void setClickable(boolean clickable) { 4788 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 4789 } 4790 4791 /** 4792 * Indicates whether this view reacts to long click events or not. 4793 * 4794 * @return true if the view is long clickable, false otherwise 4795 * 4796 * @see #setLongClickable(boolean) 4797 * @attr ref android.R.styleable#View_longClickable 4798 */ 4799 public boolean isLongClickable() { 4800 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 4801 } 4802 4803 /** 4804 * Enables or disables long click events for this view. When a view is long 4805 * clickable it reacts to the user holding down the button for a longer 4806 * duration than a tap. This event can either launch the listener or a 4807 * context menu. 4808 * 4809 * @param longClickable true to make the view long clickable, false otherwise 4810 * @see #isLongClickable() 4811 * @attr ref android.R.styleable#View_longClickable 4812 */ 4813 public void setLongClickable(boolean longClickable) { 4814 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 4815 } 4816 4817 /** 4818 * Sets the pressed state for this view. 4819 * 4820 * @see #isClickable() 4821 * @see #setClickable(boolean) 4822 * 4823 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 4824 * the View's internal state from a previously set "pressed" state. 4825 */ 4826 public void setPressed(boolean pressed) { 4827 if (pressed) { 4828 mPrivateFlags |= PRESSED; 4829 } else { 4830 mPrivateFlags &= ~PRESSED; 4831 } 4832 refreshDrawableState(); 4833 dispatchSetPressed(pressed); 4834 } 4835 4836 /** 4837 * Dispatch setPressed to all of this View's children. 4838 * 4839 * @see #setPressed(boolean) 4840 * 4841 * @param pressed The new pressed state 4842 */ 4843 protected void dispatchSetPressed(boolean pressed) { 4844 } 4845 4846 /** 4847 * Indicates whether the view is currently in pressed state. Unless 4848 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 4849 * the pressed state. 4850 * 4851 * @see #setPressed(boolean) 4852 * @see #isClickable() 4853 * @see #setClickable(boolean) 4854 * 4855 * @return true if the view is currently pressed, false otherwise 4856 */ 4857 public boolean isPressed() { 4858 return (mPrivateFlags & PRESSED) == PRESSED; 4859 } 4860 4861 /** 4862 * Indicates whether this view will save its state (that is, 4863 * whether its {@link #onSaveInstanceState} method will be called). 4864 * 4865 * @return Returns true if the view state saving is enabled, else false. 4866 * 4867 * @see #setSaveEnabled(boolean) 4868 * @attr ref android.R.styleable#View_saveEnabled 4869 */ 4870 public boolean isSaveEnabled() { 4871 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 4872 } 4873 4874 /** 4875 * Controls whether the saving of this view's state is 4876 * enabled (that is, whether its {@link #onSaveInstanceState} method 4877 * will be called). Note that even if freezing is enabled, the 4878 * view still must have an id assigned to it (via {@link #setId(int)}) 4879 * for its state to be saved. This flag can only disable the 4880 * saving of this view; any child views may still have their state saved. 4881 * 4882 * @param enabled Set to false to <em>disable</em> state saving, or true 4883 * (the default) to allow it. 4884 * 4885 * @see #isSaveEnabled() 4886 * @see #setId(int) 4887 * @see #onSaveInstanceState() 4888 * @attr ref android.R.styleable#View_saveEnabled 4889 */ 4890 public void setSaveEnabled(boolean enabled) { 4891 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 4892 } 4893 4894 /** 4895 * Gets whether the framework should discard touches when the view's 4896 * window is obscured by another visible window. 4897 * Refer to the {@link View} security documentation for more details. 4898 * 4899 * @return True if touch filtering is enabled. 4900 * 4901 * @see #setFilterTouchesWhenObscured(boolean) 4902 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 4903 */ 4904 @ViewDebug.ExportedProperty 4905 public boolean getFilterTouchesWhenObscured() { 4906 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 4907 } 4908 4909 /** 4910 * Sets whether the framework should discard touches when the view's 4911 * window is obscured by another visible window. 4912 * Refer to the {@link View} security documentation for more details. 4913 * 4914 * @param enabled True if touch filtering should be enabled. 4915 * 4916 * @see #getFilterTouchesWhenObscured 4917 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 4918 */ 4919 public void setFilterTouchesWhenObscured(boolean enabled) { 4920 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED, 4921 FILTER_TOUCHES_WHEN_OBSCURED); 4922 } 4923 4924 /** 4925 * Indicates whether the entire hierarchy under this view will save its 4926 * state when a state saving traversal occurs from its parent. The default 4927 * is true; if false, these views will not be saved unless 4928 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 4929 * 4930 * @return Returns true if the view state saving from parent is enabled, else false. 4931 * 4932 * @see #setSaveFromParentEnabled(boolean) 4933 */ 4934 public boolean isSaveFromParentEnabled() { 4935 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 4936 } 4937 4938 /** 4939 * Controls whether the entire hierarchy under this view will save its 4940 * state when a state saving traversal occurs from its parent. The default 4941 * is true; if false, these views will not be saved unless 4942 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 4943 * 4944 * @param enabled Set to false to <em>disable</em> state saving, or true 4945 * (the default) to allow it. 4946 * 4947 * @see #isSaveFromParentEnabled() 4948 * @see #setId(int) 4949 * @see #onSaveInstanceState() 4950 */ 4951 public void setSaveFromParentEnabled(boolean enabled) { 4952 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 4953 } 4954 4955 4956 /** 4957 * Returns whether this View is able to take focus. 4958 * 4959 * @return True if this view can take focus, or false otherwise. 4960 * @attr ref android.R.styleable#View_focusable 4961 */ 4962 @ViewDebug.ExportedProperty(category = "focus") 4963 public final boolean isFocusable() { 4964 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 4965 } 4966 4967 /** 4968 * When a view is focusable, it may not want to take focus when in touch mode. 4969 * For example, a button would like focus when the user is navigating via a D-pad 4970 * so that the user can click on it, but once the user starts touching the screen, 4971 * the button shouldn't take focus 4972 * @return Whether the view is focusable in touch mode. 4973 * @attr ref android.R.styleable#View_focusableInTouchMode 4974 */ 4975 @ViewDebug.ExportedProperty 4976 public final boolean isFocusableInTouchMode() { 4977 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 4978 } 4979 4980 /** 4981 * Find the nearest view in the specified direction that can take focus. 4982 * This does not actually give focus to that view. 4983 * 4984 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 4985 * 4986 * @return The nearest focusable in the specified direction, or null if none 4987 * can be found. 4988 */ 4989 public View focusSearch(int direction) { 4990 if (mParent != null) { 4991 return mParent.focusSearch(this, direction); 4992 } else { 4993 return null; 4994 } 4995 } 4996 4997 /** 4998 * This method is the last chance for the focused view and its ancestors to 4999 * respond to an arrow key. This is called when the focused view did not 5000 * consume the key internally, nor could the view system find a new view in 5001 * the requested direction to give focus to. 5002 * 5003 * @param focused The currently focused view. 5004 * @param direction The direction focus wants to move. One of FOCUS_UP, 5005 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 5006 * @return True if the this view consumed this unhandled move. 5007 */ 5008 public boolean dispatchUnhandledMove(View focused, int direction) { 5009 return false; 5010 } 5011 5012 /** 5013 * If a user manually specified the next view id for a particular direction, 5014 * use the root to look up the view. 5015 * @param root The root view of the hierarchy containing this view. 5016 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 5017 * or FOCUS_BACKWARD. 5018 * @return The user specified next view, or null if there is none. 5019 */ 5020 View findUserSetNextFocus(View root, int direction) { 5021 switch (direction) { 5022 case FOCUS_LEFT: 5023 if (mNextFocusLeftId == View.NO_ID) return null; 5024 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 5025 case FOCUS_RIGHT: 5026 if (mNextFocusRightId == View.NO_ID) return null; 5027 return findViewInsideOutShouldExist(root, mNextFocusRightId); 5028 case FOCUS_UP: 5029 if (mNextFocusUpId == View.NO_ID) return null; 5030 return findViewInsideOutShouldExist(root, mNextFocusUpId); 5031 case FOCUS_DOWN: 5032 if (mNextFocusDownId == View.NO_ID) return null; 5033 return findViewInsideOutShouldExist(root, mNextFocusDownId); 5034 case FOCUS_FORWARD: 5035 if (mNextFocusForwardId == View.NO_ID) return null; 5036 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 5037 case FOCUS_BACKWARD: { 5038 final int id = mID; 5039 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 5040 @Override 5041 public boolean apply(View t) { 5042 return t.mNextFocusForwardId == id; 5043 } 5044 }); 5045 } 5046 } 5047 return null; 5048 } 5049 5050 private View findViewInsideOutShouldExist(View root, final int childViewId) { 5051 View result = root.findViewByPredicateInsideOut(this, new Predicate<View>() { 5052 @Override 5053 public boolean apply(View t) { 5054 return t.mID == childViewId; 5055 } 5056 }); 5057 5058 if (result == null) { 5059 Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified " 5060 + "by user for id " + childViewId); 5061 } 5062 return result; 5063 } 5064 5065 /** 5066 * Find and return all focusable views that are descendants of this view, 5067 * possibly including this view if it is focusable itself. 5068 * 5069 * @param direction The direction of the focus 5070 * @return A list of focusable views 5071 */ 5072 public ArrayList<View> getFocusables(int direction) { 5073 ArrayList<View> result = new ArrayList<View>(24); 5074 addFocusables(result, direction); 5075 return result; 5076 } 5077 5078 /** 5079 * Add any focusable views that are descendants of this view (possibly 5080 * including this view if it is focusable itself) to views. If we are in touch mode, 5081 * only add views that are also focusable in touch mode. 5082 * 5083 * @param views Focusable views found so far 5084 * @param direction The direction of the focus 5085 */ 5086 public void addFocusables(ArrayList<View> views, int direction) { 5087 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 5088 } 5089 5090 /** 5091 * Adds any focusable views that are descendants of this view (possibly 5092 * including this view if it is focusable itself) to views. This method 5093 * adds all focusable views regardless if we are in touch mode or 5094 * only views focusable in touch mode if we are in touch mode depending on 5095 * the focusable mode paramater. 5096 * 5097 * @param views Focusable views found so far or null if all we are interested is 5098 * the number of focusables. 5099 * @param direction The direction of the focus. 5100 * @param focusableMode The type of focusables to be added. 5101 * 5102 * @see #FOCUSABLES_ALL 5103 * @see #FOCUSABLES_TOUCH_MODE 5104 */ 5105 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { 5106 if (!isFocusable()) { 5107 return; 5108 } 5109 5110 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE && 5111 isInTouchMode() && !isFocusableInTouchMode()) { 5112 return; 5113 } 5114 5115 if (views != null) { 5116 views.add(this); 5117 } 5118 } 5119 5120 /** 5121 * Finds the Views that contain given text. The containment is case insensitive. 5122 * As View's text is considered any text content that View renders. 5123 * 5124 * @param outViews The output list of matching Views. 5125 * @param text The text to match against. 5126 */ 5127 public void findViewsWithText(ArrayList<View> outViews, CharSequence text) { 5128 } 5129 5130 /** 5131 * Find and return all touchable views that are descendants of this view, 5132 * possibly including this view if it is touchable itself. 5133 * 5134 * @return A list of touchable views 5135 */ 5136 public ArrayList<View> getTouchables() { 5137 ArrayList<View> result = new ArrayList<View>(); 5138 addTouchables(result); 5139 return result; 5140 } 5141 5142 /** 5143 * Add any touchable views that are descendants of this view (possibly 5144 * including this view if it is touchable itself) to views. 5145 * 5146 * @param views Touchable views found so far 5147 */ 5148 public void addTouchables(ArrayList<View> views) { 5149 final int viewFlags = mViewFlags; 5150 5151 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 5152 && (viewFlags & ENABLED_MASK) == ENABLED) { 5153 views.add(this); 5154 } 5155 } 5156 5157 /** 5158 * Call this to try to give focus to a specific view or to one of its 5159 * descendants. 5160 * 5161 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 5162 * false), or if it is focusable and it is not focusable in touch mode 5163 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 5164 * 5165 * See also {@link #focusSearch(int)}, which is what you call to say that you 5166 * have focus, and you want your parent to look for the next one. 5167 * 5168 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 5169 * {@link #FOCUS_DOWN} and <code>null</code>. 5170 * 5171 * @return Whether this view or one of its descendants actually took focus. 5172 */ 5173 public final boolean requestFocus() { 5174 return requestFocus(View.FOCUS_DOWN); 5175 } 5176 5177 5178 /** 5179 * Call this to try to give focus to a specific view or to one of its 5180 * descendants and give it a hint about what direction focus is heading. 5181 * 5182 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 5183 * false), or if it is focusable and it is not focusable in touch mode 5184 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 5185 * 5186 * See also {@link #focusSearch(int)}, which is what you call to say that you 5187 * have focus, and you want your parent to look for the next one. 5188 * 5189 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 5190 * <code>null</code> set for the previously focused rectangle. 5191 * 5192 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 5193 * @return Whether this view or one of its descendants actually took focus. 5194 */ 5195 public final boolean requestFocus(int direction) { 5196 return requestFocus(direction, null); 5197 } 5198 5199 /** 5200 * Call this to try to give focus to a specific view or to one of its descendants 5201 * and give it hints about the direction and a specific rectangle that the focus 5202 * is coming from. The rectangle can help give larger views a finer grained hint 5203 * about where focus is coming from, and therefore, where to show selection, or 5204 * forward focus change internally. 5205 * 5206 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 5207 * false), or if it is focusable and it is not focusable in touch mode 5208 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 5209 * 5210 * A View will not take focus if it is not visible. 5211 * 5212 * A View will not take focus if one of its parents has 5213 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 5214 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 5215 * 5216 * See also {@link #focusSearch(int)}, which is what you call to say that you 5217 * have focus, and you want your parent to look for the next one. 5218 * 5219 * You may wish to override this method if your custom {@link View} has an internal 5220 * {@link View} that it wishes to forward the request to. 5221 * 5222 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 5223 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 5224 * to give a finer grained hint about where focus is coming from. May be null 5225 * if there is no hint. 5226 * @return Whether this view or one of its descendants actually took focus. 5227 */ 5228 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 5229 // need to be focusable 5230 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 5231 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 5232 return false; 5233 } 5234 5235 // need to be focusable in touch mode if in touch mode 5236 if (isInTouchMode() && 5237 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 5238 return false; 5239 } 5240 5241 // need to not have any parents blocking us 5242 if (hasAncestorThatBlocksDescendantFocus()) { 5243 return false; 5244 } 5245 5246 handleFocusGainInternal(direction, previouslyFocusedRect); 5247 return true; 5248 } 5249 5250 /** Gets the ViewAncestor, or null if not attached. */ 5251 /*package*/ ViewRootImpl getViewRootImpl() { 5252 View root = getRootView(); 5253 return root != null ? (ViewRootImpl)root.getParent() : null; 5254 } 5255 5256 /** 5257 * Call this to try to give focus to a specific view or to one of its descendants. This is a 5258 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 5259 * touch mode to request focus when they are touched. 5260 * 5261 * @return Whether this view or one of its descendants actually took focus. 5262 * 5263 * @see #isInTouchMode() 5264 * 5265 */ 5266 public final boolean requestFocusFromTouch() { 5267 // Leave touch mode if we need to 5268 if (isInTouchMode()) { 5269 ViewRootImpl viewRoot = getViewRootImpl(); 5270 if (viewRoot != null) { 5271 viewRoot.ensureTouchMode(false); 5272 } 5273 } 5274 return requestFocus(View.FOCUS_DOWN); 5275 } 5276 5277 /** 5278 * @return Whether any ancestor of this view blocks descendant focus. 5279 */ 5280 private boolean hasAncestorThatBlocksDescendantFocus() { 5281 ViewParent ancestor = mParent; 5282 while (ancestor instanceof ViewGroup) { 5283 final ViewGroup vgAncestor = (ViewGroup) ancestor; 5284 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) { 5285 return true; 5286 } else { 5287 ancestor = vgAncestor.getParent(); 5288 } 5289 } 5290 return false; 5291 } 5292 5293 /** 5294 * @hide 5295 */ 5296 public void dispatchStartTemporaryDetach() { 5297 onStartTemporaryDetach(); 5298 } 5299 5300 /** 5301 * This is called when a container is going to temporarily detach a child, with 5302 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 5303 * It will either be followed by {@link #onFinishTemporaryDetach()} or 5304 * {@link #onDetachedFromWindow()} when the container is done. 5305 */ 5306 public void onStartTemporaryDetach() { 5307 removeUnsetPressCallback(); 5308 mPrivateFlags |= CANCEL_NEXT_UP_EVENT; 5309 } 5310 5311 /** 5312 * @hide 5313 */ 5314 public void dispatchFinishTemporaryDetach() { 5315 onFinishTemporaryDetach(); 5316 } 5317 5318 /** 5319 * Called after {@link #onStartTemporaryDetach} when the container is done 5320 * changing the view. 5321 */ 5322 public void onFinishTemporaryDetach() { 5323 } 5324 5325 /** 5326 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 5327 * for this view's window. Returns null if the view is not currently attached 5328 * to the window. Normally you will not need to use this directly, but 5329 * just use the standard high-level event callbacks like 5330 * {@link #onKeyDown(int, KeyEvent)}. 5331 */ 5332 public KeyEvent.DispatcherState getKeyDispatcherState() { 5333 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 5334 } 5335 5336 /** 5337 * Dispatch a key event before it is processed by any input method 5338 * associated with the view hierarchy. This can be used to intercept 5339 * key events in special situations before the IME consumes them; a 5340 * typical example would be handling the BACK key to update the application's 5341 * UI instead of allowing the IME to see it and close itself. 5342 * 5343 * @param event The key event to be dispatched. 5344 * @return True if the event was handled, false otherwise. 5345 */ 5346 public boolean dispatchKeyEventPreIme(KeyEvent event) { 5347 return onKeyPreIme(event.getKeyCode(), event); 5348 } 5349 5350 /** 5351 * Dispatch a key event to the next view on the focus path. This path runs 5352 * from the top of the view tree down to the currently focused view. If this 5353 * view has focus, it will dispatch to itself. Otherwise it will dispatch 5354 * the next node down the focus path. This method also fires any key 5355 * listeners. 5356 * 5357 * @param event The key event to be dispatched. 5358 * @return True if the event was handled, false otherwise. 5359 */ 5360 public boolean dispatchKeyEvent(KeyEvent event) { 5361 if (mInputEventConsistencyVerifier != null) { 5362 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 5363 } 5364 5365 // Give any attached key listener a first crack at the event. 5366 //noinspection SimplifiableIfStatement 5367 if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 5368 && mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 5369 return true; 5370 } 5371 5372 if (event.dispatch(this, mAttachInfo != null 5373 ? mAttachInfo.mKeyDispatchState : null, this)) { 5374 return true; 5375 } 5376 5377 if (mInputEventConsistencyVerifier != null) { 5378 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5379 } 5380 return false; 5381 } 5382 5383 /** 5384 * Dispatches a key shortcut event. 5385 * 5386 * @param event The key event to be dispatched. 5387 * @return True if the event was handled by the view, false otherwise. 5388 */ 5389 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 5390 return onKeyShortcut(event.getKeyCode(), event); 5391 } 5392 5393 /** 5394 * Pass the touch screen motion event down to the target view, or this 5395 * view if it is the target. 5396 * 5397 * @param event The motion event to be dispatched. 5398 * @return True if the event was handled by the view, false otherwise. 5399 */ 5400 public boolean dispatchTouchEvent(MotionEvent event) { 5401 if (mInputEventConsistencyVerifier != null) { 5402 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 5403 } 5404 5405 if (onFilterTouchEventForSecurity(event)) { 5406 //noinspection SimplifiableIfStatement 5407 if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED && 5408 mOnTouchListener.onTouch(this, event)) { 5409 return true; 5410 } 5411 5412 if (onTouchEvent(event)) { 5413 return true; 5414 } 5415 } 5416 5417 if (mInputEventConsistencyVerifier != null) { 5418 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5419 } 5420 return false; 5421 } 5422 5423 /** 5424 * Filter the touch event to apply security policies. 5425 * 5426 * @param event The motion event to be filtered. 5427 * @return True if the event should be dispatched, false if the event should be dropped. 5428 * 5429 * @see #getFilterTouchesWhenObscured 5430 */ 5431 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 5432 //noinspection RedundantIfStatement 5433 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 5434 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 5435 // Window is obscured, drop this touch. 5436 return false; 5437 } 5438 return true; 5439 } 5440 5441 /** 5442 * Pass a trackball motion event down to the focused view. 5443 * 5444 * @param event The motion event to be dispatched. 5445 * @return True if the event was handled by the view, false otherwise. 5446 */ 5447 public boolean dispatchTrackballEvent(MotionEvent event) { 5448 if (mInputEventConsistencyVerifier != null) { 5449 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 5450 } 5451 5452 return onTrackballEvent(event); 5453 } 5454 5455 /** 5456 * Dispatch a generic motion event. 5457 * <p> 5458 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 5459 * are delivered to the view under the pointer. All other generic motion events are 5460 * delivered to the focused view. Hover events are handled specially and are delivered 5461 * to {@link #onHoverEvent(MotionEvent)}. 5462 * </p> 5463 * 5464 * @param event The motion event to be dispatched. 5465 * @return True if the event was handled by the view, false otherwise. 5466 */ 5467 public boolean dispatchGenericMotionEvent(MotionEvent event) { 5468 if (mInputEventConsistencyVerifier != null) { 5469 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 5470 } 5471 5472 final int source = event.getSource(); 5473 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 5474 final int action = event.getAction(); 5475 if (action == MotionEvent.ACTION_HOVER_ENTER 5476 || action == MotionEvent.ACTION_HOVER_MOVE 5477 || action == MotionEvent.ACTION_HOVER_EXIT) { 5478 if (dispatchHoverEvent(event)) { 5479 return true; 5480 } 5481 } else if (dispatchGenericPointerEvent(event)) { 5482 return true; 5483 } 5484 } else if (dispatchGenericFocusedEvent(event)) { 5485 return true; 5486 } 5487 5488 if (dispatchGenericMotionEventInternal(event)) { 5489 return true; 5490 } 5491 5492 if (mInputEventConsistencyVerifier != null) { 5493 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5494 } 5495 return false; 5496 } 5497 5498 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 5499 //noinspection SimplifiableIfStatement 5500 if (mOnGenericMotionListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 5501 && mOnGenericMotionListener.onGenericMotion(this, event)) { 5502 return true; 5503 } 5504 5505 if (onGenericMotionEvent(event)) { 5506 return true; 5507 } 5508 5509 if (mInputEventConsistencyVerifier != null) { 5510 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5511 } 5512 return false; 5513 } 5514 5515 /** 5516 * Dispatch a hover event. 5517 * <p> 5518 * Do not call this method directly. 5519 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 5520 * </p> 5521 * 5522 * @param event The motion event to be dispatched. 5523 * @return True if the event was handled by the view, false otherwise. 5524 */ 5525 protected boolean dispatchHoverEvent(MotionEvent event) { 5526 //noinspection SimplifiableIfStatement 5527 if (mOnHoverListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 5528 && mOnHoverListener.onHover(this, event)) { 5529 return true; 5530 } 5531 5532 return onHoverEvent(event); 5533 } 5534 5535 /** 5536 * Returns true if the view has a child to which it has recently sent 5537 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 5538 * it does not have a hovered child, then it must be the innermost hovered view. 5539 * @hide 5540 */ 5541 protected boolean hasHoveredChild() { 5542 return false; 5543 } 5544 5545 /** 5546 * Dispatch a generic motion event to the view under the first pointer. 5547 * <p> 5548 * Do not call this method directly. 5549 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 5550 * </p> 5551 * 5552 * @param event The motion event to be dispatched. 5553 * @return True if the event was handled by the view, false otherwise. 5554 */ 5555 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 5556 return false; 5557 } 5558 5559 /** 5560 * Dispatch a generic motion event to the currently focused view. 5561 * <p> 5562 * Do not call this method directly. 5563 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 5564 * </p> 5565 * 5566 * @param event The motion event to be dispatched. 5567 * @return True if the event was handled by the view, false otherwise. 5568 */ 5569 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 5570 return false; 5571 } 5572 5573 /** 5574 * Dispatch a pointer event. 5575 * <p> 5576 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 5577 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 5578 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 5579 * and should not be expected to handle other pointing device features. 5580 * </p> 5581 * 5582 * @param event The motion event to be dispatched. 5583 * @return True if the event was handled by the view, false otherwise. 5584 * @hide 5585 */ 5586 public final boolean dispatchPointerEvent(MotionEvent event) { 5587 if (event.isTouchEvent()) { 5588 return dispatchTouchEvent(event); 5589 } else { 5590 return dispatchGenericMotionEvent(event); 5591 } 5592 } 5593 5594 /** 5595 * Called when the window containing this view gains or loses window focus. 5596 * ViewGroups should override to route to their children. 5597 * 5598 * @param hasFocus True if the window containing this view now has focus, 5599 * false otherwise. 5600 */ 5601 public void dispatchWindowFocusChanged(boolean hasFocus) { 5602 onWindowFocusChanged(hasFocus); 5603 } 5604 5605 /** 5606 * Called when the window containing this view gains or loses focus. Note 5607 * that this is separate from view focus: to receive key events, both 5608 * your view and its window must have focus. If a window is displayed 5609 * on top of yours that takes input focus, then your own window will lose 5610 * focus but the view focus will remain unchanged. 5611 * 5612 * @param hasWindowFocus True if the window containing this view now has 5613 * focus, false otherwise. 5614 */ 5615 public void onWindowFocusChanged(boolean hasWindowFocus) { 5616 InputMethodManager imm = InputMethodManager.peekInstance(); 5617 if (!hasWindowFocus) { 5618 if (isPressed()) { 5619 setPressed(false); 5620 } 5621 if (imm != null && (mPrivateFlags & FOCUSED) != 0) { 5622 imm.focusOut(this); 5623 } 5624 removeLongPressCallback(); 5625 removeTapCallback(); 5626 onFocusLost(); 5627 } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) { 5628 imm.focusIn(this); 5629 } 5630 refreshDrawableState(); 5631 } 5632 5633 /** 5634 * Returns true if this view is in a window that currently has window focus. 5635 * Note that this is not the same as the view itself having focus. 5636 * 5637 * @return True if this view is in a window that currently has window focus. 5638 */ 5639 public boolean hasWindowFocus() { 5640 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 5641 } 5642 5643 /** 5644 * Dispatch a view visibility change down the view hierarchy. 5645 * ViewGroups should override to route to their children. 5646 * @param changedView The view whose visibility changed. Could be 'this' or 5647 * an ancestor view. 5648 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 5649 * {@link #INVISIBLE} or {@link #GONE}. 5650 */ 5651 protected void dispatchVisibilityChanged(View changedView, int visibility) { 5652 onVisibilityChanged(changedView, visibility); 5653 } 5654 5655 /** 5656 * Called when the visibility of the view or an ancestor of the view is changed. 5657 * @param changedView The view whose visibility changed. Could be 'this' or 5658 * an ancestor view. 5659 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 5660 * {@link #INVISIBLE} or {@link #GONE}. 5661 */ 5662 protected void onVisibilityChanged(View changedView, int visibility) { 5663 if (visibility == VISIBLE) { 5664 if (mAttachInfo != null) { 5665 initialAwakenScrollBars(); 5666 } else { 5667 mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH; 5668 } 5669 } 5670 } 5671 5672 /** 5673 * Dispatch a hint about whether this view is displayed. For instance, when 5674 * a View moves out of the screen, it might receives a display hint indicating 5675 * the view is not displayed. Applications should not <em>rely</em> on this hint 5676 * as there is no guarantee that they will receive one. 5677 * 5678 * @param hint A hint about whether or not this view is displayed: 5679 * {@link #VISIBLE} or {@link #INVISIBLE}. 5680 */ 5681 public void dispatchDisplayHint(int hint) { 5682 onDisplayHint(hint); 5683 } 5684 5685 /** 5686 * Gives this view a hint about whether is displayed or not. For instance, when 5687 * a View moves out of the screen, it might receives a display hint indicating 5688 * the view is not displayed. Applications should not <em>rely</em> on this hint 5689 * as there is no guarantee that they will receive one. 5690 * 5691 * @param hint A hint about whether or not this view is displayed: 5692 * {@link #VISIBLE} or {@link #INVISIBLE}. 5693 */ 5694 protected void onDisplayHint(int hint) { 5695 } 5696 5697 /** 5698 * Dispatch a window visibility change down the view hierarchy. 5699 * ViewGroups should override to route to their children. 5700 * 5701 * @param visibility The new visibility of the window. 5702 * 5703 * @see #onWindowVisibilityChanged(int) 5704 */ 5705 public void dispatchWindowVisibilityChanged(int visibility) { 5706 onWindowVisibilityChanged(visibility); 5707 } 5708 5709 /** 5710 * Called when the window containing has change its visibility 5711 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 5712 * that this tells you whether or not your window is being made visible 5713 * to the window manager; this does <em>not</em> tell you whether or not 5714 * your window is obscured by other windows on the screen, even if it 5715 * is itself visible. 5716 * 5717 * @param visibility The new visibility of the window. 5718 */ 5719 protected void onWindowVisibilityChanged(int visibility) { 5720 if (visibility == VISIBLE) { 5721 initialAwakenScrollBars(); 5722 } 5723 } 5724 5725 /** 5726 * Returns the current visibility of the window this view is attached to 5727 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 5728 * 5729 * @return Returns the current visibility of the view's window. 5730 */ 5731 public int getWindowVisibility() { 5732 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 5733 } 5734 5735 /** 5736 * Retrieve the overall visible display size in which the window this view is 5737 * attached to has been positioned in. This takes into account screen 5738 * decorations above the window, for both cases where the window itself 5739 * is being position inside of them or the window is being placed under 5740 * then and covered insets are used for the window to position its content 5741 * inside. In effect, this tells you the available area where content can 5742 * be placed and remain visible to users. 5743 * 5744 * <p>This function requires an IPC back to the window manager to retrieve 5745 * the requested information, so should not be used in performance critical 5746 * code like drawing. 5747 * 5748 * @param outRect Filled in with the visible display frame. If the view 5749 * is not attached to a window, this is simply the raw display size. 5750 */ 5751 public void getWindowVisibleDisplayFrame(Rect outRect) { 5752 if (mAttachInfo != null) { 5753 try { 5754 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 5755 } catch (RemoteException e) { 5756 return; 5757 } 5758 // XXX This is really broken, and probably all needs to be done 5759 // in the window manager, and we need to know more about whether 5760 // we want the area behind or in front of the IME. 5761 final Rect insets = mAttachInfo.mVisibleInsets; 5762 outRect.left += insets.left; 5763 outRect.top += insets.top; 5764 outRect.right -= insets.right; 5765 outRect.bottom -= insets.bottom; 5766 return; 5767 } 5768 Display d = WindowManagerImpl.getDefault().getDefaultDisplay(); 5769 d.getRectSize(outRect); 5770 } 5771 5772 /** 5773 * Dispatch a notification about a resource configuration change down 5774 * the view hierarchy. 5775 * ViewGroups should override to route to their children. 5776 * 5777 * @param newConfig The new resource configuration. 5778 * 5779 * @see #onConfigurationChanged(android.content.res.Configuration) 5780 */ 5781 public void dispatchConfigurationChanged(Configuration newConfig) { 5782 onConfigurationChanged(newConfig); 5783 } 5784 5785 /** 5786 * Called when the current configuration of the resources being used 5787 * by the application have changed. You can use this to decide when 5788 * to reload resources that can changed based on orientation and other 5789 * configuration characterstics. You only need to use this if you are 5790 * not relying on the normal {@link android.app.Activity} mechanism of 5791 * recreating the activity instance upon a configuration change. 5792 * 5793 * @param newConfig The new resource configuration. 5794 */ 5795 protected void onConfigurationChanged(Configuration newConfig) { 5796 } 5797 5798 /** 5799 * Private function to aggregate all per-view attributes in to the view 5800 * root. 5801 */ 5802 void dispatchCollectViewAttributes(int visibility) { 5803 performCollectViewAttributes(visibility); 5804 } 5805 5806 void performCollectViewAttributes(int visibility) { 5807 if ((visibility & VISIBILITY_MASK) == VISIBLE && mAttachInfo != null) { 5808 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 5809 mAttachInfo.mKeepScreenOn = true; 5810 } 5811 mAttachInfo.mSystemUiVisibility |= mSystemUiVisibility; 5812 if (mOnSystemUiVisibilityChangeListener != null) { 5813 mAttachInfo.mHasSystemUiListeners = true; 5814 } 5815 } 5816 } 5817 5818 void needGlobalAttributesUpdate(boolean force) { 5819 final AttachInfo ai = mAttachInfo; 5820 if (ai != null) { 5821 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 5822 || ai.mHasSystemUiListeners) { 5823 ai.mRecomputeGlobalAttributes = true; 5824 } 5825 } 5826 } 5827 5828 /** 5829 * Returns whether the device is currently in touch mode. Touch mode is entered 5830 * once the user begins interacting with the device by touch, and affects various 5831 * things like whether focus is always visible to the user. 5832 * 5833 * @return Whether the device is in touch mode. 5834 */ 5835 @ViewDebug.ExportedProperty 5836 public boolean isInTouchMode() { 5837 if (mAttachInfo != null) { 5838 return mAttachInfo.mInTouchMode; 5839 } else { 5840 return ViewRootImpl.isInTouchMode(); 5841 } 5842 } 5843 5844 /** 5845 * Returns the context the view is running in, through which it can 5846 * access the current theme, resources, etc. 5847 * 5848 * @return The view's Context. 5849 */ 5850 @ViewDebug.CapturedViewProperty 5851 public final Context getContext() { 5852 return mContext; 5853 } 5854 5855 /** 5856 * Handle a key event before it is processed by any input method 5857 * associated with the view hierarchy. This can be used to intercept 5858 * key events in special situations before the IME consumes them; a 5859 * typical example would be handling the BACK key to update the application's 5860 * UI instead of allowing the IME to see it and close itself. 5861 * 5862 * @param keyCode The value in event.getKeyCode(). 5863 * @param event Description of the key event. 5864 * @return If you handled the event, return true. If you want to allow the 5865 * event to be handled by the next receiver, return false. 5866 */ 5867 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 5868 return false; 5869 } 5870 5871 /** 5872 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 5873 * KeyEvent.Callback.onKeyDown()}: perform press of the view 5874 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 5875 * is released, if the view is enabled and clickable. 5876 * 5877 * @param keyCode A key code that represents the button pressed, from 5878 * {@link android.view.KeyEvent}. 5879 * @param event The KeyEvent object that defines the button action. 5880 */ 5881 public boolean onKeyDown(int keyCode, KeyEvent event) { 5882 boolean result = false; 5883 5884 switch (keyCode) { 5885 case KeyEvent.KEYCODE_DPAD_CENTER: 5886 case KeyEvent.KEYCODE_ENTER: { 5887 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 5888 return true; 5889 } 5890 // Long clickable items don't necessarily have to be clickable 5891 if (((mViewFlags & CLICKABLE) == CLICKABLE || 5892 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 5893 (event.getRepeatCount() == 0)) { 5894 setPressed(true); 5895 checkForLongClick(0); 5896 return true; 5897 } 5898 break; 5899 } 5900 } 5901 return result; 5902 } 5903 5904 /** 5905 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 5906 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 5907 * the event). 5908 */ 5909 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 5910 return false; 5911 } 5912 5913 /** 5914 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 5915 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 5916 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 5917 * {@link KeyEvent#KEYCODE_ENTER} is released. 5918 * 5919 * @param keyCode A key code that represents the button pressed, from 5920 * {@link android.view.KeyEvent}. 5921 * @param event The KeyEvent object that defines the button action. 5922 */ 5923 public boolean onKeyUp(int keyCode, KeyEvent event) { 5924 boolean result = false; 5925 5926 switch (keyCode) { 5927 case KeyEvent.KEYCODE_DPAD_CENTER: 5928 case KeyEvent.KEYCODE_ENTER: { 5929 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 5930 return true; 5931 } 5932 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 5933 setPressed(false); 5934 5935 if (!mHasPerformedLongPress) { 5936 // This is a tap, so remove the longpress check 5937 removeLongPressCallback(); 5938 5939 result = performClick(); 5940 } 5941 } 5942 break; 5943 } 5944 } 5945 return result; 5946 } 5947 5948 /** 5949 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 5950 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 5951 * the event). 5952 * 5953 * @param keyCode A key code that represents the button pressed, from 5954 * {@link android.view.KeyEvent}. 5955 * @param repeatCount The number of times the action was made. 5956 * @param event The KeyEvent object that defines the button action. 5957 */ 5958 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 5959 return false; 5960 } 5961 5962 /** 5963 * Called on the focused view when a key shortcut event is not handled. 5964 * Override this method to implement local key shortcuts for the View. 5965 * Key shortcuts can also be implemented by setting the 5966 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 5967 * 5968 * @param keyCode The value in event.getKeyCode(). 5969 * @param event Description of the key event. 5970 * @return If you handled the event, return true. If you want to allow the 5971 * event to be handled by the next receiver, return false. 5972 */ 5973 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 5974 return false; 5975 } 5976 5977 /** 5978 * Check whether the called view is a text editor, in which case it 5979 * would make sense to automatically display a soft input window for 5980 * it. Subclasses should override this if they implement 5981 * {@link #onCreateInputConnection(EditorInfo)} to return true if 5982 * a call on that method would return a non-null InputConnection, and 5983 * they are really a first-class editor that the user would normally 5984 * start typing on when the go into a window containing your view. 5985 * 5986 * <p>The default implementation always returns false. This does 5987 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 5988 * will not be called or the user can not otherwise perform edits on your 5989 * view; it is just a hint to the system that this is not the primary 5990 * purpose of this view. 5991 * 5992 * @return Returns true if this view is a text editor, else false. 5993 */ 5994 public boolean onCheckIsTextEditor() { 5995 return false; 5996 } 5997 5998 /** 5999 * Create a new InputConnection for an InputMethod to interact 6000 * with the view. The default implementation returns null, since it doesn't 6001 * support input methods. You can override this to implement such support. 6002 * This is only needed for views that take focus and text input. 6003 * 6004 * <p>When implementing this, you probably also want to implement 6005 * {@link #onCheckIsTextEditor()} to indicate you will return a 6006 * non-null InputConnection. 6007 * 6008 * @param outAttrs Fill in with attribute information about the connection. 6009 */ 6010 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 6011 return null; 6012 } 6013 6014 /** 6015 * Called by the {@link android.view.inputmethod.InputMethodManager} 6016 * when a view who is not the current 6017 * input connection target is trying to make a call on the manager. The 6018 * default implementation returns false; you can override this to return 6019 * true for certain views if you are performing InputConnection proxying 6020 * to them. 6021 * @param view The View that is making the InputMethodManager call. 6022 * @return Return true to allow the call, false to reject. 6023 */ 6024 public boolean checkInputConnectionProxy(View view) { 6025 return false; 6026 } 6027 6028 /** 6029 * Show the context menu for this view. It is not safe to hold on to the 6030 * menu after returning from this method. 6031 * 6032 * You should normally not overload this method. Overload 6033 * {@link #onCreateContextMenu(ContextMenu)} or define an 6034 * {@link OnCreateContextMenuListener} to add items to the context menu. 6035 * 6036 * @param menu The context menu to populate 6037 */ 6038 public void createContextMenu(ContextMenu menu) { 6039 ContextMenuInfo menuInfo = getContextMenuInfo(); 6040 6041 // Sets the current menu info so all items added to menu will have 6042 // my extra info set. 6043 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 6044 6045 onCreateContextMenu(menu); 6046 if (mOnCreateContextMenuListener != null) { 6047 mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 6048 } 6049 6050 // Clear the extra information so subsequent items that aren't mine don't 6051 // have my extra info. 6052 ((MenuBuilder)menu).setCurrentMenuInfo(null); 6053 6054 if (mParent != null) { 6055 mParent.createContextMenu(menu); 6056 } 6057 } 6058 6059 /** 6060 * Views should implement this if they have extra information to associate 6061 * with the context menu. The return result is supplied as a parameter to 6062 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 6063 * callback. 6064 * 6065 * @return Extra information about the item for which the context menu 6066 * should be shown. This information will vary across different 6067 * subclasses of View. 6068 */ 6069 protected ContextMenuInfo getContextMenuInfo() { 6070 return null; 6071 } 6072 6073 /** 6074 * Views should implement this if the view itself is going to add items to 6075 * the context menu. 6076 * 6077 * @param menu the context menu to populate 6078 */ 6079 protected void onCreateContextMenu(ContextMenu menu) { 6080 } 6081 6082 /** 6083 * Implement this method to handle trackball motion events. The 6084 * <em>relative</em> movement of the trackball since the last event 6085 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 6086 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 6087 * that a movement of 1 corresponds to the user pressing one DPAD key (so 6088 * they will often be fractional values, representing the more fine-grained 6089 * movement information available from a trackball). 6090 * 6091 * @param event The motion event. 6092 * @return True if the event was handled, false otherwise. 6093 */ 6094 public boolean onTrackballEvent(MotionEvent event) { 6095 return false; 6096 } 6097 6098 /** 6099 * Implement this method to handle generic motion events. 6100 * <p> 6101 * Generic motion events describe joystick movements, mouse hovers, track pad 6102 * touches, scroll wheel movements and other input events. The 6103 * {@link MotionEvent#getSource() source} of the motion event specifies 6104 * the class of input that was received. Implementations of this method 6105 * must examine the bits in the source before processing the event. 6106 * The following code example shows how this is done. 6107 * </p><p> 6108 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 6109 * are delivered to the view under the pointer. All other generic motion events are 6110 * delivered to the focused view. 6111 * </p> 6112 * <code> 6113 * public boolean onGenericMotionEvent(MotionEvent event) { 6114 * if ((event.getSource() & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) { 6115 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 6116 * // process the joystick movement... 6117 * return true; 6118 * } 6119 * } 6120 * if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) { 6121 * switch (event.getAction()) { 6122 * case MotionEvent.ACTION_HOVER_MOVE: 6123 * // process the mouse hover movement... 6124 * return true; 6125 * case MotionEvent.ACTION_SCROLL: 6126 * // process the scroll wheel movement... 6127 * return true; 6128 * } 6129 * } 6130 * return super.onGenericMotionEvent(event); 6131 * } 6132 * </code> 6133 * 6134 * @param event The generic motion event being processed. 6135 * @return True if the event was handled, false otherwise. 6136 */ 6137 public boolean onGenericMotionEvent(MotionEvent event) { 6138 return false; 6139 } 6140 6141 /** 6142 * Implement this method to handle hover events. 6143 * <p> 6144 * This method is called whenever a pointer is hovering into, over, or out of the 6145 * bounds of a view and the view is not currently being touched. 6146 * Hover events are represented as pointer events with action 6147 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 6148 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 6149 * </p> 6150 * <ul> 6151 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 6152 * when the pointer enters the bounds of the view.</li> 6153 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 6154 * when the pointer has already entered the bounds of the view and has moved.</li> 6155 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 6156 * when the pointer has exited the bounds of the view or when the pointer is 6157 * about to go down due to a button click, tap, or similar user action that 6158 * causes the view to be touched.</li> 6159 * </ul> 6160 * <p> 6161 * The view should implement this method to return true to indicate that it is 6162 * handling the hover event, such as by changing its drawable state. 6163 * </p><p> 6164 * The default implementation calls {@link #setHovered} to update the hovered state 6165 * of the view when a hover enter or hover exit event is received, if the view 6166 * is enabled and is clickable. The default implementation also sends hover 6167 * accessibility events. 6168 * </p> 6169 * 6170 * @param event The motion event that describes the hover. 6171 * @return True if the view handled the hover event. 6172 * 6173 * @see #isHovered 6174 * @see #setHovered 6175 * @see #onHoverChanged 6176 */ 6177 public boolean onHoverEvent(MotionEvent event) { 6178 // The root view may receive hover (or touch) events that are outside the bounds of 6179 // the window. This code ensures that we only send accessibility events for 6180 // hovers that are actually within the bounds of the root view. 6181 final int action = event.getAction(); 6182 if (!mSendingHoverAccessibilityEvents) { 6183 if ((action == MotionEvent.ACTION_HOVER_ENTER 6184 || action == MotionEvent.ACTION_HOVER_MOVE) 6185 && !hasHoveredChild() 6186 && pointInView(event.getX(), event.getY())) { 6187 mSendingHoverAccessibilityEvents = true; 6188 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 6189 } 6190 } else { 6191 if (action == MotionEvent.ACTION_HOVER_EXIT 6192 || (action == MotionEvent.ACTION_HOVER_MOVE 6193 && !pointInView(event.getX(), event.getY()))) { 6194 mSendingHoverAccessibilityEvents = false; 6195 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 6196 } 6197 } 6198 6199 if (isHoverable()) { 6200 switch (action) { 6201 case MotionEvent.ACTION_HOVER_ENTER: 6202 setHovered(true); 6203 break; 6204 case MotionEvent.ACTION_HOVER_EXIT: 6205 setHovered(false); 6206 break; 6207 } 6208 6209 // Dispatch the event to onGenericMotionEvent before returning true. 6210 // This is to provide compatibility with existing applications that 6211 // handled HOVER_MOVE events in onGenericMotionEvent and that would 6212 // break because of the new default handling for hoverable views 6213 // in onHoverEvent. 6214 // Note that onGenericMotionEvent will be called by default when 6215 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 6216 dispatchGenericMotionEventInternal(event); 6217 return true; 6218 } 6219 return false; 6220 } 6221 6222 /** 6223 * Returns true if the view should handle {@link #onHoverEvent} 6224 * by calling {@link #setHovered} to change its hovered state. 6225 * 6226 * @return True if the view is hoverable. 6227 */ 6228 private boolean isHoverable() { 6229 final int viewFlags = mViewFlags; 6230 //noinspection SimplifiableIfStatement 6231 if ((viewFlags & ENABLED_MASK) == DISABLED) { 6232 return false; 6233 } 6234 6235 return (viewFlags & CLICKABLE) == CLICKABLE 6236 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 6237 } 6238 6239 /** 6240 * Returns true if the view is currently hovered. 6241 * 6242 * @return True if the view is currently hovered. 6243 * 6244 * @see #setHovered 6245 * @see #onHoverChanged 6246 */ 6247 @ViewDebug.ExportedProperty 6248 public boolean isHovered() { 6249 return (mPrivateFlags & HOVERED) != 0; 6250 } 6251 6252 /** 6253 * Sets whether the view is currently hovered. 6254 * <p> 6255 * Calling this method also changes the drawable state of the view. This 6256 * enables the view to react to hover by using different drawable resources 6257 * to change its appearance. 6258 * </p><p> 6259 * The {@link #onHoverChanged} method is called when the hovered state changes. 6260 * </p> 6261 * 6262 * @param hovered True if the view is hovered. 6263 * 6264 * @see #isHovered 6265 * @see #onHoverChanged 6266 */ 6267 public void setHovered(boolean hovered) { 6268 if (hovered) { 6269 if ((mPrivateFlags & HOVERED) == 0) { 6270 mPrivateFlags |= HOVERED; 6271 refreshDrawableState(); 6272 onHoverChanged(true); 6273 } 6274 } else { 6275 if ((mPrivateFlags & HOVERED) != 0) { 6276 mPrivateFlags &= ~HOVERED; 6277 refreshDrawableState(); 6278 onHoverChanged(false); 6279 } 6280 } 6281 } 6282 6283 /** 6284 * Implement this method to handle hover state changes. 6285 * <p> 6286 * This method is called whenever the hover state changes as a result of a 6287 * call to {@link #setHovered}. 6288 * </p> 6289 * 6290 * @param hovered The current hover state, as returned by {@link #isHovered}. 6291 * 6292 * @see #isHovered 6293 * @see #setHovered 6294 */ 6295 public void onHoverChanged(boolean hovered) { 6296 } 6297 6298 /** 6299 * Implement this method to handle touch screen motion events. 6300 * 6301 * @param event The motion event. 6302 * @return True if the event was handled, false otherwise. 6303 */ 6304 public boolean onTouchEvent(MotionEvent event) { 6305 final int viewFlags = mViewFlags; 6306 6307 if ((viewFlags & ENABLED_MASK) == DISABLED) { 6308 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) { 6309 mPrivateFlags &= ~PRESSED; 6310 refreshDrawableState(); 6311 } 6312 // A disabled view that is clickable still consumes the touch 6313 // events, it just doesn't respond to them. 6314 return (((viewFlags & CLICKABLE) == CLICKABLE || 6315 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 6316 } 6317 6318 if (mTouchDelegate != null) { 6319 if (mTouchDelegate.onTouchEvent(event)) { 6320 return true; 6321 } 6322 } 6323 6324 if (((viewFlags & CLICKABLE) == CLICKABLE || 6325 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 6326 switch (event.getAction()) { 6327 case MotionEvent.ACTION_UP: 6328 boolean prepressed = (mPrivateFlags & PREPRESSED) != 0; 6329 if ((mPrivateFlags & PRESSED) != 0 || prepressed) { 6330 // take focus if we don't have it already and we should in 6331 // touch mode. 6332 boolean focusTaken = false; 6333 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 6334 focusTaken = requestFocus(); 6335 } 6336 6337 if (prepressed) { 6338 // The button is being released before we actually 6339 // showed it as pressed. Make it show the pressed 6340 // state now (before scheduling the click) to ensure 6341 // the user sees it. 6342 mPrivateFlags |= PRESSED; 6343 refreshDrawableState(); 6344 } 6345 6346 if (!mHasPerformedLongPress) { 6347 // This is a tap, so remove the longpress check 6348 removeLongPressCallback(); 6349 6350 // Only perform take click actions if we were in the pressed state 6351 if (!focusTaken) { 6352 // Use a Runnable and post this rather than calling 6353 // performClick directly. This lets other visual state 6354 // of the view update before click actions start. 6355 if (mPerformClick == null) { 6356 mPerformClick = new PerformClick(); 6357 } 6358 if (!post(mPerformClick)) { 6359 performClick(); 6360 } 6361 } 6362 } 6363 6364 if (mUnsetPressedState == null) { 6365 mUnsetPressedState = new UnsetPressedState(); 6366 } 6367 6368 if (prepressed) { 6369 postDelayed(mUnsetPressedState, 6370 ViewConfiguration.getPressedStateDuration()); 6371 } else if (!post(mUnsetPressedState)) { 6372 // If the post failed, unpress right now 6373 mUnsetPressedState.run(); 6374 } 6375 removeTapCallback(); 6376 } 6377 break; 6378 6379 case MotionEvent.ACTION_DOWN: 6380 mHasPerformedLongPress = false; 6381 6382 if (performButtonActionOnTouchDown(event)) { 6383 break; 6384 } 6385 6386 // Walk up the hierarchy to determine if we're inside a scrolling container. 6387 boolean isInScrollingContainer = isInScrollingContainer(); 6388 6389 // For views inside a scrolling container, delay the pressed feedback for 6390 // a short period in case this is a scroll. 6391 if (isInScrollingContainer) { 6392 mPrivateFlags |= PREPRESSED; 6393 if (mPendingCheckForTap == null) { 6394 mPendingCheckForTap = new CheckForTap(); 6395 } 6396 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 6397 } else { 6398 // Not inside a scrolling container, so show the feedback right away 6399 mPrivateFlags |= PRESSED; 6400 refreshDrawableState(); 6401 checkForLongClick(0); 6402 } 6403 break; 6404 6405 case MotionEvent.ACTION_CANCEL: 6406 mPrivateFlags &= ~PRESSED; 6407 refreshDrawableState(); 6408 removeTapCallback(); 6409 break; 6410 6411 case MotionEvent.ACTION_MOVE: 6412 final int x = (int) event.getX(); 6413 final int y = (int) event.getY(); 6414 6415 // Be lenient about moving outside of buttons 6416 if (!pointInView(x, y, mTouchSlop)) { 6417 // Outside button 6418 removeTapCallback(); 6419 if ((mPrivateFlags & PRESSED) != 0) { 6420 // Remove any future long press/tap checks 6421 removeLongPressCallback(); 6422 6423 // Need to switch from pressed to not pressed 6424 mPrivateFlags &= ~PRESSED; 6425 refreshDrawableState(); 6426 } 6427 } 6428 break; 6429 } 6430 return true; 6431 } 6432 6433 return false; 6434 } 6435 6436 /** 6437 * @hide 6438 */ 6439 public boolean isInScrollingContainer() { 6440 ViewParent p = getParent(); 6441 while (p != null && p instanceof ViewGroup) { 6442 if (((ViewGroup) p).shouldDelayChildPressedState()) { 6443 return true; 6444 } 6445 p = p.getParent(); 6446 } 6447 return false; 6448 } 6449 6450 /** 6451 * Remove the longpress detection timer. 6452 */ 6453 private void removeLongPressCallback() { 6454 if (mPendingCheckForLongPress != null) { 6455 removeCallbacks(mPendingCheckForLongPress); 6456 } 6457 } 6458 6459 /** 6460 * Remove the pending click action 6461 */ 6462 private void removePerformClickCallback() { 6463 if (mPerformClick != null) { 6464 removeCallbacks(mPerformClick); 6465 } 6466 } 6467 6468 /** 6469 * Remove the prepress detection timer. 6470 */ 6471 private void removeUnsetPressCallback() { 6472 if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) { 6473 setPressed(false); 6474 removeCallbacks(mUnsetPressedState); 6475 } 6476 } 6477 6478 /** 6479 * Remove the tap detection timer. 6480 */ 6481 private void removeTapCallback() { 6482 if (mPendingCheckForTap != null) { 6483 mPrivateFlags &= ~PREPRESSED; 6484 removeCallbacks(mPendingCheckForTap); 6485 } 6486 } 6487 6488 /** 6489 * Cancels a pending long press. Your subclass can use this if you 6490 * want the context menu to come up if the user presses and holds 6491 * at the same place, but you don't want it to come up if they press 6492 * and then move around enough to cause scrolling. 6493 */ 6494 public void cancelLongPress() { 6495 removeLongPressCallback(); 6496 6497 /* 6498 * The prepressed state handled by the tap callback is a display 6499 * construct, but the tap callback will post a long press callback 6500 * less its own timeout. Remove it here. 6501 */ 6502 removeTapCallback(); 6503 } 6504 6505 /** 6506 * Remove the pending callback for sending a 6507 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 6508 */ 6509 private void removeSendViewScrolledAccessibilityEventCallback() { 6510 if (mSendViewScrolledAccessibilityEvent != null) { 6511 removeCallbacks(mSendViewScrolledAccessibilityEvent); 6512 } 6513 } 6514 6515 /** 6516 * Sets the TouchDelegate for this View. 6517 */ 6518 public void setTouchDelegate(TouchDelegate delegate) { 6519 mTouchDelegate = delegate; 6520 } 6521 6522 /** 6523 * Gets the TouchDelegate for this View. 6524 */ 6525 public TouchDelegate getTouchDelegate() { 6526 return mTouchDelegate; 6527 } 6528 6529 /** 6530 * Set flags controlling behavior of this view. 6531 * 6532 * @param flags Constant indicating the value which should be set 6533 * @param mask Constant indicating the bit range that should be changed 6534 */ 6535 void setFlags(int flags, int mask) { 6536 int old = mViewFlags; 6537 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 6538 6539 int changed = mViewFlags ^ old; 6540 if (changed == 0) { 6541 return; 6542 } 6543 int privateFlags = mPrivateFlags; 6544 6545 /* Check if the FOCUSABLE bit has changed */ 6546 if (((changed & FOCUSABLE_MASK) != 0) && 6547 ((privateFlags & HAS_BOUNDS) !=0)) { 6548 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 6549 && ((privateFlags & FOCUSED) != 0)) { 6550 /* Give up focus if we are no longer focusable */ 6551 clearFocus(); 6552 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 6553 && ((privateFlags & FOCUSED) == 0)) { 6554 /* 6555 * Tell the view system that we are now available to take focus 6556 * if no one else already has it. 6557 */ 6558 if (mParent != null) mParent.focusableViewAvailable(this); 6559 } 6560 } 6561 6562 if ((flags & VISIBILITY_MASK) == VISIBLE) { 6563 if ((changed & VISIBILITY_MASK) != 0) { 6564 /* 6565 * If this view is becoming visible, invalidate it in case it changed while 6566 * it was not visible. Marking it drawn ensures that the invalidation will 6567 * go through. 6568 */ 6569 mPrivateFlags |= DRAWN; 6570 invalidate(true); 6571 6572 needGlobalAttributesUpdate(true); 6573 6574 // a view becoming visible is worth notifying the parent 6575 // about in case nothing has focus. even if this specific view 6576 // isn't focusable, it may contain something that is, so let 6577 // the root view try to give this focus if nothing else does. 6578 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 6579 mParent.focusableViewAvailable(this); 6580 } 6581 } 6582 } 6583 6584 /* Check if the GONE bit has changed */ 6585 if ((changed & GONE) != 0) { 6586 needGlobalAttributesUpdate(false); 6587 requestLayout(); 6588 6589 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 6590 if (hasFocus()) clearFocus(); 6591 destroyDrawingCache(); 6592 if (mParent instanceof View) { 6593 // GONE views noop invalidation, so invalidate the parent 6594 ((View) mParent).invalidate(true); 6595 } 6596 // Mark the view drawn to ensure that it gets invalidated properly the next 6597 // time it is visible and gets invalidated 6598 mPrivateFlags |= DRAWN; 6599 } 6600 if (mAttachInfo != null) { 6601 mAttachInfo.mViewVisibilityChanged = true; 6602 } 6603 } 6604 6605 /* Check if the VISIBLE bit has changed */ 6606 if ((changed & INVISIBLE) != 0) { 6607 needGlobalAttributesUpdate(false); 6608 /* 6609 * If this view is becoming invisible, set the DRAWN flag so that 6610 * the next invalidate() will not be skipped. 6611 */ 6612 mPrivateFlags |= DRAWN; 6613 6614 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) { 6615 // root view becoming invisible shouldn't clear focus 6616 if (getRootView() != this) { 6617 clearFocus(); 6618 } 6619 } 6620 if (mAttachInfo != null) { 6621 mAttachInfo.mViewVisibilityChanged = true; 6622 } 6623 } 6624 6625 if ((changed & VISIBILITY_MASK) != 0) { 6626 if (mParent instanceof ViewGroup) { 6627 ((ViewGroup) mParent).onChildVisibilityChanged(this, (flags & VISIBILITY_MASK)); 6628 ((View) mParent).invalidate(true); 6629 } else if (mParent != null) { 6630 mParent.invalidateChild(this, null); 6631 } 6632 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK)); 6633 } 6634 6635 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 6636 destroyDrawingCache(); 6637 } 6638 6639 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 6640 destroyDrawingCache(); 6641 mPrivateFlags &= ~DRAWING_CACHE_VALID; 6642 invalidateParentCaches(); 6643 } 6644 6645 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 6646 destroyDrawingCache(); 6647 mPrivateFlags &= ~DRAWING_CACHE_VALID; 6648 } 6649 6650 if ((changed & DRAW_MASK) != 0) { 6651 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 6652 if (mBGDrawable != null) { 6653 mPrivateFlags &= ~SKIP_DRAW; 6654 mPrivateFlags |= ONLY_DRAWS_BACKGROUND; 6655 } else { 6656 mPrivateFlags |= SKIP_DRAW; 6657 } 6658 } else { 6659 mPrivateFlags &= ~SKIP_DRAW; 6660 } 6661 requestLayout(); 6662 invalidate(true); 6663 } 6664 6665 if ((changed & KEEP_SCREEN_ON) != 0) { 6666 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 6667 mParent.recomputeViewAttributes(this); 6668 } 6669 } 6670 6671 if ((changed & LAYOUT_DIRECTION_MASK) != 0) { 6672 requestLayout(); 6673 } 6674 } 6675 6676 /** 6677 * Change the view's z order in the tree, so it's on top of other sibling 6678 * views 6679 */ 6680 public void bringToFront() { 6681 if (mParent != null) { 6682 mParent.bringChildToFront(this); 6683 } 6684 } 6685 6686 /** 6687 * This is called in response to an internal scroll in this view (i.e., the 6688 * view scrolled its own contents). This is typically as a result of 6689 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 6690 * called. 6691 * 6692 * @param l Current horizontal scroll origin. 6693 * @param t Current vertical scroll origin. 6694 * @param oldl Previous horizontal scroll origin. 6695 * @param oldt Previous vertical scroll origin. 6696 */ 6697 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 6698 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 6699 postSendViewScrolledAccessibilityEventCallback(); 6700 } 6701 6702 mBackgroundSizeChanged = true; 6703 6704 final AttachInfo ai = mAttachInfo; 6705 if (ai != null) { 6706 ai.mViewScrollChanged = true; 6707 } 6708 } 6709 6710 /** 6711 * Interface definition for a callback to be invoked when the layout bounds of a view 6712 * changes due to layout processing. 6713 */ 6714 public interface OnLayoutChangeListener { 6715 /** 6716 * Called when the focus state of a view has changed. 6717 * 6718 * @param v The view whose state has changed. 6719 * @param left The new value of the view's left property. 6720 * @param top The new value of the view's top property. 6721 * @param right The new value of the view's right property. 6722 * @param bottom The new value of the view's bottom property. 6723 * @param oldLeft The previous value of the view's left property. 6724 * @param oldTop The previous value of the view's top property. 6725 * @param oldRight The previous value of the view's right property. 6726 * @param oldBottom The previous value of the view's bottom property. 6727 */ 6728 void onLayoutChange(View v, int left, int top, int right, int bottom, 6729 int oldLeft, int oldTop, int oldRight, int oldBottom); 6730 } 6731 6732 /** 6733 * This is called during layout when the size of this view has changed. If 6734 * you were just added to the view hierarchy, you're called with the old 6735 * values of 0. 6736 * 6737 * @param w Current width of this view. 6738 * @param h Current height of this view. 6739 * @param oldw Old width of this view. 6740 * @param oldh Old height of this view. 6741 */ 6742 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 6743 } 6744 6745 /** 6746 * Called by draw to draw the child views. This may be overridden 6747 * by derived classes to gain control just before its children are drawn 6748 * (but after its own view has been drawn). 6749 * @param canvas the canvas on which to draw the view 6750 */ 6751 protected void dispatchDraw(Canvas canvas) { 6752 } 6753 6754 /** 6755 * Gets the parent of this view. Note that the parent is a 6756 * ViewParent and not necessarily a View. 6757 * 6758 * @return Parent of this view. 6759 */ 6760 public final ViewParent getParent() { 6761 return mParent; 6762 } 6763 6764 /** 6765 * Set the horizontal scrolled position of your view. This will cause a call to 6766 * {@link #onScrollChanged(int, int, int, int)} and the view will be 6767 * invalidated. 6768 * @param value the x position to scroll to 6769 */ 6770 public void setScrollX(int value) { 6771 scrollTo(value, mScrollY); 6772 } 6773 6774 /** 6775 * Set the vertical scrolled position of your view. This will cause a call to 6776 * {@link #onScrollChanged(int, int, int, int)} and the view will be 6777 * invalidated. 6778 * @param value the y position to scroll to 6779 */ 6780 public void setScrollY(int value) { 6781 scrollTo(mScrollX, value); 6782 } 6783 6784 /** 6785 * Return the scrolled left position of this view. This is the left edge of 6786 * the displayed part of your view. You do not need to draw any pixels 6787 * farther left, since those are outside of the frame of your view on 6788 * screen. 6789 * 6790 * @return The left edge of the displayed part of your view, in pixels. 6791 */ 6792 public final int getScrollX() { 6793 return mScrollX; 6794 } 6795 6796 /** 6797 * Return the scrolled top position of this view. This is the top edge of 6798 * the displayed part of your view. You do not need to draw any pixels above 6799 * it, since those are outside of the frame of your view on screen. 6800 * 6801 * @return The top edge of the displayed part of your view, in pixels. 6802 */ 6803 public final int getScrollY() { 6804 return mScrollY; 6805 } 6806 6807 /** 6808 * Return the width of the your view. 6809 * 6810 * @return The width of your view, in pixels. 6811 */ 6812 @ViewDebug.ExportedProperty(category = "layout") 6813 public final int getWidth() { 6814 return mRight - mLeft; 6815 } 6816 6817 /** 6818 * Return the height of your view. 6819 * 6820 * @return The height of your view, in pixels. 6821 */ 6822 @ViewDebug.ExportedProperty(category = "layout") 6823 public final int getHeight() { 6824 return mBottom - mTop; 6825 } 6826 6827 /** 6828 * Return the visible drawing bounds of your view. Fills in the output 6829 * rectangle with the values from getScrollX(), getScrollY(), 6830 * getWidth(), and getHeight(). 6831 * 6832 * @param outRect The (scrolled) drawing bounds of the view. 6833 */ 6834 public void getDrawingRect(Rect outRect) { 6835 outRect.left = mScrollX; 6836 outRect.top = mScrollY; 6837 outRect.right = mScrollX + (mRight - mLeft); 6838 outRect.bottom = mScrollY + (mBottom - mTop); 6839 } 6840 6841 /** 6842 * Like {@link #getMeasuredWidthAndState()}, but only returns the 6843 * raw width component (that is the result is masked by 6844 * {@link #MEASURED_SIZE_MASK}). 6845 * 6846 * @return The raw measured width of this view. 6847 */ 6848 public final int getMeasuredWidth() { 6849 return mMeasuredWidth & MEASURED_SIZE_MASK; 6850 } 6851 6852 /** 6853 * Return the full width measurement information for this view as computed 6854 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 6855 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 6856 * This should be used during measurement and layout calculations only. Use 6857 * {@link #getWidth()} to see how wide a view is after layout. 6858 * 6859 * @return The measured width of this view as a bit mask. 6860 */ 6861 public final int getMeasuredWidthAndState() { 6862 return mMeasuredWidth; 6863 } 6864 6865 /** 6866 * Like {@link #getMeasuredHeightAndState()}, but only returns the 6867 * raw width component (that is the result is masked by 6868 * {@link #MEASURED_SIZE_MASK}). 6869 * 6870 * @return The raw measured height of this view. 6871 */ 6872 public final int getMeasuredHeight() { 6873 return mMeasuredHeight & MEASURED_SIZE_MASK; 6874 } 6875 6876 /** 6877 * Return the full height measurement information for this view as computed 6878 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 6879 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 6880 * This should be used during measurement and layout calculations only. Use 6881 * {@link #getHeight()} to see how wide a view is after layout. 6882 * 6883 * @return The measured width of this view as a bit mask. 6884 */ 6885 public final int getMeasuredHeightAndState() { 6886 return mMeasuredHeight; 6887 } 6888 6889 /** 6890 * Return only the state bits of {@link #getMeasuredWidthAndState()} 6891 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 6892 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 6893 * and the height component is at the shifted bits 6894 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 6895 */ 6896 public final int getMeasuredState() { 6897 return (mMeasuredWidth&MEASURED_STATE_MASK) 6898 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 6899 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 6900 } 6901 6902 /** 6903 * The transform matrix of this view, which is calculated based on the current 6904 * roation, scale, and pivot properties. 6905 * 6906 * @see #getRotation() 6907 * @see #getScaleX() 6908 * @see #getScaleY() 6909 * @see #getPivotX() 6910 * @see #getPivotY() 6911 * @return The current transform matrix for the view 6912 */ 6913 public Matrix getMatrix() { 6914 updateMatrix(); 6915 return mMatrix; 6916 } 6917 6918 /** 6919 * Utility function to determine if the value is far enough away from zero to be 6920 * considered non-zero. 6921 * @param value A floating point value to check for zero-ness 6922 * @return whether the passed-in value is far enough away from zero to be considered non-zero 6923 */ 6924 private static boolean nonzero(float value) { 6925 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON); 6926 } 6927 6928 /** 6929 * Returns true if the transform matrix is the identity matrix. 6930 * Recomputes the matrix if necessary. 6931 * 6932 * @return True if the transform matrix is the identity matrix, false otherwise. 6933 */ 6934 final boolean hasIdentityMatrix() { 6935 updateMatrix(); 6936 return mMatrixIsIdentity; 6937 } 6938 6939 /** 6940 * Recomputes the transform matrix if necessary. 6941 */ 6942 private void updateMatrix() { 6943 if (mMatrixDirty) { 6944 // transform-related properties have changed since the last time someone 6945 // asked for the matrix; recalculate it with the current values 6946 6947 // Figure out if we need to update the pivot point 6948 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 6949 if ((mRight - mLeft) != mPrevWidth || (mBottom - mTop) != mPrevHeight) { 6950 mPrevWidth = mRight - mLeft; 6951 mPrevHeight = mBottom - mTop; 6952 mPivotX = mPrevWidth / 2f; 6953 mPivotY = mPrevHeight / 2f; 6954 } 6955 } 6956 mMatrix.reset(); 6957 if (!nonzero(mRotationX) && !nonzero(mRotationY)) { 6958 mMatrix.setTranslate(mTranslationX, mTranslationY); 6959 mMatrix.preRotate(mRotation, mPivotX, mPivotY); 6960 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY); 6961 } else { 6962 if (mCamera == null) { 6963 mCamera = new Camera(); 6964 matrix3D = new Matrix(); 6965 } 6966 mCamera.save(); 6967 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY); 6968 mCamera.rotate(mRotationX, mRotationY, -mRotation); 6969 mCamera.getMatrix(matrix3D); 6970 matrix3D.preTranslate(-mPivotX, -mPivotY); 6971 matrix3D.postTranslate(mPivotX + mTranslationX, mPivotY + mTranslationY); 6972 mMatrix.postConcat(matrix3D); 6973 mCamera.restore(); 6974 } 6975 mMatrixDirty = false; 6976 mMatrixIsIdentity = mMatrix.isIdentity(); 6977 mInverseMatrixDirty = true; 6978 } 6979 } 6980 6981 /** 6982 * Utility method to retrieve the inverse of the current mMatrix property. 6983 * We cache the matrix to avoid recalculating it when transform properties 6984 * have not changed. 6985 * 6986 * @return The inverse of the current matrix of this view. 6987 */ 6988 final Matrix getInverseMatrix() { 6989 updateMatrix(); 6990 if (mInverseMatrixDirty) { 6991 if (mInverseMatrix == null) { 6992 mInverseMatrix = new Matrix(); 6993 } 6994 mMatrix.invert(mInverseMatrix); 6995 mInverseMatrixDirty = false; 6996 } 6997 return mInverseMatrix; 6998 } 6999 7000 /** 7001 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 7002 * views are drawn) from the camera to this view. The camera's distance 7003 * affects 3D transformations, for instance rotations around the X and Y 7004 * axis. If the rotationX or rotationY properties are changed and this view is 7005 * large (more than half the size of the screen), it is recommended to always 7006 * use a camera distance that's greater than the height (X axis rotation) or 7007 * the width (Y axis rotation) of this view.</p> 7008 * 7009 * <p>The distance of the camera from the view plane can have an affect on the 7010 * perspective distortion of the view when it is rotated around the x or y axis. 7011 * For example, a large distance will result in a large viewing angle, and there 7012 * will not be much perspective distortion of the view as it rotates. A short 7013 * distance may cause much more perspective distortion upon rotation, and can 7014 * also result in some drawing artifacts if the rotated view ends up partially 7015 * behind the camera (which is why the recommendation is to use a distance at 7016 * least as far as the size of the view, if the view is to be rotated.)</p> 7017 * 7018 * <p>The distance is expressed in "depth pixels." The default distance depends 7019 * on the screen density. For instance, on a medium density display, the 7020 * default distance is 1280. On a high density display, the default distance 7021 * is 1920.</p> 7022 * 7023 * <p>If you want to specify a distance that leads to visually consistent 7024 * results across various densities, use the following formula:</p> 7025 * <pre> 7026 * float scale = context.getResources().getDisplayMetrics().density; 7027 * view.setCameraDistance(distance * scale); 7028 * </pre> 7029 * 7030 * <p>The density scale factor of a high density display is 1.5, 7031 * and 1920 = 1280 * 1.5.</p> 7032 * 7033 * @param distance The distance in "depth pixels", if negative the opposite 7034 * value is used 7035 * 7036 * @see #setRotationX(float) 7037 * @see #setRotationY(float) 7038 */ 7039 public void setCameraDistance(float distance) { 7040 invalidateParentCaches(); 7041 invalidate(false); 7042 7043 final float dpi = mResources.getDisplayMetrics().densityDpi; 7044 if (mCamera == null) { 7045 mCamera = new Camera(); 7046 matrix3D = new Matrix(); 7047 } 7048 7049 mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi); 7050 mMatrixDirty = true; 7051 7052 invalidate(false); 7053 } 7054 7055 /** 7056 * The degrees that the view is rotated around the pivot point. 7057 * 7058 * @see #setRotation(float) 7059 * @see #getPivotX() 7060 * @see #getPivotY() 7061 * 7062 * @return The degrees of rotation. 7063 */ 7064 public float getRotation() { 7065 return mRotation; 7066 } 7067 7068 /** 7069 * Sets the degrees that the view is rotated around the pivot point. Increasing values 7070 * result in clockwise rotation. 7071 * 7072 * @param rotation The degrees of rotation. 7073 * 7074 * @see #getRotation() 7075 * @see #getPivotX() 7076 * @see #getPivotY() 7077 * @see #setRotationX(float) 7078 * @see #setRotationY(float) 7079 * 7080 * @attr ref android.R.styleable#View_rotation 7081 */ 7082 public void setRotation(float rotation) { 7083 if (mRotation != rotation) { 7084 invalidateParentCaches(); 7085 // Double-invalidation is necessary to capture view's old and new areas 7086 invalidate(false); 7087 mRotation = rotation; 7088 mMatrixDirty = true; 7089 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7090 invalidate(false); 7091 } 7092 } 7093 7094 /** 7095 * The degrees that the view is rotated around the vertical axis through the pivot point. 7096 * 7097 * @see #getPivotX() 7098 * @see #getPivotY() 7099 * @see #setRotationY(float) 7100 * 7101 * @return The degrees of Y rotation. 7102 */ 7103 public float getRotationY() { 7104 return mRotationY; 7105 } 7106 7107 /** 7108 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 7109 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 7110 * down the y axis. 7111 * 7112 * When rotating large views, it is recommended to adjust the camera distance 7113 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 7114 * 7115 * @param rotationY The degrees of Y rotation. 7116 * 7117 * @see #getRotationY() 7118 * @see #getPivotX() 7119 * @see #getPivotY() 7120 * @see #setRotation(float) 7121 * @see #setRotationX(float) 7122 * @see #setCameraDistance(float) 7123 * 7124 * @attr ref android.R.styleable#View_rotationY 7125 */ 7126 public void setRotationY(float rotationY) { 7127 if (mRotationY != rotationY) { 7128 invalidateParentCaches(); 7129 // Double-invalidation is necessary to capture view's old and new areas 7130 invalidate(false); 7131 mRotationY = rotationY; 7132 mMatrixDirty = true; 7133 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7134 invalidate(false); 7135 } 7136 } 7137 7138 /** 7139 * The degrees that the view is rotated around the horizontal axis through the pivot point. 7140 * 7141 * @see #getPivotX() 7142 * @see #getPivotY() 7143 * @see #setRotationX(float) 7144 * 7145 * @return The degrees of X rotation. 7146 */ 7147 public float getRotationX() { 7148 return mRotationX; 7149 } 7150 7151 /** 7152 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 7153 * Increasing values result in clockwise rotation from the viewpoint of looking down the 7154 * x axis. 7155 * 7156 * When rotating large views, it is recommended to adjust the camera distance 7157 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 7158 * 7159 * @param rotationX The degrees of X rotation. 7160 * 7161 * @see #getRotationX() 7162 * @see #getPivotX() 7163 * @see #getPivotY() 7164 * @see #setRotation(float) 7165 * @see #setRotationY(float) 7166 * @see #setCameraDistance(float) 7167 * 7168 * @attr ref android.R.styleable#View_rotationX 7169 */ 7170 public void setRotationX(float rotationX) { 7171 if (mRotationX != rotationX) { 7172 invalidateParentCaches(); 7173 // Double-invalidation is necessary to capture view's old and new areas 7174 invalidate(false); 7175 mRotationX = rotationX; 7176 mMatrixDirty = true; 7177 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7178 invalidate(false); 7179 } 7180 } 7181 7182 /** 7183 * The amount that the view is scaled in x around the pivot point, as a proportion of 7184 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 7185 * 7186 * <p>By default, this is 1.0f. 7187 * 7188 * @see #getPivotX() 7189 * @see #getPivotY() 7190 * @return The scaling factor. 7191 */ 7192 public float getScaleX() { 7193 return mScaleX; 7194 } 7195 7196 /** 7197 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 7198 * the view's unscaled width. A value of 1 means that no scaling is applied. 7199 * 7200 * @param scaleX The scaling factor. 7201 * @see #getPivotX() 7202 * @see #getPivotY() 7203 * 7204 * @attr ref android.R.styleable#View_scaleX 7205 */ 7206 public void setScaleX(float scaleX) { 7207 if (mScaleX != scaleX) { 7208 invalidateParentCaches(); 7209 // Double-invalidation is necessary to capture view's old and new areas 7210 invalidate(false); 7211 mScaleX = scaleX; 7212 mMatrixDirty = true; 7213 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7214 invalidate(false); 7215 } 7216 } 7217 7218 /** 7219 * The amount that the view is scaled in y around the pivot point, as a proportion of 7220 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 7221 * 7222 * <p>By default, this is 1.0f. 7223 * 7224 * @see #getPivotX() 7225 * @see #getPivotY() 7226 * @return The scaling factor. 7227 */ 7228 public float getScaleY() { 7229 return mScaleY; 7230 } 7231 7232 /** 7233 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 7234 * the view's unscaled width. A value of 1 means that no scaling is applied. 7235 * 7236 * @param scaleY The scaling factor. 7237 * @see #getPivotX() 7238 * @see #getPivotY() 7239 * 7240 * @attr ref android.R.styleable#View_scaleY 7241 */ 7242 public void setScaleY(float scaleY) { 7243 if (mScaleY != scaleY) { 7244 invalidateParentCaches(); 7245 // Double-invalidation is necessary to capture view's old and new areas 7246 invalidate(false); 7247 mScaleY = scaleY; 7248 mMatrixDirty = true; 7249 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7250 invalidate(false); 7251 } 7252 } 7253 7254 /** 7255 * The x location of the point around which the view is {@link #setRotation(float) rotated} 7256 * and {@link #setScaleX(float) scaled}. 7257 * 7258 * @see #getRotation() 7259 * @see #getScaleX() 7260 * @see #getScaleY() 7261 * @see #getPivotY() 7262 * @return The x location of the pivot point. 7263 */ 7264 public float getPivotX() { 7265 return mPivotX; 7266 } 7267 7268 /** 7269 * Sets the x location of the point around which the view is 7270 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 7271 * By default, the pivot point is centered on the object. 7272 * Setting this property disables this behavior and causes the view to use only the 7273 * explicitly set pivotX and pivotY values. 7274 * 7275 * @param pivotX The x location of the pivot point. 7276 * @see #getRotation() 7277 * @see #getScaleX() 7278 * @see #getScaleY() 7279 * @see #getPivotY() 7280 * 7281 * @attr ref android.R.styleable#View_transformPivotX 7282 */ 7283 public void setPivotX(float pivotX) { 7284 mPrivateFlags |= PIVOT_EXPLICITLY_SET; 7285 if (mPivotX != pivotX) { 7286 invalidateParentCaches(); 7287 // Double-invalidation is necessary to capture view's old and new areas 7288 invalidate(false); 7289 mPivotX = pivotX; 7290 mMatrixDirty = true; 7291 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7292 invalidate(false); 7293 } 7294 } 7295 7296 /** 7297 * The y location of the point around which the view is {@link #setRotation(float) rotated} 7298 * and {@link #setScaleY(float) scaled}. 7299 * 7300 * @see #getRotation() 7301 * @see #getScaleX() 7302 * @see #getScaleY() 7303 * @see #getPivotY() 7304 * @return The y location of the pivot point. 7305 */ 7306 public float getPivotY() { 7307 return mPivotY; 7308 } 7309 7310 /** 7311 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 7312 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 7313 * Setting this property disables this behavior and causes the view to use only the 7314 * explicitly set pivotX and pivotY values. 7315 * 7316 * @param pivotY The y location of the pivot point. 7317 * @see #getRotation() 7318 * @see #getScaleX() 7319 * @see #getScaleY() 7320 * @see #getPivotY() 7321 * 7322 * @attr ref android.R.styleable#View_transformPivotY 7323 */ 7324 public void setPivotY(float pivotY) { 7325 mPrivateFlags |= PIVOT_EXPLICITLY_SET; 7326 if (mPivotY != pivotY) { 7327 invalidateParentCaches(); 7328 // Double-invalidation is necessary to capture view's old and new areas 7329 invalidate(false); 7330 mPivotY = pivotY; 7331 mMatrixDirty = true; 7332 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7333 invalidate(false); 7334 } 7335 } 7336 7337 /** 7338 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 7339 * completely transparent and 1 means the view is completely opaque. 7340 * 7341 * <p>By default this is 1.0f. 7342 * @return The opacity of the view. 7343 */ 7344 public float getAlpha() { 7345 return mAlpha; 7346 } 7347 7348 /** 7349 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 7350 * completely transparent and 1 means the view is completely opaque.</p> 7351 * 7352 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 7353 * responsible for applying the opacity itself. Otherwise, calling this method is 7354 * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and 7355 * setting a hardware layer.</p> 7356 * 7357 * @param alpha The opacity of the view. 7358 * 7359 * @see #setLayerType(int, android.graphics.Paint) 7360 * 7361 * @attr ref android.R.styleable#View_alpha 7362 */ 7363 public void setAlpha(float alpha) { 7364 mAlpha = alpha; 7365 invalidateParentCaches(); 7366 if (onSetAlpha((int) (alpha * 255))) { 7367 mPrivateFlags |= ALPHA_SET; 7368 // subclass is handling alpha - don't optimize rendering cache invalidation 7369 invalidate(true); 7370 } else { 7371 mPrivateFlags &= ~ALPHA_SET; 7372 invalidate(false); 7373 } 7374 } 7375 7376 /** 7377 * Faster version of setAlpha() which performs the same steps except there are 7378 * no calls to invalidate(). The caller of this function should perform proper invalidation 7379 * on the parent and this object. The return value indicates whether the subclass handles 7380 * alpha (the return value for onSetAlpha()). 7381 * 7382 * @param alpha The new value for the alpha property 7383 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) 7384 */ 7385 boolean setAlphaNoInvalidation(float alpha) { 7386 mAlpha = alpha; 7387 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 7388 if (subclassHandlesAlpha) { 7389 mPrivateFlags |= ALPHA_SET; 7390 } else { 7391 mPrivateFlags &= ~ALPHA_SET; 7392 } 7393 return subclassHandlesAlpha; 7394 } 7395 7396 /** 7397 * Top position of this view relative to its parent. 7398 * 7399 * @return The top of this view, in pixels. 7400 */ 7401 @ViewDebug.CapturedViewProperty 7402 public final int getTop() { 7403 return mTop; 7404 } 7405 7406 /** 7407 * Sets the top position of this view relative to its parent. This method is meant to be called 7408 * by the layout system and should not generally be called otherwise, because the property 7409 * may be changed at any time by the layout. 7410 * 7411 * @param top The top of this view, in pixels. 7412 */ 7413 public final void setTop(int top) { 7414 if (top != mTop) { 7415 updateMatrix(); 7416 if (mMatrixIsIdentity) { 7417 if (mAttachInfo != null) { 7418 int minTop; 7419 int yLoc; 7420 if (top < mTop) { 7421 minTop = top; 7422 yLoc = top - mTop; 7423 } else { 7424 minTop = mTop; 7425 yLoc = 0; 7426 } 7427 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 7428 } 7429 } else { 7430 // Double-invalidation is necessary to capture view's old and new areas 7431 invalidate(true); 7432 } 7433 7434 int width = mRight - mLeft; 7435 int oldHeight = mBottom - mTop; 7436 7437 mTop = top; 7438 7439 onSizeChanged(width, mBottom - mTop, width, oldHeight); 7440 7441 if (!mMatrixIsIdentity) { 7442 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7443 // A change in dimension means an auto-centered pivot point changes, too 7444 mMatrixDirty = true; 7445 } 7446 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7447 invalidate(true); 7448 } 7449 mBackgroundSizeChanged = true; 7450 invalidateParentIfNeeded(); 7451 } 7452 } 7453 7454 /** 7455 * Bottom position of this view relative to its parent. 7456 * 7457 * @return The bottom of this view, in pixels. 7458 */ 7459 @ViewDebug.CapturedViewProperty 7460 public final int getBottom() { 7461 return mBottom; 7462 } 7463 7464 /** 7465 * True if this view has changed since the last time being drawn. 7466 * 7467 * @return The dirty state of this view. 7468 */ 7469 public boolean isDirty() { 7470 return (mPrivateFlags & DIRTY_MASK) != 0; 7471 } 7472 7473 /** 7474 * Sets the bottom position of this view relative to its parent. This method is meant to be 7475 * called by the layout system and should not generally be called otherwise, because the 7476 * property may be changed at any time by the layout. 7477 * 7478 * @param bottom The bottom of this view, in pixels. 7479 */ 7480 public final void setBottom(int bottom) { 7481 if (bottom != mBottom) { 7482 updateMatrix(); 7483 if (mMatrixIsIdentity) { 7484 if (mAttachInfo != null) { 7485 int maxBottom; 7486 if (bottom < mBottom) { 7487 maxBottom = mBottom; 7488 } else { 7489 maxBottom = bottom; 7490 } 7491 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 7492 } 7493 } else { 7494 // Double-invalidation is necessary to capture view's old and new areas 7495 invalidate(true); 7496 } 7497 7498 int width = mRight - mLeft; 7499 int oldHeight = mBottom - mTop; 7500 7501 mBottom = bottom; 7502 7503 onSizeChanged(width, mBottom - mTop, width, oldHeight); 7504 7505 if (!mMatrixIsIdentity) { 7506 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7507 // A change in dimension means an auto-centered pivot point changes, too 7508 mMatrixDirty = true; 7509 } 7510 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7511 invalidate(true); 7512 } 7513 mBackgroundSizeChanged = true; 7514 invalidateParentIfNeeded(); 7515 } 7516 } 7517 7518 /** 7519 * Left position of this view relative to its parent. 7520 * 7521 * @return The left edge of this view, in pixels. 7522 */ 7523 @ViewDebug.CapturedViewProperty 7524 public final int getLeft() { 7525 return mLeft; 7526 } 7527 7528 /** 7529 * Sets the left position of this view relative to its parent. This method is meant to be called 7530 * by the layout system and should not generally be called otherwise, because the property 7531 * may be changed at any time by the layout. 7532 * 7533 * @param left The bottom of this view, in pixels. 7534 */ 7535 public final void setLeft(int left) { 7536 if (left != mLeft) { 7537 updateMatrix(); 7538 if (mMatrixIsIdentity) { 7539 if (mAttachInfo != null) { 7540 int minLeft; 7541 int xLoc; 7542 if (left < mLeft) { 7543 minLeft = left; 7544 xLoc = left - mLeft; 7545 } else { 7546 minLeft = mLeft; 7547 xLoc = 0; 7548 } 7549 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 7550 } 7551 } else { 7552 // Double-invalidation is necessary to capture view's old and new areas 7553 invalidate(true); 7554 } 7555 7556 int oldWidth = mRight - mLeft; 7557 int height = mBottom - mTop; 7558 7559 mLeft = left; 7560 7561 onSizeChanged(mRight - mLeft, height, oldWidth, height); 7562 7563 if (!mMatrixIsIdentity) { 7564 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7565 // A change in dimension means an auto-centered pivot point changes, too 7566 mMatrixDirty = true; 7567 } 7568 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7569 invalidate(true); 7570 } 7571 mBackgroundSizeChanged = true; 7572 invalidateParentIfNeeded(); 7573 } 7574 } 7575 7576 /** 7577 * Right position of this view relative to its parent. 7578 * 7579 * @return The right edge of this view, in pixels. 7580 */ 7581 @ViewDebug.CapturedViewProperty 7582 public final int getRight() { 7583 return mRight; 7584 } 7585 7586 /** 7587 * Sets the right position of this view relative to its parent. This method is meant to be called 7588 * by the layout system and should not generally be called otherwise, because the property 7589 * may be changed at any time by the layout. 7590 * 7591 * @param right The bottom of this view, in pixels. 7592 */ 7593 public final void setRight(int right) { 7594 if (right != mRight) { 7595 updateMatrix(); 7596 if (mMatrixIsIdentity) { 7597 if (mAttachInfo != null) { 7598 int maxRight; 7599 if (right < mRight) { 7600 maxRight = mRight; 7601 } else { 7602 maxRight = right; 7603 } 7604 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 7605 } 7606 } else { 7607 // Double-invalidation is necessary to capture view's old and new areas 7608 invalidate(true); 7609 } 7610 7611 int oldWidth = mRight - mLeft; 7612 int height = mBottom - mTop; 7613 7614 mRight = right; 7615 7616 onSizeChanged(mRight - mLeft, height, oldWidth, height); 7617 7618 if (!mMatrixIsIdentity) { 7619 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7620 // A change in dimension means an auto-centered pivot point changes, too 7621 mMatrixDirty = true; 7622 } 7623 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7624 invalidate(true); 7625 } 7626 mBackgroundSizeChanged = true; 7627 invalidateParentIfNeeded(); 7628 } 7629 } 7630 7631 /** 7632 * The visual x position of this view, in pixels. This is equivalent to the 7633 * {@link #setTranslationX(float) translationX} property plus the current 7634 * {@link #getLeft() left} property. 7635 * 7636 * @return The visual x position of this view, in pixels. 7637 */ 7638 public float getX() { 7639 return mLeft + mTranslationX; 7640 } 7641 7642 /** 7643 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 7644 * {@link #setTranslationX(float) translationX} property to be the difference between 7645 * the x value passed in and the current {@link #getLeft() left} property. 7646 * 7647 * @param x The visual x position of this view, in pixels. 7648 */ 7649 public void setX(float x) { 7650 setTranslationX(x - mLeft); 7651 } 7652 7653 /** 7654 * The visual y position of this view, in pixels. This is equivalent to the 7655 * {@link #setTranslationY(float) translationY} property plus the current 7656 * {@link #getTop() top} property. 7657 * 7658 * @return The visual y position of this view, in pixels. 7659 */ 7660 public float getY() { 7661 return mTop + mTranslationY; 7662 } 7663 7664 /** 7665 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 7666 * {@link #setTranslationY(float) translationY} property to be the difference between 7667 * the y value passed in and the current {@link #getTop() top} property. 7668 * 7669 * @param y The visual y position of this view, in pixels. 7670 */ 7671 public void setY(float y) { 7672 setTranslationY(y - mTop); 7673 } 7674 7675 7676 /** 7677 * The horizontal location of this view relative to its {@link #getLeft() left} position. 7678 * This position is post-layout, in addition to wherever the object's 7679 * layout placed it. 7680 * 7681 * @return The horizontal position of this view relative to its left position, in pixels. 7682 */ 7683 public float getTranslationX() { 7684 return mTranslationX; 7685 } 7686 7687 /** 7688 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 7689 * This effectively positions the object post-layout, in addition to wherever the object's 7690 * layout placed it. 7691 * 7692 * @param translationX The horizontal position of this view relative to its left position, 7693 * in pixels. 7694 * 7695 * @attr ref android.R.styleable#View_translationX 7696 */ 7697 public void setTranslationX(float translationX) { 7698 if (mTranslationX != translationX) { 7699 invalidateParentCaches(); 7700 // Double-invalidation is necessary to capture view's old and new areas 7701 invalidate(false); 7702 mTranslationX = translationX; 7703 mMatrixDirty = true; 7704 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7705 invalidate(false); 7706 } 7707 } 7708 7709 /** 7710 * The horizontal location of this view relative to its {@link #getTop() top} position. 7711 * This position is post-layout, in addition to wherever the object's 7712 * layout placed it. 7713 * 7714 * @return The vertical position of this view relative to its top position, 7715 * in pixels. 7716 */ 7717 public float getTranslationY() { 7718 return mTranslationY; 7719 } 7720 7721 /** 7722 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 7723 * This effectively positions the object post-layout, in addition to wherever the object's 7724 * layout placed it. 7725 * 7726 * @param translationY The vertical position of this view relative to its top position, 7727 * in pixels. 7728 * 7729 * @attr ref android.R.styleable#View_translationY 7730 */ 7731 public void setTranslationY(float translationY) { 7732 if (mTranslationY != translationY) { 7733 invalidateParentCaches(); 7734 // Double-invalidation is necessary to capture view's old and new areas 7735 invalidate(false); 7736 mTranslationY = translationY; 7737 mMatrixDirty = true; 7738 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7739 invalidate(false); 7740 } 7741 } 7742 7743 /** 7744 * @hide 7745 */ 7746 public void setFastTranslationX(float x) { 7747 mTranslationX = x; 7748 mMatrixDirty = true; 7749 } 7750 7751 /** 7752 * @hide 7753 */ 7754 public void setFastTranslationY(float y) { 7755 mTranslationY = y; 7756 mMatrixDirty = true; 7757 } 7758 7759 /** 7760 * @hide 7761 */ 7762 public void setFastX(float x) { 7763 mTranslationX = x - mLeft; 7764 mMatrixDirty = true; 7765 } 7766 7767 /** 7768 * @hide 7769 */ 7770 public void setFastY(float y) { 7771 mTranslationY = y - mTop; 7772 mMatrixDirty = true; 7773 } 7774 7775 /** 7776 * @hide 7777 */ 7778 public void setFastScaleX(float x) { 7779 mScaleX = x; 7780 mMatrixDirty = true; 7781 } 7782 7783 /** 7784 * @hide 7785 */ 7786 public void setFastScaleY(float y) { 7787 mScaleY = y; 7788 mMatrixDirty = true; 7789 } 7790 7791 /** 7792 * @hide 7793 */ 7794 public void setFastAlpha(float alpha) { 7795 mAlpha = alpha; 7796 } 7797 7798 /** 7799 * @hide 7800 */ 7801 public void setFastRotationY(float y) { 7802 mRotationY = y; 7803 mMatrixDirty = true; 7804 } 7805 7806 /** 7807 * Hit rectangle in parent's coordinates 7808 * 7809 * @param outRect The hit rectangle of the view. 7810 */ 7811 public void getHitRect(Rect outRect) { 7812 updateMatrix(); 7813 if (mMatrixIsIdentity || mAttachInfo == null) { 7814 outRect.set(mLeft, mTop, mRight, mBottom); 7815 } else { 7816 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 7817 tmpRect.set(-mPivotX, -mPivotY, getWidth() - mPivotX, getHeight() - mPivotY); 7818 mMatrix.mapRect(tmpRect); 7819 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 7820 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 7821 } 7822 } 7823 7824 /** 7825 * Determines whether the given point, in local coordinates is inside the view. 7826 */ 7827 /*package*/ final boolean pointInView(float localX, float localY) { 7828 return localX >= 0 && localX < (mRight - mLeft) 7829 && localY >= 0 && localY < (mBottom - mTop); 7830 } 7831 7832 /** 7833 * Utility method to determine whether the given point, in local coordinates, 7834 * is inside the view, where the area of the view is expanded by the slop factor. 7835 * This method is called while processing touch-move events to determine if the event 7836 * is still within the view. 7837 */ 7838 private boolean pointInView(float localX, float localY, float slop) { 7839 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 7840 localY < ((mBottom - mTop) + slop); 7841 } 7842 7843 /** 7844 * When a view has focus and the user navigates away from it, the next view is searched for 7845 * starting from the rectangle filled in by this method. 7846 * 7847 * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)}) 7848 * of the view. However, if your view maintains some idea of internal selection, 7849 * such as a cursor, or a selected row or column, you should override this method and 7850 * fill in a more specific rectangle. 7851 * 7852 * @param r The rectangle to fill in, in this view's coordinates. 7853 */ 7854 public void getFocusedRect(Rect r) { 7855 getDrawingRect(r); 7856 } 7857 7858 /** 7859 * If some part of this view is not clipped by any of its parents, then 7860 * return that area in r in global (root) coordinates. To convert r to local 7861 * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x, 7862 * -globalOffset.y)) If the view is completely clipped or translated out, 7863 * return false. 7864 * 7865 * @param r If true is returned, r holds the global coordinates of the 7866 * visible portion of this view. 7867 * @param globalOffset If true is returned, globalOffset holds the dx,dy 7868 * between this view and its root. globalOffet may be null. 7869 * @return true if r is non-empty (i.e. part of the view is visible at the 7870 * root level. 7871 */ 7872 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 7873 int width = mRight - mLeft; 7874 int height = mBottom - mTop; 7875 if (width > 0 && height > 0) { 7876 r.set(0, 0, width, height); 7877 if (globalOffset != null) { 7878 globalOffset.set(-mScrollX, -mScrollY); 7879 } 7880 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 7881 } 7882 return false; 7883 } 7884 7885 public final boolean getGlobalVisibleRect(Rect r) { 7886 return getGlobalVisibleRect(r, null); 7887 } 7888 7889 public final boolean getLocalVisibleRect(Rect r) { 7890 Point offset = new Point(); 7891 if (getGlobalVisibleRect(r, offset)) { 7892 r.offset(-offset.x, -offset.y); // make r local 7893 return true; 7894 } 7895 return false; 7896 } 7897 7898 /** 7899 * Offset this view's vertical location by the specified number of pixels. 7900 * 7901 * @param offset the number of pixels to offset the view by 7902 */ 7903 public void offsetTopAndBottom(int offset) { 7904 if (offset != 0) { 7905 updateMatrix(); 7906 if (mMatrixIsIdentity) { 7907 final ViewParent p = mParent; 7908 if (p != null && mAttachInfo != null) { 7909 final Rect r = mAttachInfo.mTmpInvalRect; 7910 int minTop; 7911 int maxBottom; 7912 int yLoc; 7913 if (offset < 0) { 7914 minTop = mTop + offset; 7915 maxBottom = mBottom; 7916 yLoc = offset; 7917 } else { 7918 minTop = mTop; 7919 maxBottom = mBottom + offset; 7920 yLoc = 0; 7921 } 7922 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 7923 p.invalidateChild(this, r); 7924 } 7925 } else { 7926 invalidate(false); 7927 } 7928 7929 mTop += offset; 7930 mBottom += offset; 7931 7932 if (!mMatrixIsIdentity) { 7933 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7934 invalidate(false); 7935 } 7936 invalidateParentIfNeeded(); 7937 } 7938 } 7939 7940 /** 7941 * Offset this view's horizontal location by the specified amount of pixels. 7942 * 7943 * @param offset the numer of pixels to offset the view by 7944 */ 7945 public void offsetLeftAndRight(int offset) { 7946 if (offset != 0) { 7947 updateMatrix(); 7948 if (mMatrixIsIdentity) { 7949 final ViewParent p = mParent; 7950 if (p != null && mAttachInfo != null) { 7951 final Rect r = mAttachInfo.mTmpInvalRect; 7952 int minLeft; 7953 int maxRight; 7954 if (offset < 0) { 7955 minLeft = mLeft + offset; 7956 maxRight = mRight; 7957 } else { 7958 minLeft = mLeft; 7959 maxRight = mRight + offset; 7960 } 7961 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 7962 p.invalidateChild(this, r); 7963 } 7964 } else { 7965 invalidate(false); 7966 } 7967 7968 mLeft += offset; 7969 mRight += offset; 7970 7971 if (!mMatrixIsIdentity) { 7972 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7973 invalidate(false); 7974 } 7975 invalidateParentIfNeeded(); 7976 } 7977 } 7978 7979 /** 7980 * Get the LayoutParams associated with this view. All views should have 7981 * layout parameters. These supply parameters to the <i>parent</i> of this 7982 * view specifying how it should be arranged. There are many subclasses of 7983 * ViewGroup.LayoutParams, and these correspond to the different subclasses 7984 * of ViewGroup that are responsible for arranging their children. 7985 * 7986 * This method may return null if this View is not attached to a parent 7987 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 7988 * was not invoked successfully. When a View is attached to a parent 7989 * ViewGroup, this method must not return null. 7990 * 7991 * @return The LayoutParams associated with this view, or null if no 7992 * parameters have been set yet 7993 */ 7994 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 7995 public ViewGroup.LayoutParams getLayoutParams() { 7996 return mLayoutParams; 7997 } 7998 7999 /** 8000 * Set the layout parameters associated with this view. These supply 8001 * parameters to the <i>parent</i> of this view specifying how it should be 8002 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 8003 * correspond to the different subclasses of ViewGroup that are responsible 8004 * for arranging their children. 8005 * 8006 * @param params The layout parameters for this view, cannot be null 8007 */ 8008 public void setLayoutParams(ViewGroup.LayoutParams params) { 8009 if (params == null) { 8010 throw new NullPointerException("Layout parameters cannot be null"); 8011 } 8012 mLayoutParams = params; 8013 requestLayout(); 8014 } 8015 8016 /** 8017 * Set the scrolled position of your view. This will cause a call to 8018 * {@link #onScrollChanged(int, int, int, int)} and the view will be 8019 * invalidated. 8020 * @param x the x position to scroll to 8021 * @param y the y position to scroll to 8022 */ 8023 public void scrollTo(int x, int y) { 8024 if (mScrollX != x || mScrollY != y) { 8025 int oldX = mScrollX; 8026 int oldY = mScrollY; 8027 mScrollX = x; 8028 mScrollY = y; 8029 invalidateParentCaches(); 8030 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 8031 if (!awakenScrollBars()) { 8032 invalidate(true); 8033 } 8034 } 8035 } 8036 8037 /** 8038 * Move the scrolled position of your view. This will cause a call to 8039 * {@link #onScrollChanged(int, int, int, int)} and the view will be 8040 * invalidated. 8041 * @param x the amount of pixels to scroll by horizontally 8042 * @param y the amount of pixels to scroll by vertically 8043 */ 8044 public void scrollBy(int x, int y) { 8045 scrollTo(mScrollX + x, mScrollY + y); 8046 } 8047 8048 /** 8049 * <p>Trigger the scrollbars to draw. When invoked this method starts an 8050 * animation to fade the scrollbars out after a default delay. If a subclass 8051 * provides animated scrolling, the start delay should equal the duration 8052 * of the scrolling animation.</p> 8053 * 8054 * <p>The animation starts only if at least one of the scrollbars is 8055 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 8056 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 8057 * this method returns true, and false otherwise. If the animation is 8058 * started, this method calls {@link #invalidate()}; in that case the 8059 * caller should not call {@link #invalidate()}.</p> 8060 * 8061 * <p>This method should be invoked every time a subclass directly updates 8062 * the scroll parameters.</p> 8063 * 8064 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 8065 * and {@link #scrollTo(int, int)}.</p> 8066 * 8067 * @return true if the animation is played, false otherwise 8068 * 8069 * @see #awakenScrollBars(int) 8070 * @see #scrollBy(int, int) 8071 * @see #scrollTo(int, int) 8072 * @see #isHorizontalScrollBarEnabled() 8073 * @see #isVerticalScrollBarEnabled() 8074 * @see #setHorizontalScrollBarEnabled(boolean) 8075 * @see #setVerticalScrollBarEnabled(boolean) 8076 */ 8077 protected boolean awakenScrollBars() { 8078 return mScrollCache != null && 8079 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 8080 } 8081 8082 /** 8083 * Trigger the scrollbars to draw. 8084 * This method differs from awakenScrollBars() only in its default duration. 8085 * initialAwakenScrollBars() will show the scroll bars for longer than 8086 * usual to give the user more of a chance to notice them. 8087 * 8088 * @return true if the animation is played, false otherwise. 8089 */ 8090 private boolean initialAwakenScrollBars() { 8091 return mScrollCache != null && 8092 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 8093 } 8094 8095 /** 8096 * <p> 8097 * Trigger the scrollbars to draw. When invoked this method starts an 8098 * animation to fade the scrollbars out after a fixed delay. If a subclass 8099 * provides animated scrolling, the start delay should equal the duration of 8100 * the scrolling animation. 8101 * </p> 8102 * 8103 * <p> 8104 * The animation starts only if at least one of the scrollbars is enabled, 8105 * as specified by {@link #isHorizontalScrollBarEnabled()} and 8106 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 8107 * this method returns true, and false otherwise. If the animation is 8108 * started, this method calls {@link #invalidate()}; in that case the caller 8109 * should not call {@link #invalidate()}. 8110 * </p> 8111 * 8112 * <p> 8113 * This method should be invoked everytime a subclass directly updates the 8114 * scroll parameters. 8115 * </p> 8116 * 8117 * @param startDelay the delay, in milliseconds, after which the animation 8118 * should start; when the delay is 0, the animation starts 8119 * immediately 8120 * @return true if the animation is played, false otherwise 8121 * 8122 * @see #scrollBy(int, int) 8123 * @see #scrollTo(int, int) 8124 * @see #isHorizontalScrollBarEnabled() 8125 * @see #isVerticalScrollBarEnabled() 8126 * @see #setHorizontalScrollBarEnabled(boolean) 8127 * @see #setVerticalScrollBarEnabled(boolean) 8128 */ 8129 protected boolean awakenScrollBars(int startDelay) { 8130 return awakenScrollBars(startDelay, true); 8131 } 8132 8133 /** 8134 * <p> 8135 * Trigger the scrollbars to draw. When invoked this method starts an 8136 * animation to fade the scrollbars out after a fixed delay. If a subclass 8137 * provides animated scrolling, the start delay should equal the duration of 8138 * the scrolling animation. 8139 * </p> 8140 * 8141 * <p> 8142 * The animation starts only if at least one of the scrollbars is enabled, 8143 * as specified by {@link #isHorizontalScrollBarEnabled()} and 8144 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 8145 * this method returns true, and false otherwise. If the animation is 8146 * started, this method calls {@link #invalidate()} if the invalidate parameter 8147 * is set to true; in that case the caller 8148 * should not call {@link #invalidate()}. 8149 * </p> 8150 * 8151 * <p> 8152 * This method should be invoked everytime a subclass directly updates the 8153 * scroll parameters. 8154 * </p> 8155 * 8156 * @param startDelay the delay, in milliseconds, after which the animation 8157 * should start; when the delay is 0, the animation starts 8158 * immediately 8159 * 8160 * @param invalidate Wheter this method should call invalidate 8161 * 8162 * @return true if the animation is played, false otherwise 8163 * 8164 * @see #scrollBy(int, int) 8165 * @see #scrollTo(int, int) 8166 * @see #isHorizontalScrollBarEnabled() 8167 * @see #isVerticalScrollBarEnabled() 8168 * @see #setHorizontalScrollBarEnabled(boolean) 8169 * @see #setVerticalScrollBarEnabled(boolean) 8170 */ 8171 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 8172 final ScrollabilityCache scrollCache = mScrollCache; 8173 8174 if (scrollCache == null || !scrollCache.fadeScrollBars) { 8175 return false; 8176 } 8177 8178 if (scrollCache.scrollBar == null) { 8179 scrollCache.scrollBar = new ScrollBarDrawable(); 8180 } 8181 8182 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 8183 8184 if (invalidate) { 8185 // Invalidate to show the scrollbars 8186 invalidate(true); 8187 } 8188 8189 if (scrollCache.state == ScrollabilityCache.OFF) { 8190 // FIXME: this is copied from WindowManagerService. 8191 // We should get this value from the system when it 8192 // is possible to do so. 8193 final int KEY_REPEAT_FIRST_DELAY = 750; 8194 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 8195 } 8196 8197 // Tell mScrollCache when we should start fading. This may 8198 // extend the fade start time if one was already scheduled 8199 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 8200 scrollCache.fadeStartTime = fadeStartTime; 8201 scrollCache.state = ScrollabilityCache.ON; 8202 8203 // Schedule our fader to run, unscheduling any old ones first 8204 if (mAttachInfo != null) { 8205 mAttachInfo.mHandler.removeCallbacks(scrollCache); 8206 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 8207 } 8208 8209 return true; 8210 } 8211 8212 return false; 8213 } 8214 8215 /** 8216 * Do not invalidate views which are not visible and which are not running an animation. They 8217 * will not get drawn and they should not set dirty flags as if they will be drawn 8218 */ 8219 private boolean skipInvalidate() { 8220 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 8221 (!(mParent instanceof ViewGroup) || 8222 !((ViewGroup) mParent).isViewTransitioning(this)); 8223 } 8224 /** 8225 * Mark the the area defined by dirty as needing to be drawn. If the view is 8226 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point 8227 * in the future. This must be called from a UI thread. To call from a non-UI 8228 * thread, call {@link #postInvalidate()}. 8229 * 8230 * WARNING: This method is destructive to dirty. 8231 * @param dirty the rectangle representing the bounds of the dirty region 8232 */ 8233 public void invalidate(Rect dirty) { 8234 if (ViewDebug.TRACE_HIERARCHY) { 8235 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 8236 } 8237 8238 if (skipInvalidate()) { 8239 return; 8240 } 8241 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 8242 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID || 8243 (mPrivateFlags & INVALIDATED) != INVALIDATED) { 8244 mPrivateFlags &= ~DRAWING_CACHE_VALID; 8245 mPrivateFlags |= INVALIDATED; 8246 final ViewParent p = mParent; 8247 final AttachInfo ai = mAttachInfo; 8248 //noinspection PointlessBooleanExpression,ConstantConditions 8249 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 8250 if (p != null && ai != null && ai.mHardwareAccelerated) { 8251 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 8252 // with a null dirty rect, which tells the ViewAncestor to redraw everything 8253 p.invalidateChild(this, null); 8254 return; 8255 } 8256 } 8257 if (p != null && ai != null) { 8258 final int scrollX = mScrollX; 8259 final int scrollY = mScrollY; 8260 final Rect r = ai.mTmpInvalRect; 8261 r.set(dirty.left - scrollX, dirty.top - scrollY, 8262 dirty.right - scrollX, dirty.bottom - scrollY); 8263 mParent.invalidateChild(this, r); 8264 } 8265 } 8266 } 8267 8268 /** 8269 * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn. 8270 * The coordinates of the dirty rect are relative to the view. 8271 * If the view is visible, {@link #onDraw(android.graphics.Canvas)} 8272 * will be called at some point in the future. This must be called from 8273 * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}. 8274 * @param l the left position of the dirty region 8275 * @param t the top position of the dirty region 8276 * @param r the right position of the dirty region 8277 * @param b the bottom position of the dirty region 8278 */ 8279 public void invalidate(int l, int t, int r, int b) { 8280 if (ViewDebug.TRACE_HIERARCHY) { 8281 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 8282 } 8283 8284 if (skipInvalidate()) { 8285 return; 8286 } 8287 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 8288 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID || 8289 (mPrivateFlags & INVALIDATED) != INVALIDATED) { 8290 mPrivateFlags &= ~DRAWING_CACHE_VALID; 8291 mPrivateFlags |= INVALIDATED; 8292 final ViewParent p = mParent; 8293 final AttachInfo ai = mAttachInfo; 8294 //noinspection PointlessBooleanExpression,ConstantConditions 8295 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 8296 if (p != null && ai != null && ai.mHardwareAccelerated) { 8297 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 8298 // with a null dirty rect, which tells the ViewAncestor to redraw everything 8299 p.invalidateChild(this, null); 8300 return; 8301 } 8302 } 8303 if (p != null && ai != null && l < r && t < b) { 8304 final int scrollX = mScrollX; 8305 final int scrollY = mScrollY; 8306 final Rect tmpr = ai.mTmpInvalRect; 8307 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY); 8308 p.invalidateChild(this, tmpr); 8309 } 8310 } 8311 } 8312 8313 /** 8314 * Invalidate the whole view. If the view is visible, 8315 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 8316 * the future. This must be called from a UI thread. To call from a non-UI thread, 8317 * call {@link #postInvalidate()}. 8318 */ 8319 public void invalidate() { 8320 invalidate(true); 8321 } 8322 8323 /** 8324 * This is where the invalidate() work actually happens. A full invalidate() 8325 * causes the drawing cache to be invalidated, but this function can be called with 8326 * invalidateCache set to false to skip that invalidation step for cases that do not 8327 * need it (for example, a component that remains at the same dimensions with the same 8328 * content). 8329 * 8330 * @param invalidateCache Whether the drawing cache for this view should be invalidated as 8331 * well. This is usually true for a full invalidate, but may be set to false if the 8332 * View's contents or dimensions have not changed. 8333 */ 8334 void invalidate(boolean invalidateCache) { 8335 if (ViewDebug.TRACE_HIERARCHY) { 8336 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 8337 } 8338 8339 if (skipInvalidate()) { 8340 return; 8341 } 8342 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 8343 (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) || 8344 (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) { 8345 mLastIsOpaque = isOpaque(); 8346 mPrivateFlags &= ~DRAWN; 8347 if (invalidateCache) { 8348 mPrivateFlags |= INVALIDATED; 8349 mPrivateFlags &= ~DRAWING_CACHE_VALID; 8350 } 8351 final AttachInfo ai = mAttachInfo; 8352 final ViewParent p = mParent; 8353 //noinspection PointlessBooleanExpression,ConstantConditions 8354 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 8355 if (p != null && ai != null && ai.mHardwareAccelerated) { 8356 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 8357 // with a null dirty rect, which tells the ViewAncestor to redraw everything 8358 p.invalidateChild(this, null); 8359 return; 8360 } 8361 } 8362 8363 if (p != null && ai != null) { 8364 final Rect r = ai.mTmpInvalRect; 8365 r.set(0, 0, mRight - mLeft, mBottom - mTop); 8366 // Don't call invalidate -- we don't want to internally scroll 8367 // our own bounds 8368 p.invalidateChild(this, r); 8369 } 8370 } 8371 } 8372 8373 /** 8374 * @hide 8375 */ 8376 public void fastInvalidate() { 8377 if (skipInvalidate()) { 8378 return; 8379 } 8380 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 8381 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID || 8382 (mPrivateFlags & INVALIDATED) != INVALIDATED) { 8383 if (mParent instanceof View) { 8384 ((View) mParent).mPrivateFlags |= INVALIDATED; 8385 } 8386 mPrivateFlags &= ~DRAWN; 8387 mPrivateFlags |= INVALIDATED; 8388 mPrivateFlags &= ~DRAWING_CACHE_VALID; 8389 if (mParent != null && mAttachInfo != null) { 8390 if (mAttachInfo.mHardwareAccelerated) { 8391 mParent.invalidateChild(this, null); 8392 } else { 8393 final Rect r = mAttachInfo.mTmpInvalRect; 8394 r.set(0, 0, mRight - mLeft, mBottom - mTop); 8395 // Don't call invalidate -- we don't want to internally scroll 8396 // our own bounds 8397 mParent.invalidateChild(this, r); 8398 } 8399 } 8400 } 8401 } 8402 8403 /** 8404 * Used to indicate that the parent of this view should clear its caches. This functionality 8405 * is used to force the parent to rebuild its display list (when hardware-accelerated), 8406 * which is necessary when various parent-managed properties of the view change, such as 8407 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 8408 * clears the parent caches and does not causes an invalidate event. 8409 * 8410 * @hide 8411 */ 8412 protected void invalidateParentCaches() { 8413 if (mParent instanceof View) { 8414 ((View) mParent).mPrivateFlags |= INVALIDATED; 8415 } 8416 } 8417 8418 /** 8419 * Used to indicate that the parent of this view should be invalidated. This functionality 8420 * is used to force the parent to rebuild its display list (when hardware-accelerated), 8421 * which is necessary when various parent-managed properties of the view change, such as 8422 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 8423 * an invalidation event to the parent. 8424 * 8425 * @hide 8426 */ 8427 protected void invalidateParentIfNeeded() { 8428 if (isHardwareAccelerated() && mParent instanceof View) { 8429 ((View) mParent).invalidate(true); 8430 } 8431 } 8432 8433 /** 8434 * Indicates whether this View is opaque. An opaque View guarantees that it will 8435 * draw all the pixels overlapping its bounds using a fully opaque color. 8436 * 8437 * Subclasses of View should override this method whenever possible to indicate 8438 * whether an instance is opaque. Opaque Views are treated in a special way by 8439 * the View hierarchy, possibly allowing it to perform optimizations during 8440 * invalidate/draw passes. 8441 * 8442 * @return True if this View is guaranteed to be fully opaque, false otherwise. 8443 */ 8444 @ViewDebug.ExportedProperty(category = "drawing") 8445 public boolean isOpaque() { 8446 return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK && 8447 (mAlpha >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD); 8448 } 8449 8450 /** 8451 * @hide 8452 */ 8453 protected void computeOpaqueFlags() { 8454 // Opaque if: 8455 // - Has a background 8456 // - Background is opaque 8457 // - Doesn't have scrollbars or scrollbars are inside overlay 8458 8459 if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) { 8460 mPrivateFlags |= OPAQUE_BACKGROUND; 8461 } else { 8462 mPrivateFlags &= ~OPAQUE_BACKGROUND; 8463 } 8464 8465 final int flags = mViewFlags; 8466 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 8467 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) { 8468 mPrivateFlags |= OPAQUE_SCROLLBARS; 8469 } else { 8470 mPrivateFlags &= ~OPAQUE_SCROLLBARS; 8471 } 8472 } 8473 8474 /** 8475 * @hide 8476 */ 8477 protected boolean hasOpaqueScrollbars() { 8478 return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS; 8479 } 8480 8481 /** 8482 * @return A handler associated with the thread running the View. This 8483 * handler can be used to pump events in the UI events queue. 8484 */ 8485 public Handler getHandler() { 8486 if (mAttachInfo != null) { 8487 return mAttachInfo.mHandler; 8488 } 8489 return null; 8490 } 8491 8492 /** 8493 * <p>Causes the Runnable to be added to the message queue. 8494 * The runnable will be run on the user interface thread.</p> 8495 * 8496 * <p>This method can be invoked from outside of the UI thread 8497 * only when this View is attached to a window.</p> 8498 * 8499 * @param action The Runnable that will be executed. 8500 * 8501 * @return Returns true if the Runnable was successfully placed in to the 8502 * message queue. Returns false on failure, usually because the 8503 * looper processing the message queue is exiting. 8504 */ 8505 public boolean post(Runnable action) { 8506 Handler handler; 8507 AttachInfo attachInfo = mAttachInfo; 8508 if (attachInfo != null) { 8509 handler = attachInfo.mHandler; 8510 } else { 8511 // Assume that post will succeed later 8512 ViewRootImpl.getRunQueue().post(action); 8513 return true; 8514 } 8515 8516 return handler.post(action); 8517 } 8518 8519 /** 8520 * <p>Causes the Runnable to be added to the message queue, to be run 8521 * after the specified amount of time elapses. 8522 * The runnable will be run on the user interface thread.</p> 8523 * 8524 * <p>This method can be invoked from outside of the UI thread 8525 * only when this View is attached to a window.</p> 8526 * 8527 * @param action The Runnable that will be executed. 8528 * @param delayMillis The delay (in milliseconds) until the Runnable 8529 * will be executed. 8530 * 8531 * @return true if the Runnable was successfully placed in to the 8532 * message queue. Returns false on failure, usually because the 8533 * looper processing the message queue is exiting. Note that a 8534 * result of true does not mean the Runnable will be processed -- 8535 * if the looper is quit before the delivery time of the message 8536 * occurs then the message will be dropped. 8537 */ 8538 public boolean postDelayed(Runnable action, long delayMillis) { 8539 Handler handler; 8540 AttachInfo attachInfo = mAttachInfo; 8541 if (attachInfo != null) { 8542 handler = attachInfo.mHandler; 8543 } else { 8544 // Assume that post will succeed later 8545 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 8546 return true; 8547 } 8548 8549 return handler.postDelayed(action, delayMillis); 8550 } 8551 8552 /** 8553 * <p>Removes the specified Runnable from the message queue.</p> 8554 * 8555 * <p>This method can be invoked from outside of the UI thread 8556 * only when this View is attached to a window.</p> 8557 * 8558 * @param action The Runnable to remove from the message handling queue 8559 * 8560 * @return true if this view could ask the Handler to remove the Runnable, 8561 * false otherwise. When the returned value is true, the Runnable 8562 * may or may not have been actually removed from the message queue 8563 * (for instance, if the Runnable was not in the queue already.) 8564 */ 8565 public boolean removeCallbacks(Runnable action) { 8566 Handler handler; 8567 AttachInfo attachInfo = mAttachInfo; 8568 if (attachInfo != null) { 8569 handler = attachInfo.mHandler; 8570 } else { 8571 // Assume that post will succeed later 8572 ViewRootImpl.getRunQueue().removeCallbacks(action); 8573 return true; 8574 } 8575 8576 handler.removeCallbacks(action); 8577 return true; 8578 } 8579 8580 /** 8581 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 8582 * Use this to invalidate the View from a non-UI thread.</p> 8583 * 8584 * <p>This method can be invoked from outside of the UI thread 8585 * only when this View is attached to a window.</p> 8586 * 8587 * @see #invalidate() 8588 */ 8589 public void postInvalidate() { 8590 postInvalidateDelayed(0); 8591 } 8592 8593 /** 8594 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 8595 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 8596 * 8597 * <p>This method can be invoked from outside of the UI thread 8598 * only when this View is attached to a window.</p> 8599 * 8600 * @param left The left coordinate of the rectangle to invalidate. 8601 * @param top The top coordinate of the rectangle to invalidate. 8602 * @param right The right coordinate of the rectangle to invalidate. 8603 * @param bottom The bottom coordinate of the rectangle to invalidate. 8604 * 8605 * @see #invalidate(int, int, int, int) 8606 * @see #invalidate(Rect) 8607 */ 8608 public void postInvalidate(int left, int top, int right, int bottom) { 8609 postInvalidateDelayed(0, left, top, right, bottom); 8610 } 8611 8612 /** 8613 * <p>Cause an invalidate to happen on a subsequent cycle through the event 8614 * loop. Waits for the specified amount of time.</p> 8615 * 8616 * <p>This method can be invoked from outside of the UI thread 8617 * only when this View is attached to a window.</p> 8618 * 8619 * @param delayMilliseconds the duration in milliseconds to delay the 8620 * invalidation by 8621 */ 8622 public void postInvalidateDelayed(long delayMilliseconds) { 8623 // We try only with the AttachInfo because there's no point in invalidating 8624 // if we are not attached to our window 8625 AttachInfo attachInfo = mAttachInfo; 8626 if (attachInfo != null) { 8627 Message msg = Message.obtain(); 8628 msg.what = AttachInfo.INVALIDATE_MSG; 8629 msg.obj = this; 8630 attachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds); 8631 } 8632 } 8633 8634 /** 8635 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 8636 * through the event loop. Waits for the specified amount of time.</p> 8637 * 8638 * <p>This method can be invoked from outside of the UI thread 8639 * only when this View is attached to a window.</p> 8640 * 8641 * @param delayMilliseconds the duration in milliseconds to delay the 8642 * invalidation by 8643 * @param left The left coordinate of the rectangle to invalidate. 8644 * @param top The top coordinate of the rectangle to invalidate. 8645 * @param right The right coordinate of the rectangle to invalidate. 8646 * @param bottom The bottom coordinate of the rectangle to invalidate. 8647 */ 8648 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 8649 int right, int bottom) { 8650 8651 // We try only with the AttachInfo because there's no point in invalidating 8652 // if we are not attached to our window 8653 AttachInfo attachInfo = mAttachInfo; 8654 if (attachInfo != null) { 8655 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire(); 8656 info.target = this; 8657 info.left = left; 8658 info.top = top; 8659 info.right = right; 8660 info.bottom = bottom; 8661 8662 final Message msg = Message.obtain(); 8663 msg.what = AttachInfo.INVALIDATE_RECT_MSG; 8664 msg.obj = info; 8665 attachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds); 8666 } 8667 } 8668 8669 /** 8670 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 8671 * This event is sent at most once every 8672 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 8673 */ 8674 private void postSendViewScrolledAccessibilityEventCallback() { 8675 if (mSendViewScrolledAccessibilityEvent == null) { 8676 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 8677 } 8678 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 8679 mSendViewScrolledAccessibilityEvent.mIsPending = true; 8680 postDelayed(mSendViewScrolledAccessibilityEvent, 8681 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 8682 } 8683 } 8684 8685 /** 8686 * Called by a parent to request that a child update its values for mScrollX 8687 * and mScrollY if necessary. This will typically be done if the child is 8688 * animating a scroll using a {@link android.widget.Scroller Scroller} 8689 * object. 8690 */ 8691 public void computeScroll() { 8692 } 8693 8694 /** 8695 * <p>Indicate whether the horizontal edges are faded when the view is 8696 * scrolled horizontally.</p> 8697 * 8698 * @return true if the horizontal edges should are faded on scroll, false 8699 * otherwise 8700 * 8701 * @see #setHorizontalFadingEdgeEnabled(boolean) 8702 * @attr ref android.R.styleable#View_fadingEdge 8703 */ 8704 public boolean isHorizontalFadingEdgeEnabled() { 8705 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 8706 } 8707 8708 /** 8709 * <p>Define whether the horizontal edges should be faded when this view 8710 * is scrolled horizontally.</p> 8711 * 8712 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 8713 * be faded when the view is scrolled 8714 * horizontally 8715 * 8716 * @see #isHorizontalFadingEdgeEnabled() 8717 * @attr ref android.R.styleable#View_fadingEdge 8718 */ 8719 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 8720 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 8721 if (horizontalFadingEdgeEnabled) { 8722 initScrollCache(); 8723 } 8724 8725 mViewFlags ^= FADING_EDGE_HORIZONTAL; 8726 } 8727 } 8728 8729 /** 8730 * <p>Indicate whether the vertical edges are faded when the view is 8731 * scrolled horizontally.</p> 8732 * 8733 * @return true if the vertical edges should are faded on scroll, false 8734 * otherwise 8735 * 8736 * @see #setVerticalFadingEdgeEnabled(boolean) 8737 * @attr ref android.R.styleable#View_fadingEdge 8738 */ 8739 public boolean isVerticalFadingEdgeEnabled() { 8740 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 8741 } 8742 8743 /** 8744 * <p>Define whether the vertical edges should be faded when this view 8745 * is scrolled vertically.</p> 8746 * 8747 * @param verticalFadingEdgeEnabled true if the vertical edges should 8748 * be faded when the view is scrolled 8749 * vertically 8750 * 8751 * @see #isVerticalFadingEdgeEnabled() 8752 * @attr ref android.R.styleable#View_fadingEdge 8753 */ 8754 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 8755 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 8756 if (verticalFadingEdgeEnabled) { 8757 initScrollCache(); 8758 } 8759 8760 mViewFlags ^= FADING_EDGE_VERTICAL; 8761 } 8762 } 8763 8764 /** 8765 * Returns the strength, or intensity, of the top faded edge. The strength is 8766 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 8767 * returns 0.0 or 1.0 but no value in between. 8768 * 8769 * Subclasses should override this method to provide a smoother fade transition 8770 * when scrolling occurs. 8771 * 8772 * @return the intensity of the top fade as a float between 0.0f and 1.0f 8773 */ 8774 protected float getTopFadingEdgeStrength() { 8775 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 8776 } 8777 8778 /** 8779 * Returns the strength, or intensity, of the bottom faded edge. The strength is 8780 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 8781 * returns 0.0 or 1.0 but no value in between. 8782 * 8783 * Subclasses should override this method to provide a smoother fade transition 8784 * when scrolling occurs. 8785 * 8786 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 8787 */ 8788 protected float getBottomFadingEdgeStrength() { 8789 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 8790 computeVerticalScrollRange() ? 1.0f : 0.0f; 8791 } 8792 8793 /** 8794 * Returns the strength, or intensity, of the left faded edge. The strength is 8795 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 8796 * returns 0.0 or 1.0 but no value in between. 8797 * 8798 * Subclasses should override this method to provide a smoother fade transition 8799 * when scrolling occurs. 8800 * 8801 * @return the intensity of the left fade as a float between 0.0f and 1.0f 8802 */ 8803 protected float getLeftFadingEdgeStrength() { 8804 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 8805 } 8806 8807 /** 8808 * Returns the strength, or intensity, of the right faded edge. The strength is 8809 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 8810 * returns 0.0 or 1.0 but no value in between. 8811 * 8812 * Subclasses should override this method to provide a smoother fade transition 8813 * when scrolling occurs. 8814 * 8815 * @return the intensity of the right fade as a float between 0.0f and 1.0f 8816 */ 8817 protected float getRightFadingEdgeStrength() { 8818 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 8819 computeHorizontalScrollRange() ? 1.0f : 0.0f; 8820 } 8821 8822 /** 8823 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 8824 * scrollbar is not drawn by default.</p> 8825 * 8826 * @return true if the horizontal scrollbar should be painted, false 8827 * otherwise 8828 * 8829 * @see #setHorizontalScrollBarEnabled(boolean) 8830 */ 8831 public boolean isHorizontalScrollBarEnabled() { 8832 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 8833 } 8834 8835 /** 8836 * <p>Define whether the horizontal scrollbar should be drawn or not. The 8837 * scrollbar is not drawn by default.</p> 8838 * 8839 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 8840 * be painted 8841 * 8842 * @see #isHorizontalScrollBarEnabled() 8843 */ 8844 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 8845 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 8846 mViewFlags ^= SCROLLBARS_HORIZONTAL; 8847 computeOpaqueFlags(); 8848 resolvePadding(); 8849 } 8850 } 8851 8852 /** 8853 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 8854 * scrollbar is not drawn by default.</p> 8855 * 8856 * @return true if the vertical scrollbar should be painted, false 8857 * otherwise 8858 * 8859 * @see #setVerticalScrollBarEnabled(boolean) 8860 */ 8861 public boolean isVerticalScrollBarEnabled() { 8862 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 8863 } 8864 8865 /** 8866 * <p>Define whether the vertical scrollbar should be drawn or not. The 8867 * scrollbar is not drawn by default.</p> 8868 * 8869 * @param verticalScrollBarEnabled true if the vertical scrollbar should 8870 * be painted 8871 * 8872 * @see #isVerticalScrollBarEnabled() 8873 */ 8874 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 8875 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 8876 mViewFlags ^= SCROLLBARS_VERTICAL; 8877 computeOpaqueFlags(); 8878 resolvePadding(); 8879 } 8880 } 8881 8882 /** 8883 * @hide 8884 */ 8885 protected void recomputePadding() { 8886 setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 8887 } 8888 8889 /** 8890 * Define whether scrollbars will fade when the view is not scrolling. 8891 * 8892 * @param fadeScrollbars wheter to enable fading 8893 * 8894 */ 8895 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 8896 initScrollCache(); 8897 final ScrollabilityCache scrollabilityCache = mScrollCache; 8898 scrollabilityCache.fadeScrollBars = fadeScrollbars; 8899 if (fadeScrollbars) { 8900 scrollabilityCache.state = ScrollabilityCache.OFF; 8901 } else { 8902 scrollabilityCache.state = ScrollabilityCache.ON; 8903 } 8904 } 8905 8906 /** 8907 * 8908 * Returns true if scrollbars will fade when this view is not scrolling 8909 * 8910 * @return true if scrollbar fading is enabled 8911 */ 8912 public boolean isScrollbarFadingEnabled() { 8913 return mScrollCache != null && mScrollCache.fadeScrollBars; 8914 } 8915 8916 /** 8917 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 8918 * inset. When inset, they add to the padding of the view. And the scrollbars 8919 * can be drawn inside the padding area or on the edge of the view. For example, 8920 * if a view has a background drawable and you want to draw the scrollbars 8921 * inside the padding specified by the drawable, you can use 8922 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 8923 * appear at the edge of the view, ignoring the padding, then you can use 8924 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 8925 * @param style the style of the scrollbars. Should be one of 8926 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 8927 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 8928 * @see #SCROLLBARS_INSIDE_OVERLAY 8929 * @see #SCROLLBARS_INSIDE_INSET 8930 * @see #SCROLLBARS_OUTSIDE_OVERLAY 8931 * @see #SCROLLBARS_OUTSIDE_INSET 8932 */ 8933 public void setScrollBarStyle(int style) { 8934 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 8935 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 8936 computeOpaqueFlags(); 8937 resolvePadding(); 8938 } 8939 } 8940 8941 /** 8942 * <p>Returns the current scrollbar style.</p> 8943 * @return the current scrollbar style 8944 * @see #SCROLLBARS_INSIDE_OVERLAY 8945 * @see #SCROLLBARS_INSIDE_INSET 8946 * @see #SCROLLBARS_OUTSIDE_OVERLAY 8947 * @see #SCROLLBARS_OUTSIDE_INSET 8948 */ 8949 @ViewDebug.ExportedProperty(mapping = { 8950 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 8951 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 8952 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 8953 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 8954 }) 8955 public int getScrollBarStyle() { 8956 return mViewFlags & SCROLLBARS_STYLE_MASK; 8957 } 8958 8959 /** 8960 * <p>Compute the horizontal range that the horizontal scrollbar 8961 * represents.</p> 8962 * 8963 * <p>The range is expressed in arbitrary units that must be the same as the 8964 * units used by {@link #computeHorizontalScrollExtent()} and 8965 * {@link #computeHorizontalScrollOffset()}.</p> 8966 * 8967 * <p>The default range is the drawing width of this view.</p> 8968 * 8969 * @return the total horizontal range represented by the horizontal 8970 * scrollbar 8971 * 8972 * @see #computeHorizontalScrollExtent() 8973 * @see #computeHorizontalScrollOffset() 8974 * @see android.widget.ScrollBarDrawable 8975 */ 8976 protected int computeHorizontalScrollRange() { 8977 return getWidth(); 8978 } 8979 8980 /** 8981 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 8982 * within the horizontal range. This value is used to compute the position 8983 * of the thumb within the scrollbar's track.</p> 8984 * 8985 * <p>The range is expressed in arbitrary units that must be the same as the 8986 * units used by {@link #computeHorizontalScrollRange()} and 8987 * {@link #computeHorizontalScrollExtent()}.</p> 8988 * 8989 * <p>The default offset is the scroll offset of this view.</p> 8990 * 8991 * @return the horizontal offset of the scrollbar's thumb 8992 * 8993 * @see #computeHorizontalScrollRange() 8994 * @see #computeHorizontalScrollExtent() 8995 * @see android.widget.ScrollBarDrawable 8996 */ 8997 protected int computeHorizontalScrollOffset() { 8998 return mScrollX; 8999 } 9000 9001 /** 9002 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 9003 * within the horizontal range. This value is used to compute the length 9004 * of the thumb within the scrollbar's track.</p> 9005 * 9006 * <p>The range is expressed in arbitrary units that must be the same as the 9007 * units used by {@link #computeHorizontalScrollRange()} and 9008 * {@link #computeHorizontalScrollOffset()}.</p> 9009 * 9010 * <p>The default extent is the drawing width of this view.</p> 9011 * 9012 * @return the horizontal extent of the scrollbar's thumb 9013 * 9014 * @see #computeHorizontalScrollRange() 9015 * @see #computeHorizontalScrollOffset() 9016 * @see android.widget.ScrollBarDrawable 9017 */ 9018 protected int computeHorizontalScrollExtent() { 9019 return getWidth(); 9020 } 9021 9022 /** 9023 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 9024 * 9025 * <p>The range is expressed in arbitrary units that must be the same as the 9026 * units used by {@link #computeVerticalScrollExtent()} and 9027 * {@link #computeVerticalScrollOffset()}.</p> 9028 * 9029 * @return the total vertical range represented by the vertical scrollbar 9030 * 9031 * <p>The default range is the drawing height of this view.</p> 9032 * 9033 * @see #computeVerticalScrollExtent() 9034 * @see #computeVerticalScrollOffset() 9035 * @see android.widget.ScrollBarDrawable 9036 */ 9037 protected int computeVerticalScrollRange() { 9038 return getHeight(); 9039 } 9040 9041 /** 9042 * <p>Compute the vertical offset of the vertical scrollbar's thumb 9043 * within the horizontal range. This value is used to compute the position 9044 * of the thumb within the scrollbar's track.</p> 9045 * 9046 * <p>The range is expressed in arbitrary units that must be the same as the 9047 * units used by {@link #computeVerticalScrollRange()} and 9048 * {@link #computeVerticalScrollExtent()}.</p> 9049 * 9050 * <p>The default offset is the scroll offset of this view.</p> 9051 * 9052 * @return the vertical offset of the scrollbar's thumb 9053 * 9054 * @see #computeVerticalScrollRange() 9055 * @see #computeVerticalScrollExtent() 9056 * @see android.widget.ScrollBarDrawable 9057 */ 9058 protected int computeVerticalScrollOffset() { 9059 return mScrollY; 9060 } 9061 9062 /** 9063 * <p>Compute the vertical extent of the horizontal scrollbar's thumb 9064 * within the vertical range. This value is used to compute the length 9065 * of the thumb within the scrollbar's track.</p> 9066 * 9067 * <p>The range is expressed in arbitrary units that must be the same as the 9068 * units used by {@link #computeVerticalScrollRange()} and 9069 * {@link #computeVerticalScrollOffset()}.</p> 9070 * 9071 * <p>The default extent is the drawing height of this view.</p> 9072 * 9073 * @return the vertical extent of the scrollbar's thumb 9074 * 9075 * @see #computeVerticalScrollRange() 9076 * @see #computeVerticalScrollOffset() 9077 * @see android.widget.ScrollBarDrawable 9078 */ 9079 protected int computeVerticalScrollExtent() { 9080 return getHeight(); 9081 } 9082 9083 /** 9084 * Check if this view can be scrolled horizontally in a certain direction. 9085 * 9086 * @param direction Negative to check scrolling left, positive to check scrolling right. 9087 * @return true if this view can be scrolled in the specified direction, false otherwise. 9088 */ 9089 public boolean canScrollHorizontally(int direction) { 9090 final int offset = computeHorizontalScrollOffset(); 9091 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 9092 if (range == 0) return false; 9093 if (direction < 0) { 9094 return offset > 0; 9095 } else { 9096 return offset < range - 1; 9097 } 9098 } 9099 9100 /** 9101 * Check if this view can be scrolled vertically in a certain direction. 9102 * 9103 * @param direction Negative to check scrolling up, positive to check scrolling down. 9104 * @return true if this view can be scrolled in the specified direction, false otherwise. 9105 */ 9106 public boolean canScrollVertically(int direction) { 9107 final int offset = computeVerticalScrollOffset(); 9108 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 9109 if (range == 0) return false; 9110 if (direction < 0) { 9111 return offset > 0; 9112 } else { 9113 return offset < range - 1; 9114 } 9115 } 9116 9117 /** 9118 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 9119 * scrollbars are painted only if they have been awakened first.</p> 9120 * 9121 * @param canvas the canvas on which to draw the scrollbars 9122 * 9123 * @see #awakenScrollBars(int) 9124 */ 9125 protected final void onDrawScrollBars(Canvas canvas) { 9126 // scrollbars are drawn only when the animation is running 9127 final ScrollabilityCache cache = mScrollCache; 9128 if (cache != null) { 9129 9130 int state = cache.state; 9131 9132 if (state == ScrollabilityCache.OFF) { 9133 return; 9134 } 9135 9136 boolean invalidate = false; 9137 9138 if (state == ScrollabilityCache.FADING) { 9139 // We're fading -- get our fade interpolation 9140 if (cache.interpolatorValues == null) { 9141 cache.interpolatorValues = new float[1]; 9142 } 9143 9144 float[] values = cache.interpolatorValues; 9145 9146 // Stops the animation if we're done 9147 if (cache.scrollBarInterpolator.timeToValues(values) == 9148 Interpolator.Result.FREEZE_END) { 9149 cache.state = ScrollabilityCache.OFF; 9150 } else { 9151 cache.scrollBar.setAlpha(Math.round(values[0])); 9152 } 9153 9154 // This will make the scroll bars inval themselves after 9155 // drawing. We only want this when we're fading so that 9156 // we prevent excessive redraws 9157 invalidate = true; 9158 } else { 9159 // We're just on -- but we may have been fading before so 9160 // reset alpha 9161 cache.scrollBar.setAlpha(255); 9162 } 9163 9164 9165 final int viewFlags = mViewFlags; 9166 9167 final boolean drawHorizontalScrollBar = 9168 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 9169 final boolean drawVerticalScrollBar = 9170 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 9171 && !isVerticalScrollBarHidden(); 9172 9173 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 9174 final int width = mRight - mLeft; 9175 final int height = mBottom - mTop; 9176 9177 final ScrollBarDrawable scrollBar = cache.scrollBar; 9178 9179 final int scrollX = mScrollX; 9180 final int scrollY = mScrollY; 9181 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 9182 9183 int left, top, right, bottom; 9184 9185 if (drawHorizontalScrollBar) { 9186 int size = scrollBar.getSize(false); 9187 if (size <= 0) { 9188 size = cache.scrollBarSize; 9189 } 9190 9191 scrollBar.setParameters(computeHorizontalScrollRange(), 9192 computeHorizontalScrollOffset(), 9193 computeHorizontalScrollExtent(), false); 9194 final int verticalScrollBarGap = drawVerticalScrollBar ? 9195 getVerticalScrollbarWidth() : 0; 9196 top = scrollY + height - size - (mUserPaddingBottom & inside); 9197 left = scrollX + (mPaddingLeft & inside); 9198 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 9199 bottom = top + size; 9200 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 9201 if (invalidate) { 9202 invalidate(left, top, right, bottom); 9203 } 9204 } 9205 9206 if (drawVerticalScrollBar) { 9207 int size = scrollBar.getSize(true); 9208 if (size <= 0) { 9209 size = cache.scrollBarSize; 9210 } 9211 9212 scrollBar.setParameters(computeVerticalScrollRange(), 9213 computeVerticalScrollOffset(), 9214 computeVerticalScrollExtent(), true); 9215 switch (mVerticalScrollbarPosition) { 9216 default: 9217 case SCROLLBAR_POSITION_DEFAULT: 9218 case SCROLLBAR_POSITION_RIGHT: 9219 left = scrollX + width - size - (mUserPaddingRight & inside); 9220 break; 9221 case SCROLLBAR_POSITION_LEFT: 9222 left = scrollX + (mUserPaddingLeft & inside); 9223 break; 9224 } 9225 top = scrollY + (mPaddingTop & inside); 9226 right = left + size; 9227 bottom = scrollY + height - (mUserPaddingBottom & inside); 9228 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 9229 if (invalidate) { 9230 invalidate(left, top, right, bottom); 9231 } 9232 } 9233 } 9234 } 9235 } 9236 9237 /** 9238 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 9239 * FastScroller is visible. 9240 * @return whether to temporarily hide the vertical scrollbar 9241 * @hide 9242 */ 9243 protected boolean isVerticalScrollBarHidden() { 9244 return false; 9245 } 9246 9247 /** 9248 * <p>Draw the horizontal scrollbar if 9249 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 9250 * 9251 * @param canvas the canvas on which to draw the scrollbar 9252 * @param scrollBar the scrollbar's drawable 9253 * 9254 * @see #isHorizontalScrollBarEnabled() 9255 * @see #computeHorizontalScrollRange() 9256 * @see #computeHorizontalScrollExtent() 9257 * @see #computeHorizontalScrollOffset() 9258 * @see android.widget.ScrollBarDrawable 9259 * @hide 9260 */ 9261 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 9262 int l, int t, int r, int b) { 9263 scrollBar.setBounds(l, t, r, b); 9264 scrollBar.draw(canvas); 9265 } 9266 9267 /** 9268 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 9269 * returns true.</p> 9270 * 9271 * @param canvas the canvas on which to draw the scrollbar 9272 * @param scrollBar the scrollbar's drawable 9273 * 9274 * @see #isVerticalScrollBarEnabled() 9275 * @see #computeVerticalScrollRange() 9276 * @see #computeVerticalScrollExtent() 9277 * @see #computeVerticalScrollOffset() 9278 * @see android.widget.ScrollBarDrawable 9279 * @hide 9280 */ 9281 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 9282 int l, int t, int r, int b) { 9283 scrollBar.setBounds(l, t, r, b); 9284 scrollBar.draw(canvas); 9285 } 9286 9287 /** 9288 * Implement this to do your drawing. 9289 * 9290 * @param canvas the canvas on which the background will be drawn 9291 */ 9292 protected void onDraw(Canvas canvas) { 9293 } 9294 9295 /* 9296 * Caller is responsible for calling requestLayout if necessary. 9297 * (This allows addViewInLayout to not request a new layout.) 9298 */ 9299 void assignParent(ViewParent parent) { 9300 if (mParent == null) { 9301 mParent = parent; 9302 } else if (parent == null) { 9303 mParent = null; 9304 } else { 9305 throw new RuntimeException("view " + this + " being added, but" 9306 + " it already has a parent"); 9307 } 9308 } 9309 9310 /** 9311 * This is called when the view is attached to a window. At this point it 9312 * has a Surface and will start drawing. Note that this function is 9313 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 9314 * however it may be called any time before the first onDraw -- including 9315 * before or after {@link #onMeasure(int, int)}. 9316 * 9317 * @see #onDetachedFromWindow() 9318 */ 9319 protected void onAttachedToWindow() { 9320 if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) { 9321 mParent.requestTransparentRegion(this); 9322 } 9323 if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 9324 initialAwakenScrollBars(); 9325 mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH; 9326 } 9327 jumpDrawablesToCurrentState(); 9328 // Order is important here: LayoutDirection MUST be resolved before Padding 9329 // and TextDirection 9330 resolveLayoutDirectionIfNeeded(); 9331 resolvePadding(); 9332 resolveTextDirection(); 9333 if (isFocused()) { 9334 InputMethodManager imm = InputMethodManager.peekInstance(); 9335 imm.focusIn(this); 9336 } 9337 } 9338 9339 /** 9340 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 9341 * that the parent directionality can and will be resolved before its children. 9342 */ 9343 private void resolveLayoutDirectionIfNeeded() { 9344 // Do not resolve if it is not needed 9345 if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) == LAYOUT_DIRECTION_RESOLVED) return; 9346 9347 // Clear any previous layout direction resolution 9348 mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_RTL; 9349 9350 // Reset also TextDirection as a change into LayoutDirection may impact the selected 9351 // TextDirectionHeuristic 9352 resetResolvedTextDirection(); 9353 9354 // Set resolved depending on layout direction 9355 switch (getLayoutDirection()) { 9356 case LAYOUT_DIRECTION_INHERIT: 9357 // We cannot do the resolution if there is no parent 9358 if (mParent == null) return; 9359 9360 // If this is root view, no need to look at parent's layout dir. 9361 if (mParent instanceof ViewGroup) { 9362 ViewGroup viewGroup = ((ViewGroup) mParent); 9363 9364 // Check if the parent view group can resolve 9365 if (! viewGroup.canResolveLayoutDirection()) { 9366 return; 9367 } 9368 if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) { 9369 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL; 9370 } 9371 } 9372 break; 9373 case LAYOUT_DIRECTION_RTL: 9374 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL; 9375 break; 9376 case LAYOUT_DIRECTION_LOCALE: 9377 if(isLayoutDirectionRtl(Locale.getDefault())) { 9378 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL; 9379 } 9380 break; 9381 default: 9382 // Nothing to do, LTR by default 9383 } 9384 9385 // Set to resolved 9386 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED; 9387 } 9388 9389 /** 9390 * @hide 9391 */ 9392 protected void resolvePadding() { 9393 // If the user specified the absolute padding (either with android:padding or 9394 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise 9395 // use the default padding or the padding from the background drawable 9396 // (stored at this point in mPadding*) 9397 switch (getResolvedLayoutDirection()) { 9398 case LAYOUT_DIRECTION_RTL: 9399 // Start user padding override Right user padding. Otherwise, if Right user 9400 // padding is not defined, use the default Right padding. If Right user padding 9401 // is defined, just use it. 9402 if (mUserPaddingStart >= 0) { 9403 mUserPaddingRight = mUserPaddingStart; 9404 } else if (mUserPaddingRight < 0) { 9405 mUserPaddingRight = mPaddingRight; 9406 } 9407 if (mUserPaddingEnd >= 0) { 9408 mUserPaddingLeft = mUserPaddingEnd; 9409 } else if (mUserPaddingLeft < 0) { 9410 mUserPaddingLeft = mPaddingLeft; 9411 } 9412 break; 9413 case LAYOUT_DIRECTION_LTR: 9414 default: 9415 // Start user padding override Left user padding. Otherwise, if Left user 9416 // padding is not defined, use the default left padding. If Left user padding 9417 // is defined, just use it. 9418 if (mUserPaddingStart >= 0) { 9419 mUserPaddingLeft = mUserPaddingStart; 9420 } else if (mUserPaddingLeft < 0) { 9421 mUserPaddingLeft = mPaddingLeft; 9422 } 9423 if (mUserPaddingEnd >= 0) { 9424 mUserPaddingRight = mUserPaddingEnd; 9425 } else if (mUserPaddingRight < 0) { 9426 mUserPaddingRight = mPaddingRight; 9427 } 9428 } 9429 9430 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 9431 9432 recomputePadding(); 9433 } 9434 9435 /** 9436 * Return true if layout direction resolution can be done 9437 * 9438 * @hide 9439 */ 9440 protected boolean canResolveLayoutDirection() { 9441 switch (getLayoutDirection()) { 9442 case LAYOUT_DIRECTION_INHERIT: 9443 return (mParent != null); 9444 default: 9445 return true; 9446 } 9447 } 9448 9449 /** 9450 * Reset the resolved layout direction. 9451 * 9452 * Subclasses need to override this method to clear cached information that depends on the 9453 * resolved layout direction, or to inform child views that inherit their layout direction. 9454 * Overrides must also call the superclass implementation at the start of their implementation. 9455 * 9456 * @hide 9457 */ 9458 protected void resetResolvedLayoutDirection() { 9459 // Reset the current View resolution 9460 mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED; 9461 } 9462 9463 /** 9464 * Check if a Locale is corresponding to a RTL script. 9465 * 9466 * @param locale Locale to check 9467 * @return true if a Locale is corresponding to a RTL script. 9468 * 9469 * @hide 9470 */ 9471 protected static boolean isLayoutDirectionRtl(Locale locale) { 9472 return (LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE == 9473 LocaleUtil.getLayoutDirectionFromLocale(locale)); 9474 } 9475 9476 /** 9477 * This is called when the view is detached from a window. At this point it 9478 * no longer has a surface for drawing. 9479 * 9480 * @see #onAttachedToWindow() 9481 */ 9482 protected void onDetachedFromWindow() { 9483 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT; 9484 9485 removeUnsetPressCallback(); 9486 removeLongPressCallback(); 9487 removePerformClickCallback(); 9488 removeSendViewScrolledAccessibilityEventCallback(); 9489 9490 destroyDrawingCache(); 9491 9492 destroyLayer(); 9493 9494 if (mDisplayList != null) { 9495 mDisplayList.invalidate(); 9496 } 9497 9498 if (mAttachInfo != null) { 9499 mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_MSG, this); 9500 } 9501 9502 mCurrentAnimation = null; 9503 9504 resetResolvedLayoutDirection(); 9505 resetResolvedTextDirection(); 9506 } 9507 9508 /** 9509 * @return The number of times this view has been attached to a window 9510 */ 9511 protected int getWindowAttachCount() { 9512 return mWindowAttachCount; 9513 } 9514 9515 /** 9516 * Retrieve a unique token identifying the window this view is attached to. 9517 * @return Return the window's token for use in 9518 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 9519 */ 9520 public IBinder getWindowToken() { 9521 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 9522 } 9523 9524 /** 9525 * Retrieve a unique token identifying the top-level "real" window of 9526 * the window that this view is attached to. That is, this is like 9527 * {@link #getWindowToken}, except if the window this view in is a panel 9528 * window (attached to another containing window), then the token of 9529 * the containing window is returned instead. 9530 * 9531 * @return Returns the associated window token, either 9532 * {@link #getWindowToken()} or the containing window's token. 9533 */ 9534 public IBinder getApplicationWindowToken() { 9535 AttachInfo ai = mAttachInfo; 9536 if (ai != null) { 9537 IBinder appWindowToken = ai.mPanelParentWindowToken; 9538 if (appWindowToken == null) { 9539 appWindowToken = ai.mWindowToken; 9540 } 9541 return appWindowToken; 9542 } 9543 return null; 9544 } 9545 9546 /** 9547 * Retrieve private session object this view hierarchy is using to 9548 * communicate with the window manager. 9549 * @return the session object to communicate with the window manager 9550 */ 9551 /*package*/ IWindowSession getWindowSession() { 9552 return mAttachInfo != null ? mAttachInfo.mSession : null; 9553 } 9554 9555 /** 9556 * @param info the {@link android.view.View.AttachInfo} to associated with 9557 * this view 9558 */ 9559 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 9560 //System.out.println("Attached! " + this); 9561 mAttachInfo = info; 9562 mWindowAttachCount++; 9563 // We will need to evaluate the drawable state at least once. 9564 mPrivateFlags |= DRAWABLE_STATE_DIRTY; 9565 if (mFloatingTreeObserver != null) { 9566 info.mTreeObserver.merge(mFloatingTreeObserver); 9567 mFloatingTreeObserver = null; 9568 } 9569 if ((mPrivateFlags&SCROLL_CONTAINER) != 0) { 9570 mAttachInfo.mScrollContainers.add(this); 9571 mPrivateFlags |= SCROLL_CONTAINER_ADDED; 9572 } 9573 performCollectViewAttributes(visibility); 9574 onAttachedToWindow(); 9575 9576 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 9577 mOnAttachStateChangeListeners; 9578 if (listeners != null && listeners.size() > 0) { 9579 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 9580 // perform the dispatching. The iterator is a safe guard against listeners that 9581 // could mutate the list by calling the various add/remove methods. This prevents 9582 // the array from being modified while we iterate it. 9583 for (OnAttachStateChangeListener listener : listeners) { 9584 listener.onViewAttachedToWindow(this); 9585 } 9586 } 9587 9588 int vis = info.mWindowVisibility; 9589 if (vis != GONE) { 9590 onWindowVisibilityChanged(vis); 9591 } 9592 if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) { 9593 // If nobody has evaluated the drawable state yet, then do it now. 9594 refreshDrawableState(); 9595 } 9596 } 9597 9598 void dispatchDetachedFromWindow() { 9599 AttachInfo info = mAttachInfo; 9600 if (info != null) { 9601 int vis = info.mWindowVisibility; 9602 if (vis != GONE) { 9603 onWindowVisibilityChanged(GONE); 9604 } 9605 } 9606 9607 onDetachedFromWindow(); 9608 9609 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 9610 mOnAttachStateChangeListeners; 9611 if (listeners != null && listeners.size() > 0) { 9612 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 9613 // perform the dispatching. The iterator is a safe guard against listeners that 9614 // could mutate the list by calling the various add/remove methods. This prevents 9615 // the array from being modified while we iterate it. 9616 for (OnAttachStateChangeListener listener : listeners) { 9617 listener.onViewDetachedFromWindow(this); 9618 } 9619 } 9620 9621 if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) { 9622 mAttachInfo.mScrollContainers.remove(this); 9623 mPrivateFlags &= ~SCROLL_CONTAINER_ADDED; 9624 } 9625 9626 mAttachInfo = null; 9627 } 9628 9629 /** 9630 * Store this view hierarchy's frozen state into the given container. 9631 * 9632 * @param container The SparseArray in which to save the view's state. 9633 * 9634 * @see #restoreHierarchyState(android.util.SparseArray) 9635 * @see #dispatchSaveInstanceState(android.util.SparseArray) 9636 * @see #onSaveInstanceState() 9637 */ 9638 public void saveHierarchyState(SparseArray<Parcelable> container) { 9639 dispatchSaveInstanceState(container); 9640 } 9641 9642 /** 9643 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 9644 * this view and its children. May be overridden to modify how freezing happens to a 9645 * view's children; for example, some views may want to not store state for their children. 9646 * 9647 * @param container The SparseArray in which to save the view's state. 9648 * 9649 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 9650 * @see #saveHierarchyState(android.util.SparseArray) 9651 * @see #onSaveInstanceState() 9652 */ 9653 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 9654 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 9655 mPrivateFlags &= ~SAVE_STATE_CALLED; 9656 Parcelable state = onSaveInstanceState(); 9657 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) { 9658 throw new IllegalStateException( 9659 "Derived class did not call super.onSaveInstanceState()"); 9660 } 9661 if (state != null) { 9662 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 9663 // + ": " + state); 9664 container.put(mID, state); 9665 } 9666 } 9667 } 9668 9669 /** 9670 * Hook allowing a view to generate a representation of its internal state 9671 * that can later be used to create a new instance with that same state. 9672 * This state should only contain information that is not persistent or can 9673 * not be reconstructed later. For example, you will never store your 9674 * current position on screen because that will be computed again when a 9675 * new instance of the view is placed in its view hierarchy. 9676 * <p> 9677 * Some examples of things you may store here: the current cursor position 9678 * in a text view (but usually not the text itself since that is stored in a 9679 * content provider or other persistent storage), the currently selected 9680 * item in a list view. 9681 * 9682 * @return Returns a Parcelable object containing the view's current dynamic 9683 * state, or null if there is nothing interesting to save. The 9684 * default implementation returns null. 9685 * @see #onRestoreInstanceState(android.os.Parcelable) 9686 * @see #saveHierarchyState(android.util.SparseArray) 9687 * @see #dispatchSaveInstanceState(android.util.SparseArray) 9688 * @see #setSaveEnabled(boolean) 9689 */ 9690 protected Parcelable onSaveInstanceState() { 9691 mPrivateFlags |= SAVE_STATE_CALLED; 9692 return BaseSavedState.EMPTY_STATE; 9693 } 9694 9695 /** 9696 * Restore this view hierarchy's frozen state from the given container. 9697 * 9698 * @param container The SparseArray which holds previously frozen states. 9699 * 9700 * @see #saveHierarchyState(android.util.SparseArray) 9701 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 9702 * @see #onRestoreInstanceState(android.os.Parcelable) 9703 */ 9704 public void restoreHierarchyState(SparseArray<Parcelable> container) { 9705 dispatchRestoreInstanceState(container); 9706 } 9707 9708 /** 9709 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 9710 * state for this view and its children. May be overridden to modify how restoring 9711 * happens to a view's children; for example, some views may want to not store state 9712 * for their children. 9713 * 9714 * @param container The SparseArray which holds previously saved state. 9715 * 9716 * @see #dispatchSaveInstanceState(android.util.SparseArray) 9717 * @see #restoreHierarchyState(android.util.SparseArray) 9718 * @see #onRestoreInstanceState(android.os.Parcelable) 9719 */ 9720 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 9721 if (mID != NO_ID) { 9722 Parcelable state = container.get(mID); 9723 if (state != null) { 9724 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 9725 // + ": " + state); 9726 mPrivateFlags &= ~SAVE_STATE_CALLED; 9727 onRestoreInstanceState(state); 9728 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) { 9729 throw new IllegalStateException( 9730 "Derived class did not call super.onRestoreInstanceState()"); 9731 } 9732 } 9733 } 9734 } 9735 9736 /** 9737 * Hook allowing a view to re-apply a representation of its internal state that had previously 9738 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 9739 * null state. 9740 * 9741 * @param state The frozen state that had previously been returned by 9742 * {@link #onSaveInstanceState}. 9743 * 9744 * @see #onSaveInstanceState() 9745 * @see #restoreHierarchyState(android.util.SparseArray) 9746 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 9747 */ 9748 protected void onRestoreInstanceState(Parcelable state) { 9749 mPrivateFlags |= SAVE_STATE_CALLED; 9750 if (state != BaseSavedState.EMPTY_STATE && state != null) { 9751 throw new IllegalArgumentException("Wrong state class, expecting View State but " 9752 + "received " + state.getClass().toString() + " instead. This usually happens " 9753 + "when two views of different type have the same id in the same hierarchy. " 9754 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 9755 + "other views do not use the same id."); 9756 } 9757 } 9758 9759 /** 9760 * <p>Return the time at which the drawing of the view hierarchy started.</p> 9761 * 9762 * @return the drawing start time in milliseconds 9763 */ 9764 public long getDrawingTime() { 9765 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 9766 } 9767 9768 /** 9769 * <p>Enables or disables the duplication of the parent's state into this view. When 9770 * duplication is enabled, this view gets its drawable state from its parent rather 9771 * than from its own internal properties.</p> 9772 * 9773 * <p>Note: in the current implementation, setting this property to true after the 9774 * view was added to a ViewGroup might have no effect at all. This property should 9775 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 9776 * 9777 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 9778 * property is enabled, an exception will be thrown.</p> 9779 * 9780 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 9781 * parent, these states should not be affected by this method.</p> 9782 * 9783 * @param enabled True to enable duplication of the parent's drawable state, false 9784 * to disable it. 9785 * 9786 * @see #getDrawableState() 9787 * @see #isDuplicateParentStateEnabled() 9788 */ 9789 public void setDuplicateParentStateEnabled(boolean enabled) { 9790 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 9791 } 9792 9793 /** 9794 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 9795 * 9796 * @return True if this view's drawable state is duplicated from the parent, 9797 * false otherwise 9798 * 9799 * @see #getDrawableState() 9800 * @see #setDuplicateParentStateEnabled(boolean) 9801 */ 9802 public boolean isDuplicateParentStateEnabled() { 9803 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 9804 } 9805 9806 /** 9807 * <p>Specifies the type of layer backing this view. The layer can be 9808 * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or 9809 * {@link #LAYER_TYPE_HARDWARE hardware}.</p> 9810 * 9811 * <p>A layer is associated with an optional {@link android.graphics.Paint} 9812 * instance that controls how the layer is composed on screen. The following 9813 * properties of the paint are taken into account when composing the layer:</p> 9814 * <ul> 9815 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 9816 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 9817 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 9818 * </ul> 9819 * 9820 * <p>If this view has an alpha value set to < 1.0 by calling 9821 * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by 9822 * this view's alpha value. Calling {@link #setAlpha(float)} is therefore 9823 * equivalent to setting a hardware layer on this view and providing a paint with 9824 * the desired alpha value.<p> 9825 * 9826 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled}, 9827 * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware} 9828 * for more information on when and how to use layers.</p> 9829 * 9830 * @param layerType The ype of layer to use with this view, must be one of 9831 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 9832 * {@link #LAYER_TYPE_HARDWARE} 9833 * @param paint The paint used to compose the layer. This argument is optional 9834 * and can be null. It is ignored when the layer type is 9835 * {@link #LAYER_TYPE_NONE} 9836 * 9837 * @see #getLayerType() 9838 * @see #LAYER_TYPE_NONE 9839 * @see #LAYER_TYPE_SOFTWARE 9840 * @see #LAYER_TYPE_HARDWARE 9841 * @see #setAlpha(float) 9842 * 9843 * @attr ref android.R.styleable#View_layerType 9844 */ 9845 public void setLayerType(int layerType, Paint paint) { 9846 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 9847 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 9848 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 9849 } 9850 9851 if (layerType == mLayerType) { 9852 if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) { 9853 mLayerPaint = paint == null ? new Paint() : paint; 9854 invalidateParentCaches(); 9855 invalidate(true); 9856 } 9857 return; 9858 } 9859 9860 // Destroy any previous software drawing cache if needed 9861 switch (mLayerType) { 9862 case LAYER_TYPE_HARDWARE: 9863 destroyLayer(); 9864 // fall through - unaccelerated views may use software layer mechanism instead 9865 case LAYER_TYPE_SOFTWARE: 9866 destroyDrawingCache(); 9867 break; 9868 default: 9869 break; 9870 } 9871 9872 mLayerType = layerType; 9873 final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE; 9874 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 9875 mLocalDirtyRect = layerDisabled ? null : new Rect(); 9876 9877 invalidateParentCaches(); 9878 invalidate(true); 9879 } 9880 9881 /** 9882 * Indicates what type of layer is currently associated with this view. By default 9883 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 9884 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 9885 * for more information on the different types of layers. 9886 * 9887 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 9888 * {@link #LAYER_TYPE_HARDWARE} 9889 * 9890 * @see #setLayerType(int, android.graphics.Paint) 9891 * @see #buildLayer() 9892 * @see #LAYER_TYPE_NONE 9893 * @see #LAYER_TYPE_SOFTWARE 9894 * @see #LAYER_TYPE_HARDWARE 9895 */ 9896 public int getLayerType() { 9897 return mLayerType; 9898 } 9899 9900 /** 9901 * Forces this view's layer to be created and this view to be rendered 9902 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 9903 * invoking this method will have no effect. 9904 * 9905 * This method can for instance be used to render a view into its layer before 9906 * starting an animation. If this view is complex, rendering into the layer 9907 * before starting the animation will avoid skipping frames. 9908 * 9909 * @throws IllegalStateException If this view is not attached to a window 9910 * 9911 * @see #setLayerType(int, android.graphics.Paint) 9912 */ 9913 public void buildLayer() { 9914 if (mLayerType == LAYER_TYPE_NONE) return; 9915 9916 if (mAttachInfo == null) { 9917 throw new IllegalStateException("This view must be attached to a window first"); 9918 } 9919 9920 switch (mLayerType) { 9921 case LAYER_TYPE_HARDWARE: 9922 getHardwareLayer(); 9923 break; 9924 case LAYER_TYPE_SOFTWARE: 9925 buildDrawingCache(true); 9926 break; 9927 } 9928 } 9929 9930 /** 9931 * <p>Returns a hardware layer that can be used to draw this view again 9932 * without executing its draw method.</p> 9933 * 9934 * @return A HardwareLayer ready to render, or null if an error occurred. 9935 */ 9936 HardwareLayer getHardwareLayer() { 9937 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null || 9938 !mAttachInfo.mHardwareRenderer.isEnabled()) { 9939 return null; 9940 } 9941 9942 final int width = mRight - mLeft; 9943 final int height = mBottom - mTop; 9944 9945 if (width == 0 || height == 0) { 9946 return null; 9947 } 9948 9949 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) { 9950 if (mHardwareLayer == null) { 9951 mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer( 9952 width, height, isOpaque()); 9953 mLocalDirtyRect.setEmpty(); 9954 } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) { 9955 mHardwareLayer.resize(width, height); 9956 mLocalDirtyRect.setEmpty(); 9957 } 9958 9959 HardwareCanvas currentCanvas = mAttachInfo.mHardwareCanvas; 9960 final HardwareCanvas canvas = mHardwareLayer.start(currentCanvas); 9961 mAttachInfo.mHardwareCanvas = canvas; 9962 try { 9963 canvas.setViewport(width, height); 9964 canvas.onPreDraw(mLocalDirtyRect); 9965 mLocalDirtyRect.setEmpty(); 9966 9967 final int restoreCount = canvas.save(); 9968 9969 computeScroll(); 9970 canvas.translate(-mScrollX, -mScrollY); 9971 9972 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 9973 9974 // Fast path for layouts with no backgrounds 9975 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 9976 mPrivateFlags &= ~DIRTY_MASK; 9977 dispatchDraw(canvas); 9978 } else { 9979 draw(canvas); 9980 } 9981 9982 canvas.restoreToCount(restoreCount); 9983 } finally { 9984 canvas.onPostDraw(); 9985 mHardwareLayer.end(currentCanvas); 9986 mAttachInfo.mHardwareCanvas = currentCanvas; 9987 } 9988 } 9989 9990 return mHardwareLayer; 9991 } 9992 9993 boolean destroyLayer() { 9994 if (mHardwareLayer != null) { 9995 mHardwareLayer.destroy(); 9996 mHardwareLayer = null; 9997 return true; 9998 } 9999 return false; 10000 } 10001 10002 /** 10003 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 10004 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 10005 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 10006 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 10007 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 10008 * null.</p> 10009 * 10010 * <p>Enabling the drawing cache is similar to 10011 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 10012 * acceleration is turned off. When hardware acceleration is turned on, enabling the 10013 * drawing cache has no effect on rendering because the system uses a different mechanism 10014 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 10015 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 10016 * for information on how to enable software and hardware layers.</p> 10017 * 10018 * <p>This API can be used to manually generate 10019 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 10020 * {@link #getDrawingCache()}.</p> 10021 * 10022 * @param enabled true to enable the drawing cache, false otherwise 10023 * 10024 * @see #isDrawingCacheEnabled() 10025 * @see #getDrawingCache() 10026 * @see #buildDrawingCache() 10027 * @see #setLayerType(int, android.graphics.Paint) 10028 */ 10029 public void setDrawingCacheEnabled(boolean enabled) { 10030 mCachingFailed = false; 10031 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 10032 } 10033 10034 /** 10035 * <p>Indicates whether the drawing cache is enabled for this view.</p> 10036 * 10037 * @return true if the drawing cache is enabled 10038 * 10039 * @see #setDrawingCacheEnabled(boolean) 10040 * @see #getDrawingCache() 10041 */ 10042 @ViewDebug.ExportedProperty(category = "drawing") 10043 public boolean isDrawingCacheEnabled() { 10044 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 10045 } 10046 10047 /** 10048 * Debugging utility which recursively outputs the dirty state of a view and its 10049 * descendants. 10050 * 10051 * @hide 10052 */ 10053 @SuppressWarnings({"UnusedDeclaration"}) 10054 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 10055 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) + 10056 ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" + 10057 (mPrivateFlags & View.DRAWING_CACHE_VALID) + 10058 ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")"); 10059 if (clear) { 10060 mPrivateFlags &= clearMask; 10061 } 10062 if (this instanceof ViewGroup) { 10063 ViewGroup parent = (ViewGroup) this; 10064 final int count = parent.getChildCount(); 10065 for (int i = 0; i < count; i++) { 10066 final View child = parent.getChildAt(i); 10067 child.outputDirtyFlags(indent + " ", clear, clearMask); 10068 } 10069 } 10070 } 10071 10072 /** 10073 * This method is used by ViewGroup to cause its children to restore or recreate their 10074 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 10075 * to recreate its own display list, which would happen if it went through the normal 10076 * draw/dispatchDraw mechanisms. 10077 * 10078 * @hide 10079 */ 10080 protected void dispatchGetDisplayList() {} 10081 10082 /** 10083 * A view that is not attached or hardware accelerated cannot create a display list. 10084 * This method checks these conditions and returns the appropriate result. 10085 * 10086 * @return true if view has the ability to create a display list, false otherwise. 10087 * 10088 * @hide 10089 */ 10090 public boolean canHaveDisplayList() { 10091 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 10092 } 10093 10094 /** 10095 * <p>Returns a display list that can be used to draw this view again 10096 * without executing its draw method.</p> 10097 * 10098 * @return A DisplayList ready to replay, or null if caching is not enabled. 10099 * 10100 * @hide 10101 */ 10102 public DisplayList getDisplayList() { 10103 if (!canHaveDisplayList()) { 10104 return null; 10105 } 10106 10107 if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || 10108 mDisplayList == null || !mDisplayList.isValid() || 10109 mRecreateDisplayList)) { 10110 // Don't need to recreate the display list, just need to tell our 10111 // children to restore/recreate theirs 10112 if (mDisplayList != null && mDisplayList.isValid() && 10113 !mRecreateDisplayList) { 10114 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 10115 mPrivateFlags &= ~DIRTY_MASK; 10116 dispatchGetDisplayList(); 10117 10118 return mDisplayList; 10119 } 10120 10121 // If we got here, we're recreating it. Mark it as such to ensure that 10122 // we copy in child display lists into ours in drawChild() 10123 mRecreateDisplayList = true; 10124 if (mDisplayList == null) { 10125 mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList(); 10126 // If we're creating a new display list, make sure our parent gets invalidated 10127 // since they will need to recreate their display list to account for this 10128 // new child display list. 10129 invalidateParentCaches(); 10130 } 10131 10132 final HardwareCanvas canvas = mDisplayList.start(); 10133 try { 10134 int width = mRight - mLeft; 10135 int height = mBottom - mTop; 10136 10137 canvas.setViewport(width, height); 10138 // The dirty rect should always be null for a display list 10139 canvas.onPreDraw(null); 10140 10141 computeScroll(); 10142 canvas.translate(-mScrollX, -mScrollY); 10143 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 10144 mPrivateFlags &= ~DIRTY_MASK; 10145 10146 // Fast path for layouts with no backgrounds 10147 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 10148 dispatchDraw(canvas); 10149 } else { 10150 draw(canvas); 10151 } 10152 } finally { 10153 canvas.onPostDraw(); 10154 10155 mDisplayList.end(); 10156 } 10157 } else { 10158 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 10159 mPrivateFlags &= ~DIRTY_MASK; 10160 } 10161 10162 return mDisplayList; 10163 } 10164 10165 /** 10166 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 10167 * 10168 * @return A non-scaled bitmap representing this view or null if cache is disabled. 10169 * 10170 * @see #getDrawingCache(boolean) 10171 */ 10172 public Bitmap getDrawingCache() { 10173 return getDrawingCache(false); 10174 } 10175 10176 /** 10177 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 10178 * is null when caching is disabled. If caching is enabled and the cache is not ready, 10179 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 10180 * draw from the cache when the cache is enabled. To benefit from the cache, you must 10181 * request the drawing cache by calling this method and draw it on screen if the 10182 * returned bitmap is not null.</p> 10183 * 10184 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 10185 * this method will create a bitmap of the same size as this view. Because this bitmap 10186 * will be drawn scaled by the parent ViewGroup, the result on screen might show 10187 * scaling artifacts. To avoid such artifacts, you should call this method by setting 10188 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 10189 * size than the view. This implies that your application must be able to handle this 10190 * size.</p> 10191 * 10192 * @param autoScale Indicates whether the generated bitmap should be scaled based on 10193 * the current density of the screen when the application is in compatibility 10194 * mode. 10195 * 10196 * @return A bitmap representing this view or null if cache is disabled. 10197 * 10198 * @see #setDrawingCacheEnabled(boolean) 10199 * @see #isDrawingCacheEnabled() 10200 * @see #buildDrawingCache(boolean) 10201 * @see #destroyDrawingCache() 10202 */ 10203 public Bitmap getDrawingCache(boolean autoScale) { 10204 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 10205 return null; 10206 } 10207 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 10208 buildDrawingCache(autoScale); 10209 } 10210 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 10211 } 10212 10213 /** 10214 * <p>Frees the resources used by the drawing cache. If you call 10215 * {@link #buildDrawingCache()} manually without calling 10216 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 10217 * should cleanup the cache with this method afterwards.</p> 10218 * 10219 * @see #setDrawingCacheEnabled(boolean) 10220 * @see #buildDrawingCache() 10221 * @see #getDrawingCache() 10222 */ 10223 public void destroyDrawingCache() { 10224 if (mDrawingCache != null) { 10225 mDrawingCache.recycle(); 10226 mDrawingCache = null; 10227 } 10228 if (mUnscaledDrawingCache != null) { 10229 mUnscaledDrawingCache.recycle(); 10230 mUnscaledDrawingCache = null; 10231 } 10232 } 10233 10234 /** 10235 * Setting a solid background color for the drawing cache's bitmaps will improve 10236 * performance and memory usage. Note, though that this should only be used if this 10237 * view will always be drawn on top of a solid color. 10238 * 10239 * @param color The background color to use for the drawing cache's bitmap 10240 * 10241 * @see #setDrawingCacheEnabled(boolean) 10242 * @see #buildDrawingCache() 10243 * @see #getDrawingCache() 10244 */ 10245 public void setDrawingCacheBackgroundColor(int color) { 10246 if (color != mDrawingCacheBackgroundColor) { 10247 mDrawingCacheBackgroundColor = color; 10248 mPrivateFlags &= ~DRAWING_CACHE_VALID; 10249 } 10250 } 10251 10252 /** 10253 * @see #setDrawingCacheBackgroundColor(int) 10254 * 10255 * @return The background color to used for the drawing cache's bitmap 10256 */ 10257 public int getDrawingCacheBackgroundColor() { 10258 return mDrawingCacheBackgroundColor; 10259 } 10260 10261 /** 10262 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 10263 * 10264 * @see #buildDrawingCache(boolean) 10265 */ 10266 public void buildDrawingCache() { 10267 buildDrawingCache(false); 10268 } 10269 10270 /** 10271 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 10272 * 10273 * <p>If you call {@link #buildDrawingCache()} manually without calling 10274 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 10275 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 10276 * 10277 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 10278 * this method will create a bitmap of the same size as this view. Because this bitmap 10279 * will be drawn scaled by the parent ViewGroup, the result on screen might show 10280 * scaling artifacts. To avoid such artifacts, you should call this method by setting 10281 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 10282 * size than the view. This implies that your application must be able to handle this 10283 * size.</p> 10284 * 10285 * <p>You should avoid calling this method when hardware acceleration is enabled. If 10286 * you do not need the drawing cache bitmap, calling this method will increase memory 10287 * usage and cause the view to be rendered in software once, thus negatively impacting 10288 * performance.</p> 10289 * 10290 * @see #getDrawingCache() 10291 * @see #destroyDrawingCache() 10292 */ 10293 public void buildDrawingCache(boolean autoScale) { 10294 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ? 10295 mDrawingCache == null : mUnscaledDrawingCache == null)) { 10296 mCachingFailed = false; 10297 10298 if (ViewDebug.TRACE_HIERARCHY) { 10299 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE); 10300 } 10301 10302 int width = mRight - mLeft; 10303 int height = mBottom - mTop; 10304 10305 final AttachInfo attachInfo = mAttachInfo; 10306 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 10307 10308 if (autoScale && scalingRequired) { 10309 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 10310 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 10311 } 10312 10313 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 10314 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 10315 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 10316 10317 if (width <= 0 || height <= 0 || 10318 // Projected bitmap size in bytes 10319 (width * height * (opaque && !use32BitCache ? 2 : 4) > 10320 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) { 10321 destroyDrawingCache(); 10322 mCachingFailed = true; 10323 return; 10324 } 10325 10326 boolean clear = true; 10327 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 10328 10329 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 10330 Bitmap.Config quality; 10331 if (!opaque) { 10332 // Never pick ARGB_4444 because it looks awful 10333 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 10334 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 10335 case DRAWING_CACHE_QUALITY_AUTO: 10336 quality = Bitmap.Config.ARGB_8888; 10337 break; 10338 case DRAWING_CACHE_QUALITY_LOW: 10339 quality = Bitmap.Config.ARGB_8888; 10340 break; 10341 case DRAWING_CACHE_QUALITY_HIGH: 10342 quality = Bitmap.Config.ARGB_8888; 10343 break; 10344 default: 10345 quality = Bitmap.Config.ARGB_8888; 10346 break; 10347 } 10348 } else { 10349 // Optimization for translucent windows 10350 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 10351 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 10352 } 10353 10354 // Try to cleanup memory 10355 if (bitmap != null) bitmap.recycle(); 10356 10357 try { 10358 bitmap = Bitmap.createBitmap(width, height, quality); 10359 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 10360 if (autoScale) { 10361 mDrawingCache = bitmap; 10362 } else { 10363 mUnscaledDrawingCache = bitmap; 10364 } 10365 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 10366 } catch (OutOfMemoryError e) { 10367 // If there is not enough memory to create the bitmap cache, just 10368 // ignore the issue as bitmap caches are not required to draw the 10369 // view hierarchy 10370 if (autoScale) { 10371 mDrawingCache = null; 10372 } else { 10373 mUnscaledDrawingCache = null; 10374 } 10375 mCachingFailed = true; 10376 return; 10377 } 10378 10379 clear = drawingCacheBackgroundColor != 0; 10380 } 10381 10382 Canvas canvas; 10383 if (attachInfo != null) { 10384 canvas = attachInfo.mCanvas; 10385 if (canvas == null) { 10386 canvas = new Canvas(); 10387 } 10388 canvas.setBitmap(bitmap); 10389 // Temporarily clobber the cached Canvas in case one of our children 10390 // is also using a drawing cache. Without this, the children would 10391 // steal the canvas by attaching their own bitmap to it and bad, bad 10392 // thing would happen (invisible views, corrupted drawings, etc.) 10393 attachInfo.mCanvas = null; 10394 } else { 10395 // This case should hopefully never or seldom happen 10396 canvas = new Canvas(bitmap); 10397 } 10398 10399 if (clear) { 10400 bitmap.eraseColor(drawingCacheBackgroundColor); 10401 } 10402 10403 computeScroll(); 10404 final int restoreCount = canvas.save(); 10405 10406 if (autoScale && scalingRequired) { 10407 final float scale = attachInfo.mApplicationScale; 10408 canvas.scale(scale, scale); 10409 } 10410 10411 canvas.translate(-mScrollX, -mScrollY); 10412 10413 mPrivateFlags |= DRAWN; 10414 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 10415 mLayerType != LAYER_TYPE_NONE) { 10416 mPrivateFlags |= DRAWING_CACHE_VALID; 10417 } 10418 10419 // Fast path for layouts with no backgrounds 10420 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 10421 if (ViewDebug.TRACE_HIERARCHY) { 10422 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); 10423 } 10424 mPrivateFlags &= ~DIRTY_MASK; 10425 dispatchDraw(canvas); 10426 } else { 10427 draw(canvas); 10428 } 10429 10430 canvas.restoreToCount(restoreCount); 10431 canvas.setBitmap(null); 10432 10433 if (attachInfo != null) { 10434 // Restore the cached Canvas for our siblings 10435 attachInfo.mCanvas = canvas; 10436 } 10437 } 10438 } 10439 10440 /** 10441 * Create a snapshot of the view into a bitmap. We should probably make 10442 * some form of this public, but should think about the API. 10443 */ 10444 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 10445 int width = mRight - mLeft; 10446 int height = mBottom - mTop; 10447 10448 final AttachInfo attachInfo = mAttachInfo; 10449 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 10450 width = (int) ((width * scale) + 0.5f); 10451 height = (int) ((height * scale) + 0.5f); 10452 10453 Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality); 10454 if (bitmap == null) { 10455 throw new OutOfMemoryError(); 10456 } 10457 10458 Resources resources = getResources(); 10459 if (resources != null) { 10460 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 10461 } 10462 10463 Canvas canvas; 10464 if (attachInfo != null) { 10465 canvas = attachInfo.mCanvas; 10466 if (canvas == null) { 10467 canvas = new Canvas(); 10468 } 10469 canvas.setBitmap(bitmap); 10470 // Temporarily clobber the cached Canvas in case one of our children 10471 // is also using a drawing cache. Without this, the children would 10472 // steal the canvas by attaching their own bitmap to it and bad, bad 10473 // things would happen (invisible views, corrupted drawings, etc.) 10474 attachInfo.mCanvas = null; 10475 } else { 10476 // This case should hopefully never or seldom happen 10477 canvas = new Canvas(bitmap); 10478 } 10479 10480 if ((backgroundColor & 0xff000000) != 0) { 10481 bitmap.eraseColor(backgroundColor); 10482 } 10483 10484 computeScroll(); 10485 final int restoreCount = canvas.save(); 10486 canvas.scale(scale, scale); 10487 canvas.translate(-mScrollX, -mScrollY); 10488 10489 // Temporarily remove the dirty mask 10490 int flags = mPrivateFlags; 10491 mPrivateFlags &= ~DIRTY_MASK; 10492 10493 // Fast path for layouts with no backgrounds 10494 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 10495 dispatchDraw(canvas); 10496 } else { 10497 draw(canvas); 10498 } 10499 10500 mPrivateFlags = flags; 10501 10502 canvas.restoreToCount(restoreCount); 10503 canvas.setBitmap(null); 10504 10505 if (attachInfo != null) { 10506 // Restore the cached Canvas for our siblings 10507 attachInfo.mCanvas = canvas; 10508 } 10509 10510 return bitmap; 10511 } 10512 10513 /** 10514 * Indicates whether this View is currently in edit mode. A View is usually 10515 * in edit mode when displayed within a developer tool. For instance, if 10516 * this View is being drawn by a visual user interface builder, this method 10517 * should return true. 10518 * 10519 * Subclasses should check the return value of this method to provide 10520 * different behaviors if their normal behavior might interfere with the 10521 * host environment. For instance: the class spawns a thread in its 10522 * constructor, the drawing code relies on device-specific features, etc. 10523 * 10524 * This method is usually checked in the drawing code of custom widgets. 10525 * 10526 * @return True if this View is in edit mode, false otherwise. 10527 */ 10528 public boolean isInEditMode() { 10529 return false; 10530 } 10531 10532 /** 10533 * If the View draws content inside its padding and enables fading edges, 10534 * it needs to support padding offsets. Padding offsets are added to the 10535 * fading edges to extend the length of the fade so that it covers pixels 10536 * drawn inside the padding. 10537 * 10538 * Subclasses of this class should override this method if they need 10539 * to draw content inside the padding. 10540 * 10541 * @return True if padding offset must be applied, false otherwise. 10542 * 10543 * @see #getLeftPaddingOffset() 10544 * @see #getRightPaddingOffset() 10545 * @see #getTopPaddingOffset() 10546 * @see #getBottomPaddingOffset() 10547 * 10548 * @since CURRENT 10549 */ 10550 protected boolean isPaddingOffsetRequired() { 10551 return false; 10552 } 10553 10554 /** 10555 * Amount by which to extend the left fading region. Called only when 10556 * {@link #isPaddingOffsetRequired()} returns true. 10557 * 10558 * @return The left padding offset in pixels. 10559 * 10560 * @see #isPaddingOffsetRequired() 10561 * 10562 * @since CURRENT 10563 */ 10564 protected int getLeftPaddingOffset() { 10565 return 0; 10566 } 10567 10568 /** 10569 * Amount by which to extend the right fading region. Called only when 10570 * {@link #isPaddingOffsetRequired()} returns true. 10571 * 10572 * @return The right padding offset in pixels. 10573 * 10574 * @see #isPaddingOffsetRequired() 10575 * 10576 * @since CURRENT 10577 */ 10578 protected int getRightPaddingOffset() { 10579 return 0; 10580 } 10581 10582 /** 10583 * Amount by which to extend the top fading region. Called only when 10584 * {@link #isPaddingOffsetRequired()} returns true. 10585 * 10586 * @return The top padding offset in pixels. 10587 * 10588 * @see #isPaddingOffsetRequired() 10589 * 10590 * @since CURRENT 10591 */ 10592 protected int getTopPaddingOffset() { 10593 return 0; 10594 } 10595 10596 /** 10597 * Amount by which to extend the bottom fading region. Called only when 10598 * {@link #isPaddingOffsetRequired()} returns true. 10599 * 10600 * @return The bottom padding offset in pixels. 10601 * 10602 * @see #isPaddingOffsetRequired() 10603 * 10604 * @since CURRENT 10605 */ 10606 protected int getBottomPaddingOffset() { 10607 return 0; 10608 } 10609 10610 /** 10611 * @hide 10612 * @param offsetRequired 10613 */ 10614 protected int getFadeTop(boolean offsetRequired) { 10615 int top = mPaddingTop; 10616 if (offsetRequired) top += getTopPaddingOffset(); 10617 return top; 10618 } 10619 10620 /** 10621 * @hide 10622 * @param offsetRequired 10623 */ 10624 protected int getFadeHeight(boolean offsetRequired) { 10625 int padding = mPaddingTop; 10626 if (offsetRequired) padding += getTopPaddingOffset(); 10627 return mBottom - mTop - mPaddingBottom - padding; 10628 } 10629 10630 /** 10631 * <p>Indicates whether this view is attached to an hardware accelerated 10632 * window or not.</p> 10633 * 10634 * <p>Even if this method returns true, it does not mean that every call 10635 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 10636 * accelerated {@link android.graphics.Canvas}. For instance, if this view 10637 * is drawn onto an offscren {@link android.graphics.Bitmap} and its 10638 * window is hardware accelerated, 10639 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 10640 * return false, and this method will return true.</p> 10641 * 10642 * @return True if the view is attached to a window and the window is 10643 * hardware accelerated; false in any other case. 10644 */ 10645 public boolean isHardwareAccelerated() { 10646 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 10647 } 10648 10649 /** 10650 * Manually render this view (and all of its children) to the given Canvas. 10651 * The view must have already done a full layout before this function is 10652 * called. When implementing a view, implement 10653 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 10654 * If you do need to override this method, call the superclass version. 10655 * 10656 * @param canvas The Canvas to which the View is rendered. 10657 */ 10658 public void draw(Canvas canvas) { 10659 if (ViewDebug.TRACE_HIERARCHY) { 10660 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); 10661 } 10662 10663 final int privateFlags = mPrivateFlags; 10664 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE && 10665 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 10666 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN; 10667 10668 /* 10669 * Draw traversal performs several drawing steps which must be executed 10670 * in the appropriate order: 10671 * 10672 * 1. Draw the background 10673 * 2. If necessary, save the canvas' layers to prepare for fading 10674 * 3. Draw view's content 10675 * 4. Draw children 10676 * 5. If necessary, draw the fading edges and restore layers 10677 * 6. Draw decorations (scrollbars for instance) 10678 */ 10679 10680 // Step 1, draw the background, if needed 10681 int saveCount; 10682 10683 if (!dirtyOpaque) { 10684 final Drawable background = mBGDrawable; 10685 if (background != null) { 10686 final int scrollX = mScrollX; 10687 final int scrollY = mScrollY; 10688 10689 if (mBackgroundSizeChanged) { 10690 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 10691 mBackgroundSizeChanged = false; 10692 } 10693 10694 if ((scrollX | scrollY) == 0) { 10695 background.draw(canvas); 10696 } else { 10697 canvas.translate(scrollX, scrollY); 10698 background.draw(canvas); 10699 canvas.translate(-scrollX, -scrollY); 10700 } 10701 } 10702 } 10703 10704 // skip step 2 & 5 if possible (common case) 10705 final int viewFlags = mViewFlags; 10706 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 10707 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 10708 if (!verticalEdges && !horizontalEdges) { 10709 // Step 3, draw the content 10710 if (!dirtyOpaque) onDraw(canvas); 10711 10712 // Step 4, draw the children 10713 dispatchDraw(canvas); 10714 10715 // Step 6, draw decorations (scrollbars) 10716 onDrawScrollBars(canvas); 10717 10718 // we're done... 10719 return; 10720 } 10721 10722 /* 10723 * Here we do the full fledged routine... 10724 * (this is an uncommon case where speed matters less, 10725 * this is why we repeat some of the tests that have been 10726 * done above) 10727 */ 10728 10729 boolean drawTop = false; 10730 boolean drawBottom = false; 10731 boolean drawLeft = false; 10732 boolean drawRight = false; 10733 10734 float topFadeStrength = 0.0f; 10735 float bottomFadeStrength = 0.0f; 10736 float leftFadeStrength = 0.0f; 10737 float rightFadeStrength = 0.0f; 10738 10739 // Step 2, save the canvas' layers 10740 int paddingLeft = mPaddingLeft; 10741 10742 final boolean offsetRequired = isPaddingOffsetRequired(); 10743 if (offsetRequired) { 10744 paddingLeft += getLeftPaddingOffset(); 10745 } 10746 10747 int left = mScrollX + paddingLeft; 10748 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 10749 int top = mScrollY + getFadeTop(offsetRequired); 10750 int bottom = top + getFadeHeight(offsetRequired); 10751 10752 if (offsetRequired) { 10753 right += getRightPaddingOffset(); 10754 bottom += getBottomPaddingOffset(); 10755 } 10756 10757 final ScrollabilityCache scrollabilityCache = mScrollCache; 10758 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 10759 int length = (int) fadeHeight; 10760 10761 // clip the fade length if top and bottom fades overlap 10762 // overlapping fades produce odd-looking artifacts 10763 if (verticalEdges && (top + length > bottom - length)) { 10764 length = (bottom - top) / 2; 10765 } 10766 10767 // also clip horizontal fades if necessary 10768 if (horizontalEdges && (left + length > right - length)) { 10769 length = (right - left) / 2; 10770 } 10771 10772 if (verticalEdges) { 10773 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 10774 drawTop = topFadeStrength * fadeHeight > 1.0f; 10775 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 10776 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 10777 } 10778 10779 if (horizontalEdges) { 10780 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 10781 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 10782 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 10783 drawRight = rightFadeStrength * fadeHeight > 1.0f; 10784 } 10785 10786 saveCount = canvas.getSaveCount(); 10787 10788 int solidColor = getSolidColor(); 10789 if (solidColor == 0) { 10790 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 10791 10792 if (drawTop) { 10793 canvas.saveLayer(left, top, right, top + length, null, flags); 10794 } 10795 10796 if (drawBottom) { 10797 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 10798 } 10799 10800 if (drawLeft) { 10801 canvas.saveLayer(left, top, left + length, bottom, null, flags); 10802 } 10803 10804 if (drawRight) { 10805 canvas.saveLayer(right - length, top, right, bottom, null, flags); 10806 } 10807 } else { 10808 scrollabilityCache.setFadeColor(solidColor); 10809 } 10810 10811 // Step 3, draw the content 10812 if (!dirtyOpaque) onDraw(canvas); 10813 10814 // Step 4, draw the children 10815 dispatchDraw(canvas); 10816 10817 // Step 5, draw the fade effect and restore layers 10818 final Paint p = scrollabilityCache.paint; 10819 final Matrix matrix = scrollabilityCache.matrix; 10820 final Shader fade = scrollabilityCache.shader; 10821 10822 if (drawTop) { 10823 matrix.setScale(1, fadeHeight * topFadeStrength); 10824 matrix.postTranslate(left, top); 10825 fade.setLocalMatrix(matrix); 10826 canvas.drawRect(left, top, right, top + length, p); 10827 } 10828 10829 if (drawBottom) { 10830 matrix.setScale(1, fadeHeight * bottomFadeStrength); 10831 matrix.postRotate(180); 10832 matrix.postTranslate(left, bottom); 10833 fade.setLocalMatrix(matrix); 10834 canvas.drawRect(left, bottom - length, right, bottom, p); 10835 } 10836 10837 if (drawLeft) { 10838 matrix.setScale(1, fadeHeight * leftFadeStrength); 10839 matrix.postRotate(-90); 10840 matrix.postTranslate(left, top); 10841 fade.setLocalMatrix(matrix); 10842 canvas.drawRect(left, top, left + length, bottom, p); 10843 } 10844 10845 if (drawRight) { 10846 matrix.setScale(1, fadeHeight * rightFadeStrength); 10847 matrix.postRotate(90); 10848 matrix.postTranslate(right, top); 10849 fade.setLocalMatrix(matrix); 10850 canvas.drawRect(right - length, top, right, bottom, p); 10851 } 10852 10853 canvas.restoreToCount(saveCount); 10854 10855 // Step 6, draw decorations (scrollbars) 10856 onDrawScrollBars(canvas); 10857 } 10858 10859 /** 10860 * Override this if your view is known to always be drawn on top of a solid color background, 10861 * and needs to draw fading edges. Returning a non-zero color enables the view system to 10862 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 10863 * should be set to 0xFF. 10864 * 10865 * @see #setVerticalFadingEdgeEnabled(boolean) 10866 * @see #setHorizontalFadingEdgeEnabled(boolean) 10867 * 10868 * @return The known solid color background for this view, or 0 if the color may vary 10869 */ 10870 @ViewDebug.ExportedProperty(category = "drawing") 10871 public int getSolidColor() { 10872 return 0; 10873 } 10874 10875 /** 10876 * Build a human readable string representation of the specified view flags. 10877 * 10878 * @param flags the view flags to convert to a string 10879 * @return a String representing the supplied flags 10880 */ 10881 private static String printFlags(int flags) { 10882 String output = ""; 10883 int numFlags = 0; 10884 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 10885 output += "TAKES_FOCUS"; 10886 numFlags++; 10887 } 10888 10889 switch (flags & VISIBILITY_MASK) { 10890 case INVISIBLE: 10891 if (numFlags > 0) { 10892 output += " "; 10893 } 10894 output += "INVISIBLE"; 10895 // USELESS HERE numFlags++; 10896 break; 10897 case GONE: 10898 if (numFlags > 0) { 10899 output += " "; 10900 } 10901 output += "GONE"; 10902 // USELESS HERE numFlags++; 10903 break; 10904 default: 10905 break; 10906 } 10907 return output; 10908 } 10909 10910 /** 10911 * Build a human readable string representation of the specified private 10912 * view flags. 10913 * 10914 * @param privateFlags the private view flags to convert to a string 10915 * @return a String representing the supplied flags 10916 */ 10917 private static String printPrivateFlags(int privateFlags) { 10918 String output = ""; 10919 int numFlags = 0; 10920 10921 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) { 10922 output += "WANTS_FOCUS"; 10923 numFlags++; 10924 } 10925 10926 if ((privateFlags & FOCUSED) == FOCUSED) { 10927 if (numFlags > 0) { 10928 output += " "; 10929 } 10930 output += "FOCUSED"; 10931 numFlags++; 10932 } 10933 10934 if ((privateFlags & SELECTED) == SELECTED) { 10935 if (numFlags > 0) { 10936 output += " "; 10937 } 10938 output += "SELECTED"; 10939 numFlags++; 10940 } 10941 10942 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) { 10943 if (numFlags > 0) { 10944 output += " "; 10945 } 10946 output += "IS_ROOT_NAMESPACE"; 10947 numFlags++; 10948 } 10949 10950 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) { 10951 if (numFlags > 0) { 10952 output += " "; 10953 } 10954 output += "HAS_BOUNDS"; 10955 numFlags++; 10956 } 10957 10958 if ((privateFlags & DRAWN) == DRAWN) { 10959 if (numFlags > 0) { 10960 output += " "; 10961 } 10962 output += "DRAWN"; 10963 // USELESS HERE numFlags++; 10964 } 10965 return output; 10966 } 10967 10968 /** 10969 * <p>Indicates whether or not this view's layout will be requested during 10970 * the next hierarchy layout pass.</p> 10971 * 10972 * @return true if the layout will be forced during next layout pass 10973 */ 10974 public boolean isLayoutRequested() { 10975 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT; 10976 } 10977 10978 /** 10979 * Assign a size and position to a view and all of its 10980 * descendants 10981 * 10982 * <p>This is the second phase of the layout mechanism. 10983 * (The first is measuring). In this phase, each parent calls 10984 * layout on all of its children to position them. 10985 * This is typically done using the child measurements 10986 * that were stored in the measure pass().</p> 10987 * 10988 * <p>Derived classes should not override this method. 10989 * Derived classes with children should override 10990 * onLayout. In that method, they should 10991 * call layout on each of their children.</p> 10992 * 10993 * @param l Left position, relative to parent 10994 * @param t Top position, relative to parent 10995 * @param r Right position, relative to parent 10996 * @param b Bottom position, relative to parent 10997 */ 10998 @SuppressWarnings({"unchecked"}) 10999 public void layout(int l, int t, int r, int b) { 11000 int oldL = mLeft; 11001 int oldT = mTop; 11002 int oldB = mBottom; 11003 int oldR = mRight; 11004 boolean changed = setFrame(l, t, r, b); 11005 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) { 11006 if (ViewDebug.TRACE_HIERARCHY) { 11007 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT); 11008 } 11009 11010 onLayout(changed, l, t, r, b); 11011 mPrivateFlags &= ~LAYOUT_REQUIRED; 11012 11013 if (mOnLayoutChangeListeners != null) { 11014 ArrayList<OnLayoutChangeListener> listenersCopy = 11015 (ArrayList<OnLayoutChangeListener>) mOnLayoutChangeListeners.clone(); 11016 int numListeners = listenersCopy.size(); 11017 for (int i = 0; i < numListeners; ++i) { 11018 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 11019 } 11020 } 11021 } 11022 mPrivateFlags &= ~FORCE_LAYOUT; 11023 } 11024 11025 /** 11026 * Called from layout when this view should 11027 * assign a size and position to each of its children. 11028 * 11029 * Derived classes with children should override 11030 * this method and call layout on each of 11031 * their children. 11032 * @param changed This is a new size or position for this view 11033 * @param left Left position, relative to parent 11034 * @param top Top position, relative to parent 11035 * @param right Right position, relative to parent 11036 * @param bottom Bottom position, relative to parent 11037 */ 11038 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 11039 } 11040 11041 /** 11042 * Assign a size and position to this view. 11043 * 11044 * This is called from layout. 11045 * 11046 * @param left Left position, relative to parent 11047 * @param top Top position, relative to parent 11048 * @param right Right position, relative to parent 11049 * @param bottom Bottom position, relative to parent 11050 * @return true if the new size and position are different than the 11051 * previous ones 11052 * {@hide} 11053 */ 11054 protected boolean setFrame(int left, int top, int right, int bottom) { 11055 boolean changed = false; 11056 11057 if (DBG) { 11058 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 11059 + right + "," + bottom + ")"); 11060 } 11061 11062 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 11063 changed = true; 11064 11065 // Remember our drawn bit 11066 int drawn = mPrivateFlags & DRAWN; 11067 11068 int oldWidth = mRight - mLeft; 11069 int oldHeight = mBottom - mTop; 11070 int newWidth = right - left; 11071 int newHeight = bottom - top; 11072 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 11073 11074 // Invalidate our old position 11075 invalidate(sizeChanged); 11076 11077 mLeft = left; 11078 mTop = top; 11079 mRight = right; 11080 mBottom = bottom; 11081 11082 mPrivateFlags |= HAS_BOUNDS; 11083 11084 11085 if (sizeChanged) { 11086 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 11087 // A change in dimension means an auto-centered pivot point changes, too 11088 mMatrixDirty = true; 11089 } 11090 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 11091 } 11092 11093 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 11094 // If we are visible, force the DRAWN bit to on so that 11095 // this invalidate will go through (at least to our parent). 11096 // This is because someone may have invalidated this view 11097 // before this call to setFrame came in, thereby clearing 11098 // the DRAWN bit. 11099 mPrivateFlags |= DRAWN; 11100 invalidate(sizeChanged); 11101 // parent display list may need to be recreated based on a change in the bounds 11102 // of any child 11103 invalidateParentCaches(); 11104 } 11105 11106 // Reset drawn bit to original value (invalidate turns it off) 11107 mPrivateFlags |= drawn; 11108 11109 mBackgroundSizeChanged = true; 11110 } 11111 return changed; 11112 } 11113 11114 /** 11115 * Finalize inflating a view from XML. This is called as the last phase 11116 * of inflation, after all child views have been added. 11117 * 11118 * <p>Even if the subclass overrides onFinishInflate, they should always be 11119 * sure to call the super method, so that we get called. 11120 */ 11121 protected void onFinishInflate() { 11122 } 11123 11124 /** 11125 * Returns the resources associated with this view. 11126 * 11127 * @return Resources object. 11128 */ 11129 public Resources getResources() { 11130 return mResources; 11131 } 11132 11133 /** 11134 * Invalidates the specified Drawable. 11135 * 11136 * @param drawable the drawable to invalidate 11137 */ 11138 public void invalidateDrawable(Drawable drawable) { 11139 if (verifyDrawable(drawable)) { 11140 final Rect dirty = drawable.getBounds(); 11141 final int scrollX = mScrollX; 11142 final int scrollY = mScrollY; 11143 11144 invalidate(dirty.left + scrollX, dirty.top + scrollY, 11145 dirty.right + scrollX, dirty.bottom + scrollY); 11146 } 11147 } 11148 11149 /** 11150 * Schedules an action on a drawable to occur at a specified time. 11151 * 11152 * @param who the recipient of the action 11153 * @param what the action to run on the drawable 11154 * @param when the time at which the action must occur. Uses the 11155 * {@link SystemClock#uptimeMillis} timebase. 11156 */ 11157 public void scheduleDrawable(Drawable who, Runnable what, long when) { 11158 if (verifyDrawable(who) && what != null && mAttachInfo != null) { 11159 mAttachInfo.mHandler.postAtTime(what, who, when); 11160 } 11161 } 11162 11163 /** 11164 * Cancels a scheduled action on a drawable. 11165 * 11166 * @param who the recipient of the action 11167 * @param what the action to cancel 11168 */ 11169 public void unscheduleDrawable(Drawable who, Runnable what) { 11170 if (verifyDrawable(who) && what != null && mAttachInfo != null) { 11171 mAttachInfo.mHandler.removeCallbacks(what, who); 11172 } 11173 } 11174 11175 /** 11176 * Unschedule any events associated with the given Drawable. This can be 11177 * used when selecting a new Drawable into a view, so that the previous 11178 * one is completely unscheduled. 11179 * 11180 * @param who The Drawable to unschedule. 11181 * 11182 * @see #drawableStateChanged 11183 */ 11184 public void unscheduleDrawable(Drawable who) { 11185 if (mAttachInfo != null) { 11186 mAttachInfo.mHandler.removeCallbacksAndMessages(who); 11187 } 11188 } 11189 11190 /** 11191 * Return the layout direction of a given Drawable. 11192 * 11193 * @param who the Drawable to query 11194 * 11195 * @hide 11196 */ 11197 public int getResolvedLayoutDirection(Drawable who) { 11198 return (who == mBGDrawable) ? getResolvedLayoutDirection() : LAYOUT_DIRECTION_DEFAULT; 11199 } 11200 11201 /** 11202 * If your view subclass is displaying its own Drawable objects, it should 11203 * override this function and return true for any Drawable it is 11204 * displaying. This allows animations for those drawables to be 11205 * scheduled. 11206 * 11207 * <p>Be sure to call through to the super class when overriding this 11208 * function. 11209 * 11210 * @param who The Drawable to verify. Return true if it is one you are 11211 * displaying, else return the result of calling through to the 11212 * super class. 11213 * 11214 * @return boolean If true than the Drawable is being displayed in the 11215 * view; else false and it is not allowed to animate. 11216 * 11217 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 11218 * @see #drawableStateChanged() 11219 */ 11220 protected boolean verifyDrawable(Drawable who) { 11221 return who == mBGDrawable; 11222 } 11223 11224 /** 11225 * This function is called whenever the state of the view changes in such 11226 * a way that it impacts the state of drawables being shown. 11227 * 11228 * <p>Be sure to call through to the superclass when overriding this 11229 * function. 11230 * 11231 * @see Drawable#setState(int[]) 11232 */ 11233 protected void drawableStateChanged() { 11234 Drawable d = mBGDrawable; 11235 if (d != null && d.isStateful()) { 11236 d.setState(getDrawableState()); 11237 } 11238 } 11239 11240 /** 11241 * Call this to force a view to update its drawable state. This will cause 11242 * drawableStateChanged to be called on this view. Views that are interested 11243 * in the new state should call getDrawableState. 11244 * 11245 * @see #drawableStateChanged 11246 * @see #getDrawableState 11247 */ 11248 public void refreshDrawableState() { 11249 mPrivateFlags |= DRAWABLE_STATE_DIRTY; 11250 drawableStateChanged(); 11251 11252 ViewParent parent = mParent; 11253 if (parent != null) { 11254 parent.childDrawableStateChanged(this); 11255 } 11256 } 11257 11258 /** 11259 * Return an array of resource IDs of the drawable states representing the 11260 * current state of the view. 11261 * 11262 * @return The current drawable state 11263 * 11264 * @see Drawable#setState(int[]) 11265 * @see #drawableStateChanged() 11266 * @see #onCreateDrawableState(int) 11267 */ 11268 public final int[] getDrawableState() { 11269 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) { 11270 return mDrawableState; 11271 } else { 11272 mDrawableState = onCreateDrawableState(0); 11273 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY; 11274 return mDrawableState; 11275 } 11276 } 11277 11278 /** 11279 * Generate the new {@link android.graphics.drawable.Drawable} state for 11280 * this view. This is called by the view 11281 * system when the cached Drawable state is determined to be invalid. To 11282 * retrieve the current state, you should use {@link #getDrawableState}. 11283 * 11284 * @param extraSpace if non-zero, this is the number of extra entries you 11285 * would like in the returned array in which you can place your own 11286 * states. 11287 * 11288 * @return Returns an array holding the current {@link Drawable} state of 11289 * the view. 11290 * 11291 * @see #mergeDrawableStates(int[], int[]) 11292 */ 11293 protected int[] onCreateDrawableState(int extraSpace) { 11294 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 11295 mParent instanceof View) { 11296 return ((View) mParent).onCreateDrawableState(extraSpace); 11297 } 11298 11299 int[] drawableState; 11300 11301 int privateFlags = mPrivateFlags; 11302 11303 int viewStateIndex = 0; 11304 if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 11305 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 11306 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 11307 if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 11308 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 11309 if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 11310 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 11311 HardwareRenderer.isAvailable()) { 11312 // This is set if HW acceleration is requested, even if the current 11313 // process doesn't allow it. This is just to allow app preview 11314 // windows to better match their app. 11315 viewStateIndex |= VIEW_STATE_ACCELERATED; 11316 } 11317 if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 11318 11319 final int privateFlags2 = mPrivateFlags2; 11320 if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 11321 if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 11322 11323 drawableState = VIEW_STATE_SETS[viewStateIndex]; 11324 11325 //noinspection ConstantIfStatement 11326 if (false) { 11327 Log.i("View", "drawableStateIndex=" + viewStateIndex); 11328 Log.i("View", toString() 11329 + " pressed=" + ((privateFlags & PRESSED) != 0) 11330 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 11331 + " fo=" + hasFocus() 11332 + " sl=" + ((privateFlags & SELECTED) != 0) 11333 + " wf=" + hasWindowFocus() 11334 + ": " + Arrays.toString(drawableState)); 11335 } 11336 11337 if (extraSpace == 0) { 11338 return drawableState; 11339 } 11340 11341 final int[] fullState; 11342 if (drawableState != null) { 11343 fullState = new int[drawableState.length + extraSpace]; 11344 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 11345 } else { 11346 fullState = new int[extraSpace]; 11347 } 11348 11349 return fullState; 11350 } 11351 11352 /** 11353 * Merge your own state values in <var>additionalState</var> into the base 11354 * state values <var>baseState</var> that were returned by 11355 * {@link #onCreateDrawableState(int)}. 11356 * 11357 * @param baseState The base state values returned by 11358 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 11359 * own additional state values. 11360 * 11361 * @param additionalState The additional state values you would like 11362 * added to <var>baseState</var>; this array is not modified. 11363 * 11364 * @return As a convenience, the <var>baseState</var> array you originally 11365 * passed into the function is returned. 11366 * 11367 * @see #onCreateDrawableState(int) 11368 */ 11369 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 11370 final int N = baseState.length; 11371 int i = N - 1; 11372 while (i >= 0 && baseState[i] == 0) { 11373 i--; 11374 } 11375 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 11376 return baseState; 11377 } 11378 11379 /** 11380 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 11381 * on all Drawable objects associated with this view. 11382 */ 11383 public void jumpDrawablesToCurrentState() { 11384 if (mBGDrawable != null) { 11385 mBGDrawable.jumpToCurrentState(); 11386 } 11387 } 11388 11389 /** 11390 * Sets the background color for this view. 11391 * @param color the color of the background 11392 */ 11393 @RemotableViewMethod 11394 public void setBackgroundColor(int color) { 11395 if (mBGDrawable instanceof ColorDrawable) { 11396 ((ColorDrawable) mBGDrawable).setColor(color); 11397 } else { 11398 setBackgroundDrawable(new ColorDrawable(color)); 11399 } 11400 } 11401 11402 /** 11403 * Set the background to a given resource. The resource should refer to 11404 * a Drawable object or 0 to remove the background. 11405 * @param resid The identifier of the resource. 11406 * @attr ref android.R.styleable#View_background 11407 */ 11408 @RemotableViewMethod 11409 public void setBackgroundResource(int resid) { 11410 if (resid != 0 && resid == mBackgroundResource) { 11411 return; 11412 } 11413 11414 Drawable d= null; 11415 if (resid != 0) { 11416 d = mResources.getDrawable(resid); 11417 } 11418 setBackgroundDrawable(d); 11419 11420 mBackgroundResource = resid; 11421 } 11422 11423 /** 11424 * Set the background to a given Drawable, or remove the background. If the 11425 * background has padding, this View's padding is set to the background's 11426 * padding. However, when a background is removed, this View's padding isn't 11427 * touched. If setting the padding is desired, please use 11428 * {@link #setPadding(int, int, int, int)}. 11429 * 11430 * @param d The Drawable to use as the background, or null to remove the 11431 * background 11432 */ 11433 public void setBackgroundDrawable(Drawable d) { 11434 if (d == mBGDrawable) { 11435 return; 11436 } 11437 11438 boolean requestLayout = false; 11439 11440 mBackgroundResource = 0; 11441 11442 /* 11443 * Regardless of whether we're setting a new background or not, we want 11444 * to clear the previous drawable. 11445 */ 11446 if (mBGDrawable != null) { 11447 mBGDrawable.setCallback(null); 11448 unscheduleDrawable(mBGDrawable); 11449 } 11450 11451 if (d != null) { 11452 Rect padding = sThreadLocal.get(); 11453 if (padding == null) { 11454 padding = new Rect(); 11455 sThreadLocal.set(padding); 11456 } 11457 if (d.getPadding(padding)) { 11458 switch (d.getResolvedLayoutDirectionSelf()) { 11459 case LAYOUT_DIRECTION_RTL: 11460 setPadding(padding.right, padding.top, padding.left, padding.bottom); 11461 break; 11462 case LAYOUT_DIRECTION_LTR: 11463 default: 11464 setPadding(padding.left, padding.top, padding.right, padding.bottom); 11465 } 11466 } 11467 11468 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 11469 // if it has a different minimum size, we should layout again 11470 if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() || 11471 mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) { 11472 requestLayout = true; 11473 } 11474 11475 d.setCallback(this); 11476 if (d.isStateful()) { 11477 d.setState(getDrawableState()); 11478 } 11479 d.setVisible(getVisibility() == VISIBLE, false); 11480 mBGDrawable = d; 11481 11482 if ((mPrivateFlags & SKIP_DRAW) != 0) { 11483 mPrivateFlags &= ~SKIP_DRAW; 11484 mPrivateFlags |= ONLY_DRAWS_BACKGROUND; 11485 requestLayout = true; 11486 } 11487 } else { 11488 /* Remove the background */ 11489 mBGDrawable = null; 11490 11491 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) { 11492 /* 11493 * This view ONLY drew the background before and we're removing 11494 * the background, so now it won't draw anything 11495 * (hence we SKIP_DRAW) 11496 */ 11497 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND; 11498 mPrivateFlags |= SKIP_DRAW; 11499 } 11500 11501 /* 11502 * When the background is set, we try to apply its padding to this 11503 * View. When the background is removed, we don't touch this View's 11504 * padding. This is noted in the Javadocs. Hence, we don't need to 11505 * requestLayout(), the invalidate() below is sufficient. 11506 */ 11507 11508 // The old background's minimum size could have affected this 11509 // View's layout, so let's requestLayout 11510 requestLayout = true; 11511 } 11512 11513 computeOpaqueFlags(); 11514 11515 if (requestLayout) { 11516 requestLayout(); 11517 } 11518 11519 mBackgroundSizeChanged = true; 11520 invalidate(true); 11521 } 11522 11523 /** 11524 * Gets the background drawable 11525 * @return The drawable used as the background for this view, if any. 11526 */ 11527 public Drawable getBackground() { 11528 return mBGDrawable; 11529 } 11530 11531 /** 11532 * Sets the padding. The view may add on the space required to display 11533 * the scrollbars, depending on the style and visibility of the scrollbars. 11534 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 11535 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 11536 * from the values set in this call. 11537 * 11538 * @attr ref android.R.styleable#View_padding 11539 * @attr ref android.R.styleable#View_paddingBottom 11540 * @attr ref android.R.styleable#View_paddingLeft 11541 * @attr ref android.R.styleable#View_paddingRight 11542 * @attr ref android.R.styleable#View_paddingTop 11543 * @param left the left padding in pixels 11544 * @param top the top padding in pixels 11545 * @param right the right padding in pixels 11546 * @param bottom the bottom padding in pixels 11547 */ 11548 public void setPadding(int left, int top, int right, int bottom) { 11549 boolean changed = false; 11550 11551 mUserPaddingRelative = false; 11552 11553 mUserPaddingLeft = left; 11554 mUserPaddingRight = right; 11555 mUserPaddingBottom = bottom; 11556 11557 final int viewFlags = mViewFlags; 11558 11559 // Common case is there are no scroll bars. 11560 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 11561 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 11562 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 11563 ? 0 : getVerticalScrollbarWidth(); 11564 switch (mVerticalScrollbarPosition) { 11565 case SCROLLBAR_POSITION_DEFAULT: 11566 if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) { 11567 left += offset; 11568 } else { 11569 right += offset; 11570 } 11571 break; 11572 case SCROLLBAR_POSITION_RIGHT: 11573 right += offset; 11574 break; 11575 case SCROLLBAR_POSITION_LEFT: 11576 left += offset; 11577 break; 11578 } 11579 } 11580 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 11581 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 11582 ? 0 : getHorizontalScrollbarHeight(); 11583 } 11584 } 11585 11586 if (mPaddingLeft != left) { 11587 changed = true; 11588 mPaddingLeft = left; 11589 } 11590 if (mPaddingTop != top) { 11591 changed = true; 11592 mPaddingTop = top; 11593 } 11594 if (mPaddingRight != right) { 11595 changed = true; 11596 mPaddingRight = right; 11597 } 11598 if (mPaddingBottom != bottom) { 11599 changed = true; 11600 mPaddingBottom = bottom; 11601 } 11602 11603 if (changed) { 11604 requestLayout(); 11605 } 11606 } 11607 11608 /** 11609 * Sets the relative padding. The view may add on the space required to display 11610 * the scrollbars, depending on the style and visibility of the scrollbars. 11611 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 11612 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 11613 * from the values set in this call. 11614 * 11615 * @attr ref android.R.styleable#View_padding 11616 * @attr ref android.R.styleable#View_paddingBottom 11617 * @attr ref android.R.styleable#View_paddingStart 11618 * @attr ref android.R.styleable#View_paddingEnd 11619 * @attr ref android.R.styleable#View_paddingTop 11620 * @param start the start padding in pixels 11621 * @param top the top padding in pixels 11622 * @param end the end padding in pixels 11623 * @param bottom the bottom padding in pixels 11624 * 11625 * @hide 11626 */ 11627 public void setPaddingRelative(int start, int top, int end, int bottom) { 11628 mUserPaddingRelative = true; 11629 11630 mUserPaddingStart = start; 11631 mUserPaddingEnd = end; 11632 11633 switch(getResolvedLayoutDirection()) { 11634 case LAYOUT_DIRECTION_RTL: 11635 setPadding(end, top, start, bottom); 11636 break; 11637 case LAYOUT_DIRECTION_LTR: 11638 default: 11639 setPadding(start, top, end, bottom); 11640 } 11641 } 11642 11643 /** 11644 * Returns the top padding of this view. 11645 * 11646 * @return the top padding in pixels 11647 */ 11648 public int getPaddingTop() { 11649 return mPaddingTop; 11650 } 11651 11652 /** 11653 * Returns the bottom padding of this view. If there are inset and enabled 11654 * scrollbars, this value may include the space required to display the 11655 * scrollbars as well. 11656 * 11657 * @return the bottom padding in pixels 11658 */ 11659 public int getPaddingBottom() { 11660 return mPaddingBottom; 11661 } 11662 11663 /** 11664 * Returns the left padding of this view. If there are inset and enabled 11665 * scrollbars, this value may include the space required to display the 11666 * scrollbars as well. 11667 * 11668 * @return the left padding in pixels 11669 */ 11670 public int getPaddingLeft() { 11671 return mPaddingLeft; 11672 } 11673 11674 /** 11675 * Returns the start padding of this view. If there are inset and enabled 11676 * scrollbars, this value may include the space required to display the 11677 * scrollbars as well. 11678 * 11679 * @return the start padding in pixels 11680 * 11681 * @hide 11682 */ 11683 public int getPaddingStart() { 11684 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 11685 mPaddingRight : mPaddingLeft; 11686 } 11687 11688 /** 11689 * Returns the right padding of this view. If there are inset and enabled 11690 * scrollbars, this value may include the space required to display the 11691 * scrollbars as well. 11692 * 11693 * @return the right padding in pixels 11694 */ 11695 public int getPaddingRight() { 11696 return mPaddingRight; 11697 } 11698 11699 /** 11700 * Returns the end padding of this view. If there are inset and enabled 11701 * scrollbars, this value may include the space required to display the 11702 * scrollbars as well. 11703 * 11704 * @return the end padding in pixels 11705 * 11706 * @hide 11707 */ 11708 public int getPaddingEnd() { 11709 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 11710 mPaddingLeft : mPaddingRight; 11711 } 11712 11713 /** 11714 * Return if the padding as been set thru relative values 11715 * {@link #setPaddingRelative(int, int, int, int)} or thru 11716 * @attr ref android.R.styleable#View_paddingStart or 11717 * @attr ref android.R.styleable#View_paddingEnd 11718 * 11719 * @return true if the padding is relative or false if it is not. 11720 * 11721 * @hide 11722 */ 11723 public boolean isPaddingRelative() { 11724 return mUserPaddingRelative; 11725 } 11726 11727 /** 11728 * Changes the selection state of this view. A view can be selected or not. 11729 * Note that selection is not the same as focus. Views are typically 11730 * selected in the context of an AdapterView like ListView or GridView; 11731 * the selected view is the view that is highlighted. 11732 * 11733 * @param selected true if the view must be selected, false otherwise 11734 */ 11735 public void setSelected(boolean selected) { 11736 if (((mPrivateFlags & SELECTED) != 0) != selected) { 11737 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0); 11738 if (!selected) resetPressedState(); 11739 invalidate(true); 11740 refreshDrawableState(); 11741 dispatchSetSelected(selected); 11742 } 11743 } 11744 11745 /** 11746 * Dispatch setSelected to all of this View's children. 11747 * 11748 * @see #setSelected(boolean) 11749 * 11750 * @param selected The new selected state 11751 */ 11752 protected void dispatchSetSelected(boolean selected) { 11753 } 11754 11755 /** 11756 * Indicates the selection state of this view. 11757 * 11758 * @return true if the view is selected, false otherwise 11759 */ 11760 @ViewDebug.ExportedProperty 11761 public boolean isSelected() { 11762 return (mPrivateFlags & SELECTED) != 0; 11763 } 11764 11765 /** 11766 * Changes the activated state of this view. A view can be activated or not. 11767 * Note that activation is not the same as selection. Selection is 11768 * a transient property, representing the view (hierarchy) the user is 11769 * currently interacting with. Activation is a longer-term state that the 11770 * user can move views in and out of. For example, in a list view with 11771 * single or multiple selection enabled, the views in the current selection 11772 * set are activated. (Um, yeah, we are deeply sorry about the terminology 11773 * here.) The activated state is propagated down to children of the view it 11774 * is set on. 11775 * 11776 * @param activated true if the view must be activated, false otherwise 11777 */ 11778 public void setActivated(boolean activated) { 11779 if (((mPrivateFlags & ACTIVATED) != 0) != activated) { 11780 mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0); 11781 invalidate(true); 11782 refreshDrawableState(); 11783 dispatchSetActivated(activated); 11784 } 11785 } 11786 11787 /** 11788 * Dispatch setActivated to all of this View's children. 11789 * 11790 * @see #setActivated(boolean) 11791 * 11792 * @param activated The new activated state 11793 */ 11794 protected void dispatchSetActivated(boolean activated) { 11795 } 11796 11797 /** 11798 * Indicates the activation state of this view. 11799 * 11800 * @return true if the view is activated, false otherwise 11801 */ 11802 @ViewDebug.ExportedProperty 11803 public boolean isActivated() { 11804 return (mPrivateFlags & ACTIVATED) != 0; 11805 } 11806 11807 /** 11808 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 11809 * observer can be used to get notifications when global events, like 11810 * layout, happen. 11811 * 11812 * The returned ViewTreeObserver observer is not guaranteed to remain 11813 * valid for the lifetime of this View. If the caller of this method keeps 11814 * a long-lived reference to ViewTreeObserver, it should always check for 11815 * the return value of {@link ViewTreeObserver#isAlive()}. 11816 * 11817 * @return The ViewTreeObserver for this view's hierarchy. 11818 */ 11819 public ViewTreeObserver getViewTreeObserver() { 11820 if (mAttachInfo != null) { 11821 return mAttachInfo.mTreeObserver; 11822 } 11823 if (mFloatingTreeObserver == null) { 11824 mFloatingTreeObserver = new ViewTreeObserver(); 11825 } 11826 return mFloatingTreeObserver; 11827 } 11828 11829 /** 11830 * <p>Finds the topmost view in the current view hierarchy.</p> 11831 * 11832 * @return the topmost view containing this view 11833 */ 11834 public View getRootView() { 11835 if (mAttachInfo != null) { 11836 final View v = mAttachInfo.mRootView; 11837 if (v != null) { 11838 return v; 11839 } 11840 } 11841 11842 View parent = this; 11843 11844 while (parent.mParent != null && parent.mParent instanceof View) { 11845 parent = (View) parent.mParent; 11846 } 11847 11848 return parent; 11849 } 11850 11851 /** 11852 * <p>Computes the coordinates of this view on the screen. The argument 11853 * must be an array of two integers. After the method returns, the array 11854 * contains the x and y location in that order.</p> 11855 * 11856 * @param location an array of two integers in which to hold the coordinates 11857 */ 11858 public void getLocationOnScreen(int[] location) { 11859 getLocationInWindow(location); 11860 11861 final AttachInfo info = mAttachInfo; 11862 if (info != null) { 11863 location[0] += info.mWindowLeft; 11864 location[1] += info.mWindowTop; 11865 } 11866 } 11867 11868 /** 11869 * <p>Computes the coordinates of this view in its window. The argument 11870 * must be an array of two integers. After the method returns, the array 11871 * contains the x and y location in that order.</p> 11872 * 11873 * @param location an array of two integers in which to hold the coordinates 11874 */ 11875 public void getLocationInWindow(int[] location) { 11876 if (location == null || location.length < 2) { 11877 throw new IllegalArgumentException("location must be an array of " 11878 + "two integers"); 11879 } 11880 11881 location[0] = mLeft + (int) (mTranslationX + 0.5f); 11882 location[1] = mTop + (int) (mTranslationY + 0.5f); 11883 11884 ViewParent viewParent = mParent; 11885 while (viewParent instanceof View) { 11886 final View view = (View)viewParent; 11887 location[0] += view.mLeft + (int) (view.mTranslationX + 0.5f) - view.mScrollX; 11888 location[1] += view.mTop + (int) (view.mTranslationY + 0.5f) - view.mScrollY; 11889 viewParent = view.mParent; 11890 } 11891 11892 if (viewParent instanceof ViewRootImpl) { 11893 // *cough* 11894 final ViewRootImpl vr = (ViewRootImpl)viewParent; 11895 location[1] -= vr.mCurScrollY; 11896 } 11897 } 11898 11899 /** 11900 * {@hide} 11901 * @param id the id of the view to be found 11902 * @return the view of the specified id, null if cannot be found 11903 */ 11904 protected View findViewTraversal(int id) { 11905 if (id == mID) { 11906 return this; 11907 } 11908 return null; 11909 } 11910 11911 /** 11912 * {@hide} 11913 * @param tag the tag of the view to be found 11914 * @return the view of specified tag, null if cannot be found 11915 */ 11916 protected View findViewWithTagTraversal(Object tag) { 11917 if (tag != null && tag.equals(mTag)) { 11918 return this; 11919 } 11920 return null; 11921 } 11922 11923 /** 11924 * {@hide} 11925 * @param predicate The predicate to evaluate. 11926 * @param childToSkip If not null, ignores this child during the recursive traversal. 11927 * @return The first view that matches the predicate or null. 11928 */ 11929 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 11930 if (predicate.apply(this)) { 11931 return this; 11932 } 11933 return null; 11934 } 11935 11936 /** 11937 * Look for a child view with the given id. If this view has the given 11938 * id, return this view. 11939 * 11940 * @param id The id to search for. 11941 * @return The view that has the given id in the hierarchy or null 11942 */ 11943 public final View findViewById(int id) { 11944 if (id < 0) { 11945 return null; 11946 } 11947 return findViewTraversal(id); 11948 } 11949 11950 /** 11951 * Look for a child view with the given tag. If this view has the given 11952 * tag, return this view. 11953 * 11954 * @param tag The tag to search for, using "tag.equals(getTag())". 11955 * @return The View that has the given tag in the hierarchy or null 11956 */ 11957 public final View findViewWithTag(Object tag) { 11958 if (tag == null) { 11959 return null; 11960 } 11961 return findViewWithTagTraversal(tag); 11962 } 11963 11964 /** 11965 * {@hide} 11966 * Look for a child view that matches the specified predicate. 11967 * If this view matches the predicate, return this view. 11968 * 11969 * @param predicate The predicate to evaluate. 11970 * @return The first view that matches the predicate or null. 11971 */ 11972 public final View findViewByPredicate(Predicate<View> predicate) { 11973 return findViewByPredicateTraversal(predicate, null); 11974 } 11975 11976 /** 11977 * {@hide} 11978 * Look for a child view that matches the specified predicate, 11979 * starting with the specified view and its descendents and then 11980 * recusively searching the ancestors and siblings of that view 11981 * until this view is reached. 11982 * 11983 * This method is useful in cases where the predicate does not match 11984 * a single unique view (perhaps multiple views use the same id) 11985 * and we are trying to find the view that is "closest" in scope to the 11986 * starting view. 11987 * 11988 * @param start The view to start from. 11989 * @param predicate The predicate to evaluate. 11990 * @return The first view that matches the predicate or null. 11991 */ 11992 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 11993 View childToSkip = null; 11994 for (;;) { 11995 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 11996 if (view != null || start == this) { 11997 return view; 11998 } 11999 12000 ViewParent parent = start.getParent(); 12001 if (parent == null || !(parent instanceof View)) { 12002 return null; 12003 } 12004 12005 childToSkip = start; 12006 start = (View) parent; 12007 } 12008 } 12009 12010 /** 12011 * Sets the identifier for this view. The identifier does not have to be 12012 * unique in this view's hierarchy. The identifier should be a positive 12013 * number. 12014 * 12015 * @see #NO_ID 12016 * @see #getId() 12017 * @see #findViewById(int) 12018 * 12019 * @param id a number used to identify the view 12020 * 12021 * @attr ref android.R.styleable#View_id 12022 */ 12023 public void setId(int id) { 12024 mID = id; 12025 } 12026 12027 /** 12028 * {@hide} 12029 * 12030 * @param isRoot true if the view belongs to the root namespace, false 12031 * otherwise 12032 */ 12033 public void setIsRootNamespace(boolean isRoot) { 12034 if (isRoot) { 12035 mPrivateFlags |= IS_ROOT_NAMESPACE; 12036 } else { 12037 mPrivateFlags &= ~IS_ROOT_NAMESPACE; 12038 } 12039 } 12040 12041 /** 12042 * {@hide} 12043 * 12044 * @return true if the view belongs to the root namespace, false otherwise 12045 */ 12046 public boolean isRootNamespace() { 12047 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0; 12048 } 12049 12050 /** 12051 * Returns this view's identifier. 12052 * 12053 * @return a positive integer used to identify the view or {@link #NO_ID} 12054 * if the view has no ID 12055 * 12056 * @see #setId(int) 12057 * @see #findViewById(int) 12058 * @attr ref android.R.styleable#View_id 12059 */ 12060 @ViewDebug.CapturedViewProperty 12061 public int getId() { 12062 return mID; 12063 } 12064 12065 /** 12066 * Returns this view's tag. 12067 * 12068 * @return the Object stored in this view as a tag 12069 * 12070 * @see #setTag(Object) 12071 * @see #getTag(int) 12072 */ 12073 @ViewDebug.ExportedProperty 12074 public Object getTag() { 12075 return mTag; 12076 } 12077 12078 /** 12079 * Sets the tag associated with this view. A tag can be used to mark 12080 * a view in its hierarchy and does not have to be unique within the 12081 * hierarchy. Tags can also be used to store data within a view without 12082 * resorting to another data structure. 12083 * 12084 * @param tag an Object to tag the view with 12085 * 12086 * @see #getTag() 12087 * @see #setTag(int, Object) 12088 */ 12089 public void setTag(final Object tag) { 12090 mTag = tag; 12091 } 12092 12093 /** 12094 * Returns the tag associated with this view and the specified key. 12095 * 12096 * @param key The key identifying the tag 12097 * 12098 * @return the Object stored in this view as a tag 12099 * 12100 * @see #setTag(int, Object) 12101 * @see #getTag() 12102 */ 12103 public Object getTag(int key) { 12104 SparseArray<Object> tags = null; 12105 synchronized (sTagsLock) { 12106 if (sTags != null) { 12107 tags = sTags.get(this); 12108 } 12109 } 12110 12111 if (tags != null) return tags.get(key); 12112 return null; 12113 } 12114 12115 /** 12116 * Sets a tag associated with this view and a key. A tag can be used 12117 * to mark a view in its hierarchy and does not have to be unique within 12118 * the hierarchy. Tags can also be used to store data within a view 12119 * without resorting to another data structure. 12120 * 12121 * The specified key should be an id declared in the resources of the 12122 * application to ensure it is unique (see the <a 12123 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 12124 * Keys identified as belonging to 12125 * the Android framework or not associated with any package will cause 12126 * an {@link IllegalArgumentException} to be thrown. 12127 * 12128 * @param key The key identifying the tag 12129 * @param tag An Object to tag the view with 12130 * 12131 * @throws IllegalArgumentException If they specified key is not valid 12132 * 12133 * @see #setTag(Object) 12134 * @see #getTag(int) 12135 */ 12136 public void setTag(int key, final Object tag) { 12137 // If the package id is 0x00 or 0x01, it's either an undefined package 12138 // or a framework id 12139 if ((key >>> 24) < 2) { 12140 throw new IllegalArgumentException("The key must be an application-specific " 12141 + "resource id."); 12142 } 12143 12144 setTagInternal(this, key, tag); 12145 } 12146 12147 /** 12148 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 12149 * framework id. 12150 * 12151 * @hide 12152 */ 12153 public void setTagInternal(int key, Object tag) { 12154 if ((key >>> 24) != 0x1) { 12155 throw new IllegalArgumentException("The key must be a framework-specific " 12156 + "resource id."); 12157 } 12158 12159 setTagInternal(this, key, tag); 12160 } 12161 12162 private static void setTagInternal(View view, int key, Object tag) { 12163 SparseArray<Object> tags = null; 12164 synchronized (sTagsLock) { 12165 if (sTags == null) { 12166 sTags = new WeakHashMap<View, SparseArray<Object>>(); 12167 } else { 12168 tags = sTags.get(view); 12169 } 12170 } 12171 12172 if (tags == null) { 12173 tags = new SparseArray<Object>(2); 12174 synchronized (sTagsLock) { 12175 sTags.put(view, tags); 12176 } 12177 } 12178 12179 tags.put(key, tag); 12180 } 12181 12182 /** 12183 * @param consistency The type of consistency. See ViewDebug for more information. 12184 * 12185 * @hide 12186 */ 12187 protected boolean dispatchConsistencyCheck(int consistency) { 12188 return onConsistencyCheck(consistency); 12189 } 12190 12191 /** 12192 * Method that subclasses should implement to check their consistency. The type of 12193 * consistency check is indicated by the bit field passed as a parameter. 12194 * 12195 * @param consistency The type of consistency. See ViewDebug for more information. 12196 * 12197 * @throws IllegalStateException if the view is in an inconsistent state. 12198 * 12199 * @hide 12200 */ 12201 protected boolean onConsistencyCheck(int consistency) { 12202 boolean result = true; 12203 12204 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0; 12205 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0; 12206 12207 if (checkLayout) { 12208 if (getParent() == null) { 12209 result = false; 12210 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 12211 "View " + this + " does not have a parent."); 12212 } 12213 12214 if (mAttachInfo == null) { 12215 result = false; 12216 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 12217 "View " + this + " is not attached to a window."); 12218 } 12219 } 12220 12221 if (checkDrawing) { 12222 // Do not check the DIRTY/DRAWN flags because views can call invalidate() 12223 // from their draw() method 12224 12225 if ((mPrivateFlags & DRAWN) != DRAWN && 12226 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) { 12227 result = false; 12228 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 12229 "View " + this + " was invalidated but its drawing cache is valid."); 12230 } 12231 } 12232 12233 return result; 12234 } 12235 12236 /** 12237 * Prints information about this view in the log output, with the tag 12238 * {@link #VIEW_LOG_TAG}. 12239 * 12240 * @hide 12241 */ 12242 public void debug() { 12243 debug(0); 12244 } 12245 12246 /** 12247 * Prints information about this view in the log output, with the tag 12248 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 12249 * indentation defined by the <code>depth</code>. 12250 * 12251 * @param depth the indentation level 12252 * 12253 * @hide 12254 */ 12255 protected void debug(int depth) { 12256 String output = debugIndent(depth - 1); 12257 12258 output += "+ " + this; 12259 int id = getId(); 12260 if (id != -1) { 12261 output += " (id=" + id + ")"; 12262 } 12263 Object tag = getTag(); 12264 if (tag != null) { 12265 output += " (tag=" + tag + ")"; 12266 } 12267 Log.d(VIEW_LOG_TAG, output); 12268 12269 if ((mPrivateFlags & FOCUSED) != 0) { 12270 output = debugIndent(depth) + " FOCUSED"; 12271 Log.d(VIEW_LOG_TAG, output); 12272 } 12273 12274 output = debugIndent(depth); 12275 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 12276 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 12277 + "} "; 12278 Log.d(VIEW_LOG_TAG, output); 12279 12280 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 12281 || mPaddingBottom != 0) { 12282 output = debugIndent(depth); 12283 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 12284 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 12285 Log.d(VIEW_LOG_TAG, output); 12286 } 12287 12288 output = debugIndent(depth); 12289 output += "mMeasureWidth=" + mMeasuredWidth + 12290 " mMeasureHeight=" + mMeasuredHeight; 12291 Log.d(VIEW_LOG_TAG, output); 12292 12293 output = debugIndent(depth); 12294 if (mLayoutParams == null) { 12295 output += "BAD! no layout params"; 12296 } else { 12297 output = mLayoutParams.debug(output); 12298 } 12299 Log.d(VIEW_LOG_TAG, output); 12300 12301 output = debugIndent(depth); 12302 output += "flags={"; 12303 output += View.printFlags(mViewFlags); 12304 output += "}"; 12305 Log.d(VIEW_LOG_TAG, output); 12306 12307 output = debugIndent(depth); 12308 output += "privateFlags={"; 12309 output += View.printPrivateFlags(mPrivateFlags); 12310 output += "}"; 12311 Log.d(VIEW_LOG_TAG, output); 12312 } 12313 12314 /** 12315 * Creates an string of whitespaces used for indentation. 12316 * 12317 * @param depth the indentation level 12318 * @return a String containing (depth * 2 + 3) * 2 white spaces 12319 * 12320 * @hide 12321 */ 12322 protected static String debugIndent(int depth) { 12323 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 12324 for (int i = 0; i < (depth * 2) + 3; i++) { 12325 spaces.append(' ').append(' '); 12326 } 12327 return spaces.toString(); 12328 } 12329 12330 /** 12331 * <p>Return the offset of the widget's text baseline from the widget's top 12332 * boundary. If this widget does not support baseline alignment, this 12333 * method returns -1. </p> 12334 * 12335 * @return the offset of the baseline within the widget's bounds or -1 12336 * if baseline alignment is not supported 12337 */ 12338 @ViewDebug.ExportedProperty(category = "layout") 12339 public int getBaseline() { 12340 return -1; 12341 } 12342 12343 /** 12344 * Call this when something has changed which has invalidated the 12345 * layout of this view. This will schedule a layout pass of the view 12346 * tree. 12347 */ 12348 public void requestLayout() { 12349 if (ViewDebug.TRACE_HIERARCHY) { 12350 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT); 12351 } 12352 12353 mPrivateFlags |= FORCE_LAYOUT; 12354 mPrivateFlags |= INVALIDATED; 12355 12356 if (mParent != null) { 12357 if (mLayoutParams != null) { 12358 mLayoutParams.resolveWithDirection(getResolvedLayoutDirection()); 12359 } 12360 if (!mParent.isLayoutRequested()) { 12361 mParent.requestLayout(); 12362 } 12363 } 12364 } 12365 12366 /** 12367 * Forces this view to be laid out during the next layout pass. 12368 * This method does not call requestLayout() or forceLayout() 12369 * on the parent. 12370 */ 12371 public void forceLayout() { 12372 mPrivateFlags |= FORCE_LAYOUT; 12373 mPrivateFlags |= INVALIDATED; 12374 } 12375 12376 /** 12377 * <p> 12378 * This is called to find out how big a view should be. The parent 12379 * supplies constraint information in the width and height parameters. 12380 * </p> 12381 * 12382 * <p> 12383 * The actual mesurement work of a view is performed in 12384 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 12385 * {@link #onMeasure(int, int)} can and must be overriden by subclasses. 12386 * </p> 12387 * 12388 * 12389 * @param widthMeasureSpec Horizontal space requirements as imposed by the 12390 * parent 12391 * @param heightMeasureSpec Vertical space requirements as imposed by the 12392 * parent 12393 * 12394 * @see #onMeasure(int, int) 12395 */ 12396 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 12397 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT || 12398 widthMeasureSpec != mOldWidthMeasureSpec || 12399 heightMeasureSpec != mOldHeightMeasureSpec) { 12400 12401 // first clears the measured dimension flag 12402 mPrivateFlags &= ~MEASURED_DIMENSION_SET; 12403 12404 if (ViewDebug.TRACE_HIERARCHY) { 12405 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE); 12406 } 12407 12408 // measure ourselves, this should set the measured dimension flag back 12409 onMeasure(widthMeasureSpec, heightMeasureSpec); 12410 12411 // flag not set, setMeasuredDimension() was not invoked, we raise 12412 // an exception to warn the developer 12413 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) { 12414 throw new IllegalStateException("onMeasure() did not set the" 12415 + " measured dimension by calling" 12416 + " setMeasuredDimension()"); 12417 } 12418 12419 mPrivateFlags |= LAYOUT_REQUIRED; 12420 } 12421 12422 mOldWidthMeasureSpec = widthMeasureSpec; 12423 mOldHeightMeasureSpec = heightMeasureSpec; 12424 } 12425 12426 /** 12427 * <p> 12428 * Measure the view and its content to determine the measured width and the 12429 * measured height. This method is invoked by {@link #measure(int, int)} and 12430 * should be overriden by subclasses to provide accurate and efficient 12431 * measurement of their contents. 12432 * </p> 12433 * 12434 * <p> 12435 * <strong>CONTRACT:</strong> When overriding this method, you 12436 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 12437 * measured width and height of this view. Failure to do so will trigger an 12438 * <code>IllegalStateException</code>, thrown by 12439 * {@link #measure(int, int)}. Calling the superclass' 12440 * {@link #onMeasure(int, int)} is a valid use. 12441 * </p> 12442 * 12443 * <p> 12444 * The base class implementation of measure defaults to the background size, 12445 * unless a larger size is allowed by the MeasureSpec. Subclasses should 12446 * override {@link #onMeasure(int, int)} to provide better measurements of 12447 * their content. 12448 * </p> 12449 * 12450 * <p> 12451 * If this method is overridden, it is the subclass's responsibility to make 12452 * sure the measured height and width are at least the view's minimum height 12453 * and width ({@link #getSuggestedMinimumHeight()} and 12454 * {@link #getSuggestedMinimumWidth()}). 12455 * </p> 12456 * 12457 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 12458 * The requirements are encoded with 12459 * {@link android.view.View.MeasureSpec}. 12460 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 12461 * The requirements are encoded with 12462 * {@link android.view.View.MeasureSpec}. 12463 * 12464 * @see #getMeasuredWidth() 12465 * @see #getMeasuredHeight() 12466 * @see #setMeasuredDimension(int, int) 12467 * @see #getSuggestedMinimumHeight() 12468 * @see #getSuggestedMinimumWidth() 12469 * @see android.view.View.MeasureSpec#getMode(int) 12470 * @see android.view.View.MeasureSpec#getSize(int) 12471 */ 12472 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 12473 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 12474 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 12475 } 12476 12477 /** 12478 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the 12479 * measured width and measured height. Failing to do so will trigger an 12480 * exception at measurement time.</p> 12481 * 12482 * @param measuredWidth The measured width of this view. May be a complex 12483 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 12484 * {@link #MEASURED_STATE_TOO_SMALL}. 12485 * @param measuredHeight The measured height of this view. May be a complex 12486 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 12487 * {@link #MEASURED_STATE_TOO_SMALL}. 12488 */ 12489 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 12490 mMeasuredWidth = measuredWidth; 12491 mMeasuredHeight = measuredHeight; 12492 12493 mPrivateFlags |= MEASURED_DIMENSION_SET; 12494 } 12495 12496 /** 12497 * Merge two states as returned by {@link #getMeasuredState()}. 12498 * @param curState The current state as returned from a view or the result 12499 * of combining multiple views. 12500 * @param newState The new view state to combine. 12501 * @return Returns a new integer reflecting the combination of the two 12502 * states. 12503 */ 12504 public static int combineMeasuredStates(int curState, int newState) { 12505 return curState | newState; 12506 } 12507 12508 /** 12509 * Version of {@link #resolveSizeAndState(int, int, int)} 12510 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 12511 */ 12512 public static int resolveSize(int size, int measureSpec) { 12513 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 12514 } 12515 12516 /** 12517 * Utility to reconcile a desired size and state, with constraints imposed 12518 * by a MeasureSpec. Will take the desired size, unless a different size 12519 * is imposed by the constraints. The returned value is a compound integer, 12520 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 12521 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 12522 * size is smaller than the size the view wants to be. 12523 * 12524 * @param size How big the view wants to be 12525 * @param measureSpec Constraints imposed by the parent 12526 * @return Size information bit mask as defined by 12527 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 12528 */ 12529 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 12530 int result = size; 12531 int specMode = MeasureSpec.getMode(measureSpec); 12532 int specSize = MeasureSpec.getSize(measureSpec); 12533 switch (specMode) { 12534 case MeasureSpec.UNSPECIFIED: 12535 result = size; 12536 break; 12537 case MeasureSpec.AT_MOST: 12538 if (specSize < size) { 12539 result = specSize | MEASURED_STATE_TOO_SMALL; 12540 } else { 12541 result = size; 12542 } 12543 break; 12544 case MeasureSpec.EXACTLY: 12545 result = specSize; 12546 break; 12547 } 12548 return result | (childMeasuredState&MEASURED_STATE_MASK); 12549 } 12550 12551 /** 12552 * Utility to return a default size. Uses the supplied size if the 12553 * MeasureSpec imposed no constraints. Will get larger if allowed 12554 * by the MeasureSpec. 12555 * 12556 * @param size Default size for this view 12557 * @param measureSpec Constraints imposed by the parent 12558 * @return The size this view should be. 12559 */ 12560 public static int getDefaultSize(int size, int measureSpec) { 12561 int result = size; 12562 int specMode = MeasureSpec.getMode(measureSpec); 12563 int specSize = MeasureSpec.getSize(measureSpec); 12564 12565 switch (specMode) { 12566 case MeasureSpec.UNSPECIFIED: 12567 result = size; 12568 break; 12569 case MeasureSpec.AT_MOST: 12570 case MeasureSpec.EXACTLY: 12571 result = specSize; 12572 break; 12573 } 12574 return result; 12575 } 12576 12577 /** 12578 * Returns the suggested minimum height that the view should use. This 12579 * returns the maximum of the view's minimum height 12580 * and the background's minimum height 12581 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 12582 * <p> 12583 * When being used in {@link #onMeasure(int, int)}, the caller should still 12584 * ensure the returned height is within the requirements of the parent. 12585 * 12586 * @return The suggested minimum height of the view. 12587 */ 12588 protected int getSuggestedMinimumHeight() { 12589 int suggestedMinHeight = mMinHeight; 12590 12591 if (mBGDrawable != null) { 12592 final int bgMinHeight = mBGDrawable.getMinimumHeight(); 12593 if (suggestedMinHeight < bgMinHeight) { 12594 suggestedMinHeight = bgMinHeight; 12595 } 12596 } 12597 12598 return suggestedMinHeight; 12599 } 12600 12601 /** 12602 * Returns the suggested minimum width that the view should use. This 12603 * returns the maximum of the view's minimum width) 12604 * and the background's minimum width 12605 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 12606 * <p> 12607 * When being used in {@link #onMeasure(int, int)}, the caller should still 12608 * ensure the returned width is within the requirements of the parent. 12609 * 12610 * @return The suggested minimum width of the view. 12611 */ 12612 protected int getSuggestedMinimumWidth() { 12613 int suggestedMinWidth = mMinWidth; 12614 12615 if (mBGDrawable != null) { 12616 final int bgMinWidth = mBGDrawable.getMinimumWidth(); 12617 if (suggestedMinWidth < bgMinWidth) { 12618 suggestedMinWidth = bgMinWidth; 12619 } 12620 } 12621 12622 return suggestedMinWidth; 12623 } 12624 12625 /** 12626 * Sets the minimum height of the view. It is not guaranteed the view will 12627 * be able to achieve this minimum height (for example, if its parent layout 12628 * constrains it with less available height). 12629 * 12630 * @param minHeight The minimum height the view will try to be. 12631 */ 12632 public void setMinimumHeight(int minHeight) { 12633 mMinHeight = minHeight; 12634 } 12635 12636 /** 12637 * Sets the minimum width of the view. It is not guaranteed the view will 12638 * be able to achieve this minimum width (for example, if its parent layout 12639 * constrains it with less available width). 12640 * 12641 * @param minWidth The minimum width the view will try to be. 12642 */ 12643 public void setMinimumWidth(int minWidth) { 12644 mMinWidth = minWidth; 12645 } 12646 12647 /** 12648 * Get the animation currently associated with this view. 12649 * 12650 * @return The animation that is currently playing or 12651 * scheduled to play for this view. 12652 */ 12653 public Animation getAnimation() { 12654 return mCurrentAnimation; 12655 } 12656 12657 /** 12658 * Start the specified animation now. 12659 * 12660 * @param animation the animation to start now 12661 */ 12662 public void startAnimation(Animation animation) { 12663 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 12664 setAnimation(animation); 12665 invalidateParentCaches(); 12666 invalidate(true); 12667 } 12668 12669 /** 12670 * Cancels any animations for this view. 12671 */ 12672 public void clearAnimation() { 12673 if (mCurrentAnimation != null) { 12674 mCurrentAnimation.detach(); 12675 } 12676 mCurrentAnimation = null; 12677 invalidateParentIfNeeded(); 12678 } 12679 12680 /** 12681 * Sets the next animation to play for this view. 12682 * If you want the animation to play immediately, use 12683 * startAnimation. This method provides allows fine-grained 12684 * control over the start time and invalidation, but you 12685 * must make sure that 1) the animation has a start time set, and 12686 * 2) the view will be invalidated when the animation is supposed to 12687 * start. 12688 * 12689 * @param animation The next animation, or null. 12690 */ 12691 public void setAnimation(Animation animation) { 12692 mCurrentAnimation = animation; 12693 if (animation != null) { 12694 animation.reset(); 12695 } 12696 } 12697 12698 /** 12699 * Invoked by a parent ViewGroup to notify the start of the animation 12700 * currently associated with this view. If you override this method, 12701 * always call super.onAnimationStart(); 12702 * 12703 * @see #setAnimation(android.view.animation.Animation) 12704 * @see #getAnimation() 12705 */ 12706 protected void onAnimationStart() { 12707 mPrivateFlags |= ANIMATION_STARTED; 12708 } 12709 12710 /** 12711 * Invoked by a parent ViewGroup to notify the end of the animation 12712 * currently associated with this view. If you override this method, 12713 * always call super.onAnimationEnd(); 12714 * 12715 * @see #setAnimation(android.view.animation.Animation) 12716 * @see #getAnimation() 12717 */ 12718 protected void onAnimationEnd() { 12719 mPrivateFlags &= ~ANIMATION_STARTED; 12720 } 12721 12722 /** 12723 * Invoked if there is a Transform that involves alpha. Subclass that can 12724 * draw themselves with the specified alpha should return true, and then 12725 * respect that alpha when their onDraw() is called. If this returns false 12726 * then the view may be redirected to draw into an offscreen buffer to 12727 * fulfill the request, which will look fine, but may be slower than if the 12728 * subclass handles it internally. The default implementation returns false. 12729 * 12730 * @param alpha The alpha (0..255) to apply to the view's drawing 12731 * @return true if the view can draw with the specified alpha. 12732 */ 12733 protected boolean onSetAlpha(int alpha) { 12734 return false; 12735 } 12736 12737 /** 12738 * This is used by the RootView to perform an optimization when 12739 * the view hierarchy contains one or several SurfaceView. 12740 * SurfaceView is always considered transparent, but its children are not, 12741 * therefore all View objects remove themselves from the global transparent 12742 * region (passed as a parameter to this function). 12743 * 12744 * @param region The transparent region for this ViewAncestor (window). 12745 * 12746 * @return Returns true if the effective visibility of the view at this 12747 * point is opaque, regardless of the transparent region; returns false 12748 * if it is possible for underlying windows to be seen behind the view. 12749 * 12750 * {@hide} 12751 */ 12752 public boolean gatherTransparentRegion(Region region) { 12753 final AttachInfo attachInfo = mAttachInfo; 12754 if (region != null && attachInfo != null) { 12755 final int pflags = mPrivateFlags; 12756 if ((pflags & SKIP_DRAW) == 0) { 12757 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 12758 // remove it from the transparent region. 12759 final int[] location = attachInfo.mTransparentLocation; 12760 getLocationInWindow(location); 12761 region.op(location[0], location[1], location[0] + mRight - mLeft, 12762 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 12763 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) { 12764 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 12765 // exists, so we remove the background drawable's non-transparent 12766 // parts from this transparent region. 12767 applyDrawableToTransparentRegion(mBGDrawable, region); 12768 } 12769 } 12770 return true; 12771 } 12772 12773 /** 12774 * Play a sound effect for this view. 12775 * 12776 * <p>The framework will play sound effects for some built in actions, such as 12777 * clicking, but you may wish to play these effects in your widget, 12778 * for instance, for internal navigation. 12779 * 12780 * <p>The sound effect will only be played if sound effects are enabled by the user, and 12781 * {@link #isSoundEffectsEnabled()} is true. 12782 * 12783 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 12784 */ 12785 public void playSoundEffect(int soundConstant) { 12786 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 12787 return; 12788 } 12789 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 12790 } 12791 12792 /** 12793 * BZZZTT!!1! 12794 * 12795 * <p>Provide haptic feedback to the user for this view. 12796 * 12797 * <p>The framework will provide haptic feedback for some built in actions, 12798 * such as long presses, but you may wish to provide feedback for your 12799 * own widget. 12800 * 12801 * <p>The feedback will only be performed if 12802 * {@link #isHapticFeedbackEnabled()} is true. 12803 * 12804 * @param feedbackConstant One of the constants defined in 12805 * {@link HapticFeedbackConstants} 12806 */ 12807 public boolean performHapticFeedback(int feedbackConstant) { 12808 return performHapticFeedback(feedbackConstant, 0); 12809 } 12810 12811 /** 12812 * BZZZTT!!1! 12813 * 12814 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 12815 * 12816 * @param feedbackConstant One of the constants defined in 12817 * {@link HapticFeedbackConstants} 12818 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 12819 */ 12820 public boolean performHapticFeedback(int feedbackConstant, int flags) { 12821 if (mAttachInfo == null) { 12822 return false; 12823 } 12824 //noinspection SimplifiableIfStatement 12825 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 12826 && !isHapticFeedbackEnabled()) { 12827 return false; 12828 } 12829 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 12830 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 12831 } 12832 12833 /** 12834 * Request that the visibility of the status bar be changed. 12835 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or 12836 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. 12837 * 12838 * This value will be re-applied immediately, even if the flags have not changed, so a view may 12839 * easily reassert a particular SystemUiVisibility condition even if the system UI itself has 12840 * since countermanded the original request. 12841 */ 12842 public void setSystemUiVisibility(int visibility) { 12843 mSystemUiVisibility = visibility; 12844 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 12845 mParent.recomputeViewAttributes(this); 12846 } 12847 } 12848 12849 /** 12850 * Returns the status bar visibility that this view has requested. 12851 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or 12852 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. 12853 */ 12854 public int getSystemUiVisibility() { 12855 return mSystemUiVisibility; 12856 } 12857 12858 /** 12859 * Set a listener to receive callbacks when the visibility of the system bar changes. 12860 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 12861 */ 12862 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 12863 mOnSystemUiVisibilityChangeListener = l; 12864 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 12865 mParent.recomputeViewAttributes(this); 12866 } 12867 } 12868 12869 /** 12870 */ 12871 public void dispatchSystemUiVisibilityChanged(int visibility) { 12872 if (mOnSystemUiVisibilityChangeListener != null) { 12873 mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 12874 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 12875 } 12876 } 12877 12878 /** 12879 * Creates an image that the system displays during the drag and drop 12880 * operation. This is called a "drag shadow". The default implementation 12881 * for a DragShadowBuilder based on a View returns an image that has exactly the same 12882 * appearance as the given View. The default also positions the center of the drag shadow 12883 * directly under the touch point. If no View is provided (the constructor with no parameters 12884 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 12885 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 12886 * default is an invisible drag shadow. 12887 * <p> 12888 * You are not required to use the View you provide to the constructor as the basis of the 12889 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 12890 * anything you want as the drag shadow. 12891 * </p> 12892 * <p> 12893 * You pass a DragShadowBuilder object to the system when you start the drag. The system 12894 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 12895 * size and position of the drag shadow. It uses this data to construct a 12896 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 12897 * so that your application can draw the shadow image in the Canvas. 12898 * </p> 12899 */ 12900 public static class DragShadowBuilder { 12901 private final WeakReference<View> mView; 12902 12903 /** 12904 * Constructs a shadow image builder based on a View. By default, the resulting drag 12905 * shadow will have the same appearance and dimensions as the View, with the touch point 12906 * over the center of the View. 12907 * @param view A View. Any View in scope can be used. 12908 */ 12909 public DragShadowBuilder(View view) { 12910 mView = new WeakReference<View>(view); 12911 } 12912 12913 /** 12914 * Construct a shadow builder object with no associated View. This 12915 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 12916 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 12917 * to supply the drag shadow's dimensions and appearance without 12918 * reference to any View object. If they are not overridden, then the result is an 12919 * invisible drag shadow. 12920 */ 12921 public DragShadowBuilder() { 12922 mView = new WeakReference<View>(null); 12923 } 12924 12925 /** 12926 * Returns the View object that had been passed to the 12927 * {@link #View.DragShadowBuilder(View)} 12928 * constructor. If that View parameter was {@code null} or if the 12929 * {@link #View.DragShadowBuilder()} 12930 * constructor was used to instantiate the builder object, this method will return 12931 * null. 12932 * 12933 * @return The View object associate with this builder object. 12934 */ 12935 @SuppressWarnings({"JavadocReference"}) 12936 final public View getView() { 12937 return mView.get(); 12938 } 12939 12940 /** 12941 * Provides the metrics for the shadow image. These include the dimensions of 12942 * the shadow image, and the point within that shadow that should 12943 * be centered under the touch location while dragging. 12944 * <p> 12945 * The default implementation sets the dimensions of the shadow to be the 12946 * same as the dimensions of the View itself and centers the shadow under 12947 * the touch point. 12948 * </p> 12949 * 12950 * @param shadowSize A {@link android.graphics.Point} containing the width and height 12951 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 12952 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 12953 * image. 12954 * 12955 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 12956 * shadow image that should be underneath the touch point during the drag and drop 12957 * operation. Your application must set {@link android.graphics.Point#x} to the 12958 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 12959 */ 12960 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 12961 final View view = mView.get(); 12962 if (view != null) { 12963 shadowSize.set(view.getWidth(), view.getHeight()); 12964 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 12965 } else { 12966 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 12967 } 12968 } 12969 12970 /** 12971 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 12972 * based on the dimensions it received from the 12973 * {@link #onProvideShadowMetrics(Point, Point)} callback. 12974 * 12975 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 12976 */ 12977 public void onDrawShadow(Canvas canvas) { 12978 final View view = mView.get(); 12979 if (view != null) { 12980 view.draw(canvas); 12981 } else { 12982 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 12983 } 12984 } 12985 } 12986 12987 /** 12988 * Starts a drag and drop operation. When your application calls this method, it passes a 12989 * {@link android.view.View.DragShadowBuilder} object to the system. The 12990 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 12991 * to get metrics for the drag shadow, and then calls the object's 12992 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 12993 * <p> 12994 * Once the system has the drag shadow, it begins the drag and drop operation by sending 12995 * drag events to all the View objects in your application that are currently visible. It does 12996 * this either by calling the View object's drag listener (an implementation of 12997 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 12998 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 12999 * Both are passed a {@link android.view.DragEvent} object that has a 13000 * {@link android.view.DragEvent#getAction()} value of 13001 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 13002 * </p> 13003 * <p> 13004 * Your application can invoke startDrag() on any attached View object. The View object does not 13005 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 13006 * be related to the View the user selected for dragging. 13007 * </p> 13008 * @param data A {@link android.content.ClipData} object pointing to the data to be 13009 * transferred by the drag and drop operation. 13010 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 13011 * drag shadow. 13012 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 13013 * drop operation. This Object is put into every DragEvent object sent by the system during the 13014 * current drag. 13015 * <p> 13016 * myLocalState is a lightweight mechanism for the sending information from the dragged View 13017 * to the target Views. For example, it can contain flags that differentiate between a 13018 * a copy operation and a move operation. 13019 * </p> 13020 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 13021 * so the parameter should be set to 0. 13022 * @return {@code true} if the method completes successfully, or 13023 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 13024 * do a drag, and so no drag operation is in progress. 13025 */ 13026 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 13027 Object myLocalState, int flags) { 13028 if (ViewDebug.DEBUG_DRAG) { 13029 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 13030 } 13031 boolean okay = false; 13032 13033 Point shadowSize = new Point(); 13034 Point shadowTouchPoint = new Point(); 13035 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 13036 13037 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 13038 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 13039 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 13040 } 13041 13042 if (ViewDebug.DEBUG_DRAG) { 13043 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 13044 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 13045 } 13046 Surface surface = new Surface(); 13047 try { 13048 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 13049 flags, shadowSize.x, shadowSize.y, surface); 13050 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 13051 + " surface=" + surface); 13052 if (token != null) { 13053 Canvas canvas = surface.lockCanvas(null); 13054 try { 13055 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 13056 shadowBuilder.onDrawShadow(canvas); 13057 } finally { 13058 surface.unlockCanvasAndPost(canvas); 13059 } 13060 13061 final ViewRootImpl root = getViewRootImpl(); 13062 13063 // Cache the local state object for delivery with DragEvents 13064 root.setLocalDragState(myLocalState); 13065 13066 // repurpose 'shadowSize' for the last touch point 13067 root.getLastTouchPoint(shadowSize); 13068 13069 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 13070 shadowSize.x, shadowSize.y, 13071 shadowTouchPoint.x, shadowTouchPoint.y, data); 13072 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 13073 } 13074 } catch (Exception e) { 13075 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 13076 surface.destroy(); 13077 } 13078 13079 return okay; 13080 } 13081 13082 /** 13083 * Handles drag events sent by the system following a call to 13084 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 13085 *<p> 13086 * When the system calls this method, it passes a 13087 * {@link android.view.DragEvent} object. A call to 13088 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 13089 * in DragEvent. The method uses these to determine what is happening in the drag and drop 13090 * operation. 13091 * @param event The {@link android.view.DragEvent} sent by the system. 13092 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 13093 * in DragEvent, indicating the type of drag event represented by this object. 13094 * @return {@code true} if the method was successful, otherwise {@code false}. 13095 * <p> 13096 * The method should return {@code true} in response to an action type of 13097 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 13098 * operation. 13099 * </p> 13100 * <p> 13101 * The method should also return {@code true} in response to an action type of 13102 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 13103 * {@code false} if it didn't. 13104 * </p> 13105 */ 13106 public boolean onDragEvent(DragEvent event) { 13107 return false; 13108 } 13109 13110 /** 13111 * Detects if this View is enabled and has a drag event listener. 13112 * If both are true, then it calls the drag event listener with the 13113 * {@link android.view.DragEvent} it received. If the drag event listener returns 13114 * {@code true}, then dispatchDragEvent() returns {@code true}. 13115 * <p> 13116 * For all other cases, the method calls the 13117 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 13118 * method and returns its result. 13119 * </p> 13120 * <p> 13121 * This ensures that a drag event is always consumed, even if the View does not have a drag 13122 * event listener. However, if the View has a listener and the listener returns true, then 13123 * onDragEvent() is not called. 13124 * </p> 13125 */ 13126 public boolean dispatchDragEvent(DragEvent event) { 13127 //noinspection SimplifiableIfStatement 13128 if (mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 13129 && mOnDragListener.onDrag(this, event)) { 13130 return true; 13131 } 13132 return onDragEvent(event); 13133 } 13134 13135 boolean canAcceptDrag() { 13136 return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0; 13137 } 13138 13139 /** 13140 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 13141 * it is ever exposed at all. 13142 * @hide 13143 */ 13144 public void onCloseSystemDialogs(String reason) { 13145 } 13146 13147 /** 13148 * Given a Drawable whose bounds have been set to draw into this view, 13149 * update a Region being computed for 13150 * {@link #gatherTransparentRegion(android.graphics.Region)} so 13151 * that any non-transparent parts of the Drawable are removed from the 13152 * given transparent region. 13153 * 13154 * @param dr The Drawable whose transparency is to be applied to the region. 13155 * @param region A Region holding the current transparency information, 13156 * where any parts of the region that are set are considered to be 13157 * transparent. On return, this region will be modified to have the 13158 * transparency information reduced by the corresponding parts of the 13159 * Drawable that are not transparent. 13160 * {@hide} 13161 */ 13162 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 13163 if (DBG) { 13164 Log.i("View", "Getting transparent region for: " + this); 13165 } 13166 final Region r = dr.getTransparentRegion(); 13167 final Rect db = dr.getBounds(); 13168 final AttachInfo attachInfo = mAttachInfo; 13169 if (r != null && attachInfo != null) { 13170 final int w = getRight()-getLeft(); 13171 final int h = getBottom()-getTop(); 13172 if (db.left > 0) { 13173 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 13174 r.op(0, 0, db.left, h, Region.Op.UNION); 13175 } 13176 if (db.right < w) { 13177 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 13178 r.op(db.right, 0, w, h, Region.Op.UNION); 13179 } 13180 if (db.top > 0) { 13181 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 13182 r.op(0, 0, w, db.top, Region.Op.UNION); 13183 } 13184 if (db.bottom < h) { 13185 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 13186 r.op(0, db.bottom, w, h, Region.Op.UNION); 13187 } 13188 final int[] location = attachInfo.mTransparentLocation; 13189 getLocationInWindow(location); 13190 r.translate(location[0], location[1]); 13191 region.op(r, Region.Op.INTERSECT); 13192 } else { 13193 region.op(db, Region.Op.DIFFERENCE); 13194 } 13195 } 13196 13197 private void checkForLongClick(int delayOffset) { 13198 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 13199 mHasPerformedLongPress = false; 13200 13201 if (mPendingCheckForLongPress == null) { 13202 mPendingCheckForLongPress = new CheckForLongPress(); 13203 } 13204 mPendingCheckForLongPress.rememberWindowAttachCount(); 13205 postDelayed(mPendingCheckForLongPress, 13206 ViewConfiguration.getLongPressTimeout() - delayOffset); 13207 } 13208 } 13209 13210 /** 13211 * Inflate a view from an XML resource. This convenience method wraps the {@link 13212 * LayoutInflater} class, which provides a full range of options for view inflation. 13213 * 13214 * @param context The Context object for your activity or application. 13215 * @param resource The resource ID to inflate 13216 * @param root A view group that will be the parent. Used to properly inflate the 13217 * layout_* parameters. 13218 * @see LayoutInflater 13219 */ 13220 public static View inflate(Context context, int resource, ViewGroup root) { 13221 LayoutInflater factory = LayoutInflater.from(context); 13222 return factory.inflate(resource, root); 13223 } 13224 13225 /** 13226 * Scroll the view with standard behavior for scrolling beyond the normal 13227 * content boundaries. Views that call this method should override 13228 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 13229 * results of an over-scroll operation. 13230 * 13231 * Views can use this method to handle any touch or fling-based scrolling. 13232 * 13233 * @param deltaX Change in X in pixels 13234 * @param deltaY Change in Y in pixels 13235 * @param scrollX Current X scroll value in pixels before applying deltaX 13236 * @param scrollY Current Y scroll value in pixels before applying deltaY 13237 * @param scrollRangeX Maximum content scroll range along the X axis 13238 * @param scrollRangeY Maximum content scroll range along the Y axis 13239 * @param maxOverScrollX Number of pixels to overscroll by in either direction 13240 * along the X axis. 13241 * @param maxOverScrollY Number of pixels to overscroll by in either direction 13242 * along the Y axis. 13243 * @param isTouchEvent true if this scroll operation is the result of a touch event. 13244 * @return true if scrolling was clamped to an over-scroll boundary along either 13245 * axis, false otherwise. 13246 */ 13247 @SuppressWarnings({"UnusedParameters"}) 13248 protected boolean overScrollBy(int deltaX, int deltaY, 13249 int scrollX, int scrollY, 13250 int scrollRangeX, int scrollRangeY, 13251 int maxOverScrollX, int maxOverScrollY, 13252 boolean isTouchEvent) { 13253 final int overScrollMode = mOverScrollMode; 13254 final boolean canScrollHorizontal = 13255 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 13256 final boolean canScrollVertical = 13257 computeVerticalScrollRange() > computeVerticalScrollExtent(); 13258 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 13259 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 13260 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 13261 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 13262 13263 int newScrollX = scrollX + deltaX; 13264 if (!overScrollHorizontal) { 13265 maxOverScrollX = 0; 13266 } 13267 13268 int newScrollY = scrollY + deltaY; 13269 if (!overScrollVertical) { 13270 maxOverScrollY = 0; 13271 } 13272 13273 // Clamp values if at the limits and record 13274 final int left = -maxOverScrollX; 13275 final int right = maxOverScrollX + scrollRangeX; 13276 final int top = -maxOverScrollY; 13277 final int bottom = maxOverScrollY + scrollRangeY; 13278 13279 boolean clampedX = false; 13280 if (newScrollX > right) { 13281 newScrollX = right; 13282 clampedX = true; 13283 } else if (newScrollX < left) { 13284 newScrollX = left; 13285 clampedX = true; 13286 } 13287 13288 boolean clampedY = false; 13289 if (newScrollY > bottom) { 13290 newScrollY = bottom; 13291 clampedY = true; 13292 } else if (newScrollY < top) { 13293 newScrollY = top; 13294 clampedY = true; 13295 } 13296 13297 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 13298 13299 return clampedX || clampedY; 13300 } 13301 13302 /** 13303 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 13304 * respond to the results of an over-scroll operation. 13305 * 13306 * @param scrollX New X scroll value in pixels 13307 * @param scrollY New Y scroll value in pixels 13308 * @param clampedX True if scrollX was clamped to an over-scroll boundary 13309 * @param clampedY True if scrollY was clamped to an over-scroll boundary 13310 */ 13311 protected void onOverScrolled(int scrollX, int scrollY, 13312 boolean clampedX, boolean clampedY) { 13313 // Intentionally empty. 13314 } 13315 13316 /** 13317 * Returns the over-scroll mode for this view. The result will be 13318 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 13319 * (allow over-scrolling only if the view content is larger than the container), 13320 * or {@link #OVER_SCROLL_NEVER}. 13321 * 13322 * @return This view's over-scroll mode. 13323 */ 13324 public int getOverScrollMode() { 13325 return mOverScrollMode; 13326 } 13327 13328 /** 13329 * Set the over-scroll mode for this view. Valid over-scroll modes are 13330 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 13331 * (allow over-scrolling only if the view content is larger than the container), 13332 * or {@link #OVER_SCROLL_NEVER}. 13333 * 13334 * Setting the over-scroll mode of a view will have an effect only if the 13335 * view is capable of scrolling. 13336 * 13337 * @param overScrollMode The new over-scroll mode for this view. 13338 */ 13339 public void setOverScrollMode(int overScrollMode) { 13340 if (overScrollMode != OVER_SCROLL_ALWAYS && 13341 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 13342 overScrollMode != OVER_SCROLL_NEVER) { 13343 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 13344 } 13345 mOverScrollMode = overScrollMode; 13346 } 13347 13348 /** 13349 * Gets a scale factor that determines the distance the view should scroll 13350 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 13351 * @return The vertical scroll scale factor. 13352 * @hide 13353 */ 13354 protected float getVerticalScrollFactor() { 13355 if (mVerticalScrollFactor == 0) { 13356 TypedValue outValue = new TypedValue(); 13357 if (!mContext.getTheme().resolveAttribute( 13358 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 13359 throw new IllegalStateException( 13360 "Expected theme to define listPreferredItemHeight."); 13361 } 13362 mVerticalScrollFactor = outValue.getDimension( 13363 mContext.getResources().getDisplayMetrics()); 13364 } 13365 return mVerticalScrollFactor; 13366 } 13367 13368 /** 13369 * Gets a scale factor that determines the distance the view should scroll 13370 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 13371 * @return The horizontal scroll scale factor. 13372 * @hide 13373 */ 13374 protected float getHorizontalScrollFactor() { 13375 // TODO: Should use something else. 13376 return getVerticalScrollFactor(); 13377 } 13378 13379 /** 13380 * Return the value specifying the text direction or policy that was set with 13381 * {@link #setTextDirection(int)}. 13382 * 13383 * @return the defined text direction. It can be one of: 13384 * 13385 * {@link #TEXT_DIRECTION_INHERIT}, 13386 * {@link #TEXT_DIRECTION_FIRST_STRONG} 13387 * {@link #TEXT_DIRECTION_ANY_RTL}, 13388 * {@link #TEXT_DIRECTION_LTR}, 13389 * {@link #TEXT_DIRECTION_RTL}, 13390 * 13391 * @hide 13392 */ 13393 public int getTextDirection() { 13394 return mTextDirection; 13395 } 13396 13397 /** 13398 * Set the text direction. 13399 * 13400 * @param textDirection the direction to set. Should be one of: 13401 * 13402 * {@link #TEXT_DIRECTION_INHERIT}, 13403 * {@link #TEXT_DIRECTION_FIRST_STRONG} 13404 * {@link #TEXT_DIRECTION_ANY_RTL}, 13405 * {@link #TEXT_DIRECTION_LTR}, 13406 * {@link #TEXT_DIRECTION_RTL}, 13407 * 13408 * @hide 13409 */ 13410 public void setTextDirection(int textDirection) { 13411 if (textDirection != mTextDirection) { 13412 mTextDirection = textDirection; 13413 resetResolvedTextDirection(); 13414 requestLayout(); 13415 } 13416 } 13417 13418 /** 13419 * Return the resolved text direction. 13420 * 13421 * @return the resolved text direction. Return one of: 13422 * 13423 * {@link #TEXT_DIRECTION_FIRST_STRONG} 13424 * {@link #TEXT_DIRECTION_ANY_RTL}, 13425 * {@link #TEXT_DIRECTION_LTR}, 13426 * {@link #TEXT_DIRECTION_RTL}, 13427 * 13428 * @hide 13429 */ 13430 public int getResolvedTextDirection() { 13431 if (mResolvedTextDirection == TEXT_DIRECTION_INHERIT) { 13432 resolveTextDirection(); 13433 } 13434 return mResolvedTextDirection; 13435 } 13436 13437 /** 13438 * Resolve the text direction. 13439 * 13440 * @hide 13441 */ 13442 protected void resolveTextDirection() { 13443 if (mTextDirection != TEXT_DIRECTION_INHERIT) { 13444 mResolvedTextDirection = mTextDirection; 13445 return; 13446 } 13447 if (mParent != null && mParent instanceof ViewGroup) { 13448 mResolvedTextDirection = ((ViewGroup) mParent).getResolvedTextDirection(); 13449 return; 13450 } 13451 mResolvedTextDirection = TEXT_DIRECTION_FIRST_STRONG; 13452 } 13453 13454 /** 13455 * Reset resolved text direction. Will be resolved during a call to getResolvedTextDirection(). 13456 * 13457 * @hide 13458 */ 13459 protected void resetResolvedTextDirection() { 13460 mResolvedTextDirection = TEXT_DIRECTION_INHERIT; 13461 } 13462 13463 // 13464 // Properties 13465 // 13466 /** 13467 * A Property wrapper around the <code>alpha</code> functionality handled by the 13468 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 13469 */ 13470 public static Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 13471 @Override 13472 public void setValue(View object, float value) { 13473 object.setAlpha(value); 13474 } 13475 13476 @Override 13477 public Float get(View object) { 13478 return object.getAlpha(); 13479 } 13480 }; 13481 13482 /** 13483 * A Property wrapper around the <code>translationX</code> functionality handled by the 13484 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 13485 */ 13486 public static Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 13487 @Override 13488 public void setValue(View object, float value) { 13489 object.setTranslationX(value); 13490 } 13491 13492 @Override 13493 public Float get(View object) { 13494 return object.getTranslationX(); 13495 } 13496 }; 13497 13498 /** 13499 * A Property wrapper around the <code>translationY</code> functionality handled by the 13500 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 13501 */ 13502 public static Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 13503 @Override 13504 public void setValue(View object, float value) { 13505 object.setTranslationY(value); 13506 } 13507 13508 @Override 13509 public Float get(View object) { 13510 return object.getTranslationY(); 13511 } 13512 }; 13513 13514 /** 13515 * A Property wrapper around the <code>x</code> functionality handled by the 13516 * {@link View#setX(float)} and {@link View#getX()} methods. 13517 */ 13518 public static Property<View, Float> X = new FloatProperty<View>("x") { 13519 @Override 13520 public void setValue(View object, float value) { 13521 object.setX(value); 13522 } 13523 13524 @Override 13525 public Float get(View object) { 13526 return object.getX(); 13527 } 13528 }; 13529 13530 /** 13531 * A Property wrapper around the <code>y</code> functionality handled by the 13532 * {@link View#setY(float)} and {@link View#getY()} methods. 13533 */ 13534 public static Property<View, Float> Y = new FloatProperty<View>("y") { 13535 @Override 13536 public void setValue(View object, float value) { 13537 object.setY(value); 13538 } 13539 13540 @Override 13541 public Float get(View object) { 13542 return object.getY(); 13543 } 13544 }; 13545 13546 /** 13547 * A Property wrapper around the <code>rotation</code> functionality handled by the 13548 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 13549 */ 13550 public static Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 13551 @Override 13552 public void setValue(View object, float value) { 13553 object.setRotation(value); 13554 } 13555 13556 @Override 13557 public Float get(View object) { 13558 return object.getRotation(); 13559 } 13560 }; 13561 13562 /** 13563 * A Property wrapper around the <code>rotationX</code> functionality handled by the 13564 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 13565 */ 13566 public static Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 13567 @Override 13568 public void setValue(View object, float value) { 13569 object.setRotationX(value); 13570 } 13571 13572 @Override 13573 public Float get(View object) { 13574 return object.getRotationX(); 13575 } 13576 }; 13577 13578 /** 13579 * A Property wrapper around the <code>rotationY</code> functionality handled by the 13580 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 13581 */ 13582 public static Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 13583 @Override 13584 public void setValue(View object, float value) { 13585 object.setRotationY(value); 13586 } 13587 13588 @Override 13589 public Float get(View object) { 13590 return object.getRotationY(); 13591 } 13592 }; 13593 13594 /** 13595 * A Property wrapper around the <code>scaleX</code> functionality handled by the 13596 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 13597 */ 13598 public static Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 13599 @Override 13600 public void setValue(View object, float value) { 13601 object.setScaleX(value); 13602 } 13603 13604 @Override 13605 public Float get(View object) { 13606 return object.getScaleX(); 13607 } 13608 }; 13609 13610 /** 13611 * A Property wrapper around the <code>scaleY</code> functionality handled by the 13612 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 13613 */ 13614 public static Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 13615 @Override 13616 public void setValue(View object, float value) { 13617 object.setScaleY(value); 13618 } 13619 13620 @Override 13621 public Float get(View object) { 13622 return object.getScaleY(); 13623 } 13624 }; 13625 13626 /** 13627 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 13628 * Each MeasureSpec represents a requirement for either the width or the height. 13629 * A MeasureSpec is comprised of a size and a mode. There are three possible 13630 * modes: 13631 * <dl> 13632 * <dt>UNSPECIFIED</dt> 13633 * <dd> 13634 * The parent has not imposed any constraint on the child. It can be whatever size 13635 * it wants. 13636 * </dd> 13637 * 13638 * <dt>EXACTLY</dt> 13639 * <dd> 13640 * The parent has determined an exact size for the child. The child is going to be 13641 * given those bounds regardless of how big it wants to be. 13642 * </dd> 13643 * 13644 * <dt>AT_MOST</dt> 13645 * <dd> 13646 * The child can be as large as it wants up to the specified size. 13647 * </dd> 13648 * </dl> 13649 * 13650 * MeasureSpecs are implemented as ints to reduce object allocation. This class 13651 * is provided to pack and unpack the <size, mode> tuple into the int. 13652 */ 13653 public static class MeasureSpec { 13654 private static final int MODE_SHIFT = 30; 13655 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 13656 13657 /** 13658 * Measure specification mode: The parent has not imposed any constraint 13659 * on the child. It can be whatever size it wants. 13660 */ 13661 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 13662 13663 /** 13664 * Measure specification mode: The parent has determined an exact size 13665 * for the child. The child is going to be given those bounds regardless 13666 * of how big it wants to be. 13667 */ 13668 public static final int EXACTLY = 1 << MODE_SHIFT; 13669 13670 /** 13671 * Measure specification mode: The child can be as large as it wants up 13672 * to the specified size. 13673 */ 13674 public static final int AT_MOST = 2 << MODE_SHIFT; 13675 13676 /** 13677 * Creates a measure specification based on the supplied size and mode. 13678 * 13679 * The mode must always be one of the following: 13680 * <ul> 13681 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 13682 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 13683 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 13684 * </ul> 13685 * 13686 * @param size the size of the measure specification 13687 * @param mode the mode of the measure specification 13688 * @return the measure specification based on size and mode 13689 */ 13690 public static int makeMeasureSpec(int size, int mode) { 13691 return size + mode; 13692 } 13693 13694 /** 13695 * Extracts the mode from the supplied measure specification. 13696 * 13697 * @param measureSpec the measure specification to extract the mode from 13698 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 13699 * {@link android.view.View.MeasureSpec#AT_MOST} or 13700 * {@link android.view.View.MeasureSpec#EXACTLY} 13701 */ 13702 public static int getMode(int measureSpec) { 13703 return (measureSpec & MODE_MASK); 13704 } 13705 13706 /** 13707 * Extracts the size from the supplied measure specification. 13708 * 13709 * @param measureSpec the measure specification to extract the size from 13710 * @return the size in pixels defined in the supplied measure specification 13711 */ 13712 public static int getSize(int measureSpec) { 13713 return (measureSpec & ~MODE_MASK); 13714 } 13715 13716 /** 13717 * Returns a String representation of the specified measure 13718 * specification. 13719 * 13720 * @param measureSpec the measure specification to convert to a String 13721 * @return a String with the following format: "MeasureSpec: MODE SIZE" 13722 */ 13723 public static String toString(int measureSpec) { 13724 int mode = getMode(measureSpec); 13725 int size = getSize(measureSpec); 13726 13727 StringBuilder sb = new StringBuilder("MeasureSpec: "); 13728 13729 if (mode == UNSPECIFIED) 13730 sb.append("UNSPECIFIED "); 13731 else if (mode == EXACTLY) 13732 sb.append("EXACTLY "); 13733 else if (mode == AT_MOST) 13734 sb.append("AT_MOST "); 13735 else 13736 sb.append(mode).append(" "); 13737 13738 sb.append(size); 13739 return sb.toString(); 13740 } 13741 } 13742 13743 class CheckForLongPress implements Runnable { 13744 13745 private int mOriginalWindowAttachCount; 13746 13747 public void run() { 13748 if (isPressed() && (mParent != null) 13749 && mOriginalWindowAttachCount == mWindowAttachCount) { 13750 if (performLongClick()) { 13751 mHasPerformedLongPress = true; 13752 } 13753 } 13754 } 13755 13756 public void rememberWindowAttachCount() { 13757 mOriginalWindowAttachCount = mWindowAttachCount; 13758 } 13759 } 13760 13761 private final class CheckForTap implements Runnable { 13762 public void run() { 13763 mPrivateFlags &= ~PREPRESSED; 13764 mPrivateFlags |= PRESSED; 13765 refreshDrawableState(); 13766 checkForLongClick(ViewConfiguration.getTapTimeout()); 13767 } 13768 } 13769 13770 private final class PerformClick implements Runnable { 13771 public void run() { 13772 performClick(); 13773 } 13774 } 13775 13776 /** @hide */ 13777 public void hackTurnOffWindowResizeAnim(boolean off) { 13778 mAttachInfo.mTurnOffWindowResizeAnim = off; 13779 } 13780 13781 /** 13782 * This method returns a ViewPropertyAnimator object, which can be used to animate 13783 * specific properties on this View. 13784 * 13785 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 13786 */ 13787 public ViewPropertyAnimator animate() { 13788 if (mAnimator == null) { 13789 mAnimator = new ViewPropertyAnimator(this); 13790 } 13791 return mAnimator; 13792 } 13793 13794 /** 13795 * Interface definition for a callback to be invoked when a key event is 13796 * dispatched to this view. The callback will be invoked before the key 13797 * event is given to the view. 13798 */ 13799 public interface OnKeyListener { 13800 /** 13801 * Called when a key is dispatched to a view. This allows listeners to 13802 * get a chance to respond before the target view. 13803 * 13804 * @param v The view the key has been dispatched to. 13805 * @param keyCode The code for the physical key that was pressed 13806 * @param event The KeyEvent object containing full information about 13807 * the event. 13808 * @return True if the listener has consumed the event, false otherwise. 13809 */ 13810 boolean onKey(View v, int keyCode, KeyEvent event); 13811 } 13812 13813 /** 13814 * Interface definition for a callback to be invoked when a touch event is 13815 * dispatched to this view. The callback will be invoked before the touch 13816 * event is given to the view. 13817 */ 13818 public interface OnTouchListener { 13819 /** 13820 * Called when a touch event is dispatched to a view. This allows listeners to 13821 * get a chance to respond before the target view. 13822 * 13823 * @param v The view the touch event has been dispatched to. 13824 * @param event The MotionEvent object containing full information about 13825 * the event. 13826 * @return True if the listener has consumed the event, false otherwise. 13827 */ 13828 boolean onTouch(View v, MotionEvent event); 13829 } 13830 13831 /** 13832 * Interface definition for a callback to be invoked when a hover event is 13833 * dispatched to this view. The callback will be invoked before the hover 13834 * event is given to the view. 13835 */ 13836 public interface OnHoverListener { 13837 /** 13838 * Called when a hover event is dispatched to a view. This allows listeners to 13839 * get a chance to respond before the target view. 13840 * 13841 * @param v The view the hover event has been dispatched to. 13842 * @param event The MotionEvent object containing full information about 13843 * the event. 13844 * @return True if the listener has consumed the event, false otherwise. 13845 */ 13846 boolean onHover(View v, MotionEvent event); 13847 } 13848 13849 /** 13850 * Interface definition for a callback to be invoked when a generic motion event is 13851 * dispatched to this view. The callback will be invoked before the generic motion 13852 * event is given to the view. 13853 */ 13854 public interface OnGenericMotionListener { 13855 /** 13856 * Called when a generic motion event is dispatched to a view. This allows listeners to 13857 * get a chance to respond before the target view. 13858 * 13859 * @param v The view the generic motion event has been dispatched to. 13860 * @param event The MotionEvent object containing full information about 13861 * the event. 13862 * @return True if the listener has consumed the event, false otherwise. 13863 */ 13864 boolean onGenericMotion(View v, MotionEvent event); 13865 } 13866 13867 /** 13868 * Interface definition for a callback to be invoked when a view has been clicked and held. 13869 */ 13870 public interface OnLongClickListener { 13871 /** 13872 * Called when a view has been clicked and held. 13873 * 13874 * @param v The view that was clicked and held. 13875 * 13876 * @return true if the callback consumed the long click, false otherwise. 13877 */ 13878 boolean onLongClick(View v); 13879 } 13880 13881 /** 13882 * Interface definition for a callback to be invoked when a drag is being dispatched 13883 * to this view. The callback will be invoked before the hosting view's own 13884 * onDrag(event) method. If the listener wants to fall back to the hosting view's 13885 * onDrag(event) behavior, it should return 'false' from this callback. 13886 */ 13887 public interface OnDragListener { 13888 /** 13889 * Called when a drag event is dispatched to a view. This allows listeners 13890 * to get a chance to override base View behavior. 13891 * 13892 * @param v The View that received the drag event. 13893 * @param event The {@link android.view.DragEvent} object for the drag event. 13894 * @return {@code true} if the drag event was handled successfully, or {@code false} 13895 * if the drag event was not handled. Note that {@code false} will trigger the View 13896 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 13897 */ 13898 boolean onDrag(View v, DragEvent event); 13899 } 13900 13901 /** 13902 * Interface definition for a callback to be invoked when the focus state of 13903 * a view changed. 13904 */ 13905 public interface OnFocusChangeListener { 13906 /** 13907 * Called when the focus state of a view has changed. 13908 * 13909 * @param v The view whose state has changed. 13910 * @param hasFocus The new focus state of v. 13911 */ 13912 void onFocusChange(View v, boolean hasFocus); 13913 } 13914 13915 /** 13916 * Interface definition for a callback to be invoked when a view is clicked. 13917 */ 13918 public interface OnClickListener { 13919 /** 13920 * Called when a view has been clicked. 13921 * 13922 * @param v The view that was clicked. 13923 */ 13924 void onClick(View v); 13925 } 13926 13927 /** 13928 * Interface definition for a callback to be invoked when the context menu 13929 * for this view is being built. 13930 */ 13931 public interface OnCreateContextMenuListener { 13932 /** 13933 * Called when the context menu for this view is being built. It is not 13934 * safe to hold onto the menu after this method returns. 13935 * 13936 * @param menu The context menu that is being built 13937 * @param v The view for which the context menu is being built 13938 * @param menuInfo Extra information about the item for which the 13939 * context menu should be shown. This information will vary 13940 * depending on the class of v. 13941 */ 13942 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 13943 } 13944 13945 /** 13946 * Interface definition for a callback to be invoked when the status bar changes 13947 * visibility. 13948 * 13949 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 13950 */ 13951 public interface OnSystemUiVisibilityChangeListener { 13952 /** 13953 * Called when the status bar changes visibility because of a call to 13954 * {@link View#setSystemUiVisibility(int)}. 13955 * 13956 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or 13957 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. 13958 */ 13959 public void onSystemUiVisibilityChange(int visibility); 13960 } 13961 13962 /** 13963 * Interface definition for a callback to be invoked when this view is attached 13964 * or detached from its window. 13965 */ 13966 public interface OnAttachStateChangeListener { 13967 /** 13968 * Called when the view is attached to a window. 13969 * @param v The view that was attached 13970 */ 13971 public void onViewAttachedToWindow(View v); 13972 /** 13973 * Called when the view is detached from a window. 13974 * @param v The view that was detached 13975 */ 13976 public void onViewDetachedFromWindow(View v); 13977 } 13978 13979 private final class UnsetPressedState implements Runnable { 13980 public void run() { 13981 setPressed(false); 13982 } 13983 } 13984 13985 /** 13986 * Base class for derived classes that want to save and restore their own 13987 * state in {@link android.view.View#onSaveInstanceState()}. 13988 */ 13989 public static class BaseSavedState extends AbsSavedState { 13990 /** 13991 * Constructor used when reading from a parcel. Reads the state of the superclass. 13992 * 13993 * @param source 13994 */ 13995 public BaseSavedState(Parcel source) { 13996 super(source); 13997 } 13998 13999 /** 14000 * Constructor called by derived classes when creating their SavedState objects 14001 * 14002 * @param superState The state of the superclass of this view 14003 */ 14004 public BaseSavedState(Parcelable superState) { 14005 super(superState); 14006 } 14007 14008 public static final Parcelable.Creator<BaseSavedState> CREATOR = 14009 new Parcelable.Creator<BaseSavedState>() { 14010 public BaseSavedState createFromParcel(Parcel in) { 14011 return new BaseSavedState(in); 14012 } 14013 14014 public BaseSavedState[] newArray(int size) { 14015 return new BaseSavedState[size]; 14016 } 14017 }; 14018 } 14019 14020 /** 14021 * A set of information given to a view when it is attached to its parent 14022 * window. 14023 */ 14024 static class AttachInfo { 14025 interface Callbacks { 14026 void playSoundEffect(int effectId); 14027 boolean performHapticFeedback(int effectId, boolean always); 14028 } 14029 14030 /** 14031 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 14032 * to a Handler. This class contains the target (View) to invalidate and 14033 * the coordinates of the dirty rectangle. 14034 * 14035 * For performance purposes, this class also implements a pool of up to 14036 * POOL_LIMIT objects that get reused. This reduces memory allocations 14037 * whenever possible. 14038 */ 14039 static class InvalidateInfo implements Poolable<InvalidateInfo> { 14040 private static final int POOL_LIMIT = 10; 14041 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool( 14042 Pools.finitePool(new PoolableManager<InvalidateInfo>() { 14043 public InvalidateInfo newInstance() { 14044 return new InvalidateInfo(); 14045 } 14046 14047 public void onAcquired(InvalidateInfo element) { 14048 } 14049 14050 public void onReleased(InvalidateInfo element) { 14051 element.target = null; 14052 } 14053 }, POOL_LIMIT) 14054 ); 14055 14056 private InvalidateInfo mNext; 14057 private boolean mIsPooled; 14058 14059 View target; 14060 14061 int left; 14062 int top; 14063 int right; 14064 int bottom; 14065 14066 public void setNextPoolable(InvalidateInfo element) { 14067 mNext = element; 14068 } 14069 14070 public InvalidateInfo getNextPoolable() { 14071 return mNext; 14072 } 14073 14074 static InvalidateInfo acquire() { 14075 return sPool.acquire(); 14076 } 14077 14078 void release() { 14079 sPool.release(this); 14080 } 14081 14082 public boolean isPooled() { 14083 return mIsPooled; 14084 } 14085 14086 public void setPooled(boolean isPooled) { 14087 mIsPooled = isPooled; 14088 } 14089 } 14090 14091 final IWindowSession mSession; 14092 14093 final IWindow mWindow; 14094 14095 final IBinder mWindowToken; 14096 14097 final Callbacks mRootCallbacks; 14098 14099 HardwareCanvas mHardwareCanvas; 14100 14101 /** 14102 * The top view of the hierarchy. 14103 */ 14104 View mRootView; 14105 14106 IBinder mPanelParentWindowToken; 14107 Surface mSurface; 14108 14109 boolean mHardwareAccelerated; 14110 boolean mHardwareAccelerationRequested; 14111 HardwareRenderer mHardwareRenderer; 14112 14113 /** 14114 * Scale factor used by the compatibility mode 14115 */ 14116 float mApplicationScale; 14117 14118 /** 14119 * Indicates whether the application is in compatibility mode 14120 */ 14121 boolean mScalingRequired; 14122 14123 /** 14124 * If set, ViewAncestor doesn't use its lame animation for when the window resizes. 14125 */ 14126 boolean mTurnOffWindowResizeAnim; 14127 14128 /** 14129 * Left position of this view's window 14130 */ 14131 int mWindowLeft; 14132 14133 /** 14134 * Top position of this view's window 14135 */ 14136 int mWindowTop; 14137 14138 /** 14139 * Indicates whether views need to use 32-bit drawing caches 14140 */ 14141 boolean mUse32BitDrawingCache; 14142 14143 /** 14144 * For windows that are full-screen but using insets to layout inside 14145 * of the screen decorations, these are the current insets for the 14146 * content of the window. 14147 */ 14148 final Rect mContentInsets = new Rect(); 14149 14150 /** 14151 * For windows that are full-screen but using insets to layout inside 14152 * of the screen decorations, these are the current insets for the 14153 * actual visible parts of the window. 14154 */ 14155 final Rect mVisibleInsets = new Rect(); 14156 14157 /** 14158 * The internal insets given by this window. This value is 14159 * supplied by the client (through 14160 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 14161 * be given to the window manager when changed to be used in laying 14162 * out windows behind it. 14163 */ 14164 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 14165 = new ViewTreeObserver.InternalInsetsInfo(); 14166 14167 /** 14168 * All views in the window's hierarchy that serve as scroll containers, 14169 * used to determine if the window can be resized or must be panned 14170 * to adjust for a soft input area. 14171 */ 14172 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 14173 14174 final KeyEvent.DispatcherState mKeyDispatchState 14175 = new KeyEvent.DispatcherState(); 14176 14177 /** 14178 * Indicates whether the view's window currently has the focus. 14179 */ 14180 boolean mHasWindowFocus; 14181 14182 /** 14183 * The current visibility of the window. 14184 */ 14185 int mWindowVisibility; 14186 14187 /** 14188 * Indicates the time at which drawing started to occur. 14189 */ 14190 long mDrawingTime; 14191 14192 /** 14193 * Indicates whether or not ignoring the DIRTY_MASK flags. 14194 */ 14195 boolean mIgnoreDirtyState; 14196 14197 /** 14198 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 14199 * to avoid clearing that flag prematurely. 14200 */ 14201 boolean mSetIgnoreDirtyState = false; 14202 14203 /** 14204 * Indicates whether the view's window is currently in touch mode. 14205 */ 14206 boolean mInTouchMode; 14207 14208 /** 14209 * Indicates that ViewAncestor should trigger a global layout change 14210 * the next time it performs a traversal 14211 */ 14212 boolean mRecomputeGlobalAttributes; 14213 14214 /** 14215 * Set during a traveral if any views want to keep the screen on. 14216 */ 14217 boolean mKeepScreenOn; 14218 14219 /** 14220 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 14221 */ 14222 int mSystemUiVisibility; 14223 14224 /** 14225 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 14226 * attached. 14227 */ 14228 boolean mHasSystemUiListeners; 14229 14230 /** 14231 * Set if the visibility of any views has changed. 14232 */ 14233 boolean mViewVisibilityChanged; 14234 14235 /** 14236 * Set to true if a view has been scrolled. 14237 */ 14238 boolean mViewScrollChanged; 14239 14240 /** 14241 * Global to the view hierarchy used as a temporary for dealing with 14242 * x/y points in the transparent region computations. 14243 */ 14244 final int[] mTransparentLocation = new int[2]; 14245 14246 /** 14247 * Global to the view hierarchy used as a temporary for dealing with 14248 * x/y points in the ViewGroup.invalidateChild implementation. 14249 */ 14250 final int[] mInvalidateChildLocation = new int[2]; 14251 14252 14253 /** 14254 * Global to the view hierarchy used as a temporary for dealing with 14255 * x/y location when view is transformed. 14256 */ 14257 final float[] mTmpTransformLocation = new float[2]; 14258 14259 /** 14260 * The view tree observer used to dispatch global events like 14261 * layout, pre-draw, touch mode change, etc. 14262 */ 14263 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 14264 14265 /** 14266 * A Canvas used by the view hierarchy to perform bitmap caching. 14267 */ 14268 Canvas mCanvas; 14269 14270 /** 14271 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 14272 * handler can be used to pump events in the UI events queue. 14273 */ 14274 final Handler mHandler; 14275 14276 /** 14277 * Identifier for messages requesting the view to be invalidated. 14278 * Such messages should be sent to {@link #mHandler}. 14279 */ 14280 static final int INVALIDATE_MSG = 0x1; 14281 14282 /** 14283 * Identifier for messages requesting the view to invalidate a region. 14284 * Such messages should be sent to {@link #mHandler}. 14285 */ 14286 static final int INVALIDATE_RECT_MSG = 0x2; 14287 14288 /** 14289 * Temporary for use in computing invalidate rectangles while 14290 * calling up the hierarchy. 14291 */ 14292 final Rect mTmpInvalRect = new Rect(); 14293 14294 /** 14295 * Temporary for use in computing hit areas with transformed views 14296 */ 14297 final RectF mTmpTransformRect = new RectF(); 14298 14299 /** 14300 * Temporary list for use in collecting focusable descendents of a view. 14301 */ 14302 final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24); 14303 14304 /** 14305 * The id of the window for accessibility purposes. 14306 */ 14307 int mAccessibilityWindowId = View.NO_ID; 14308 14309 /** 14310 * Creates a new set of attachment information with the specified 14311 * events handler and thread. 14312 * 14313 * @param handler the events handler the view must use 14314 */ 14315 AttachInfo(IWindowSession session, IWindow window, 14316 Handler handler, Callbacks effectPlayer) { 14317 mSession = session; 14318 mWindow = window; 14319 mWindowToken = window.asBinder(); 14320 mHandler = handler; 14321 mRootCallbacks = effectPlayer; 14322 } 14323 } 14324 14325 /** 14326 * <p>ScrollabilityCache holds various fields used by a View when scrolling 14327 * is supported. This avoids keeping too many unused fields in most 14328 * instances of View.</p> 14329 */ 14330 private static class ScrollabilityCache implements Runnable { 14331 14332 /** 14333 * Scrollbars are not visible 14334 */ 14335 public static final int OFF = 0; 14336 14337 /** 14338 * Scrollbars are visible 14339 */ 14340 public static final int ON = 1; 14341 14342 /** 14343 * Scrollbars are fading away 14344 */ 14345 public static final int FADING = 2; 14346 14347 public boolean fadeScrollBars; 14348 14349 public int fadingEdgeLength; 14350 public int scrollBarDefaultDelayBeforeFade; 14351 public int scrollBarFadeDuration; 14352 14353 public int scrollBarSize; 14354 public ScrollBarDrawable scrollBar; 14355 public float[] interpolatorValues; 14356 public View host; 14357 14358 public final Paint paint; 14359 public final Matrix matrix; 14360 public Shader shader; 14361 14362 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 14363 14364 private static final float[] OPAQUE = { 255 }; 14365 private static final float[] TRANSPARENT = { 0.0f }; 14366 14367 /** 14368 * When fading should start. This time moves into the future every time 14369 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 14370 */ 14371 public long fadeStartTime; 14372 14373 14374 /** 14375 * The current state of the scrollbars: ON, OFF, or FADING 14376 */ 14377 public int state = OFF; 14378 14379 private int mLastColor; 14380 14381 public ScrollabilityCache(ViewConfiguration configuration, View host) { 14382 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 14383 scrollBarSize = configuration.getScaledScrollBarSize(); 14384 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 14385 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 14386 14387 paint = new Paint(); 14388 matrix = new Matrix(); 14389 // use use a height of 1, and then wack the matrix each time we 14390 // actually use it. 14391 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 14392 14393 paint.setShader(shader); 14394 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 14395 this.host = host; 14396 } 14397 14398 public void setFadeColor(int color) { 14399 if (color != 0 && color != mLastColor) { 14400 mLastColor = color; 14401 color |= 0xFF000000; 14402 14403 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 14404 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 14405 14406 paint.setShader(shader); 14407 // Restore the default transfer mode (src_over) 14408 paint.setXfermode(null); 14409 } 14410 } 14411 14412 public void run() { 14413 long now = AnimationUtils.currentAnimationTimeMillis(); 14414 if (now >= fadeStartTime) { 14415 14416 // the animation fades the scrollbars out by changing 14417 // the opacity (alpha) from fully opaque to fully 14418 // transparent 14419 int nextFrame = (int) now; 14420 int framesCount = 0; 14421 14422 Interpolator interpolator = scrollBarInterpolator; 14423 14424 // Start opaque 14425 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 14426 14427 // End transparent 14428 nextFrame += scrollBarFadeDuration; 14429 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 14430 14431 state = FADING; 14432 14433 // Kick off the fade animation 14434 host.invalidate(true); 14435 } 14436 } 14437 } 14438 14439 /** 14440 * Resuable callback for sending 14441 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 14442 */ 14443 private class SendViewScrolledAccessibilityEvent implements Runnable { 14444 public volatile boolean mIsPending; 14445 14446 public void run() { 14447 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 14448 mIsPending = false; 14449 } 14450 } 14451 14452 /** 14453 * <p> 14454 * This class represents a delegate that can be registered in a {@link View} 14455 * to enhance accessibility support via composition rather via inheritance. 14456 * It is specifically targeted to widget developers that extend basic View 14457 * classes i.e. classes in package android.view, that would like their 14458 * applications to be backwards compatible. 14459 * </p> 14460 * <p> 14461 * A scenario in which a developer would like to use an accessibility delegate 14462 * is overriding a method introduced in a later API version then the minimal API 14463 * version supported by the application. For example, the method 14464 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 14465 * in API version 4 when the accessibility APIs were first introduced. If a 14466 * developer would like his application to run on API version 4 devices (assuming 14467 * all other APIs used by the application are version 4 or lower) and take advantage 14468 * of this method, instead of overriding the method which would break the application's 14469 * backwards compatibility, he can override the corresponding method in this 14470 * delegate and register the delegate in the target View if the API version of 14471 * the system is high enough i.e. the API version is same or higher to the API 14472 * version that introduced 14473 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 14474 * </p> 14475 * <p> 14476 * Here is an example implementation: 14477 * </p> 14478 * <code><pre><p> 14479 * if (Build.VERSION.SDK_INT >= 14) { 14480 * // If the API version is equal of higher than the version in 14481 * // which onInitializeAccessibilityNodeInfo was introduced we 14482 * // register a delegate with a customized implementation. 14483 * View view = findViewById(R.id.view_id); 14484 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 14485 * public void onInitializeAccessibilityNodeInfo(View host, 14486 * AccessibilityNodeInfo info) { 14487 * // Let the default implementation populate the info. 14488 * super.onInitializeAccessibilityNodeInfo(host, info); 14489 * // Set some other information. 14490 * info.setEnabled(host.isEnabled()); 14491 * } 14492 * }); 14493 * } 14494 * </code></pre></p> 14495 * <p> 14496 * This delegate contains methods that correspond to the accessibility methods 14497 * in View. If a delegate has been specified the implementation in View hands 14498 * off handling to the corresponding method in this delegate. The default 14499 * implementation the delegate methods behaves exactly as the corresponding 14500 * method in View for the case of no accessibility delegate been set. Hence, 14501 * to customize the behavior of a View method, clients can override only the 14502 * corresponding delegate method without altering the behavior of the rest 14503 * accessibility related methods of the host view. 14504 * </p> 14505 */ 14506 public static class AccessibilityDelegate { 14507 14508 /** 14509 * Sends an accessibility event of the given type. If accessibility is not 14510 * enabled this method has no effect. 14511 * <p> 14512 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 14513 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 14514 * been set. 14515 * </p> 14516 * 14517 * @param host The View hosting the delegate. 14518 * @param eventType The type of the event to send. 14519 * 14520 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 14521 */ 14522 public void sendAccessibilityEvent(View host, int eventType) { 14523 host.sendAccessibilityEventInternal(eventType); 14524 } 14525 14526 /** 14527 * Sends an accessibility event. This method behaves exactly as 14528 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 14529 * empty {@link AccessibilityEvent} and does not perform a check whether 14530 * accessibility is enabled. 14531 * <p> 14532 * The default implementation behaves as 14533 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 14534 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 14535 * the case of no accessibility delegate been set. 14536 * </p> 14537 * 14538 * @param host The View hosting the delegate. 14539 * @param event The event to send. 14540 * 14541 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 14542 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 14543 */ 14544 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 14545 host.sendAccessibilityEventUncheckedInternal(event); 14546 } 14547 14548 /** 14549 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 14550 * to its children for adding their text content to the event. 14551 * <p> 14552 * The default implementation behaves as 14553 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 14554 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 14555 * the case of no accessibility delegate been set. 14556 * </p> 14557 * 14558 * @param host The View hosting the delegate. 14559 * @param event The event. 14560 * @return True if the event population was completed. 14561 * 14562 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 14563 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 14564 */ 14565 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 14566 return host.dispatchPopulateAccessibilityEventInternal(event); 14567 } 14568 14569 /** 14570 * Gives a chance to the host View to populate the accessibility event with its 14571 * text content. 14572 * <p> 14573 * The default implementation behaves as 14574 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 14575 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 14576 * the case of no accessibility delegate been set. 14577 * </p> 14578 * 14579 * @param host The View hosting the delegate. 14580 * @param event The accessibility event which to populate. 14581 * 14582 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 14583 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 14584 */ 14585 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 14586 host.onPopulateAccessibilityEventInternal(event); 14587 } 14588 14589 /** 14590 * Initializes an {@link AccessibilityEvent} with information about the 14591 * the host View which is the event source. 14592 * <p> 14593 * The default implementation behaves as 14594 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 14595 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 14596 * the case of no accessibility delegate been set. 14597 * </p> 14598 * 14599 * @param host The View hosting the delegate. 14600 * @param event The event to initialize. 14601 * 14602 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 14603 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 14604 */ 14605 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 14606 host.onInitializeAccessibilityEventInternal(event); 14607 } 14608 14609 /** 14610 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 14611 * <p> 14612 * The default implementation behaves as 14613 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 14614 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 14615 * the case of no accessibility delegate been set. 14616 * </p> 14617 * 14618 * @param host The View hosting the delegate. 14619 * @param info The instance to initialize. 14620 * 14621 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 14622 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 14623 */ 14624 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 14625 host.onInitializeAccessibilityNodeInfoInternal(info); 14626 } 14627 14628 /** 14629 * Called when a child of the host View has requested sending an 14630 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 14631 * to augment the event. 14632 * <p> 14633 * The default implementation behaves as 14634 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 14635 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 14636 * the case of no accessibility delegate been set. 14637 * </p> 14638 * 14639 * @param host The View hosting the delegate. 14640 * @param child The child which requests sending the event. 14641 * @param event The event to be sent. 14642 * @return True if the event should be sent 14643 * 14644 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 14645 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 14646 */ 14647 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 14648 AccessibilityEvent event) { 14649 return host.onRequestSendAccessibilityEventInternal(child, event); 14650 } 14651 } 14652} 14653