View.java revision 2b04cef9b49ae5bd5ff197124f2dfcf97af71d09
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.Callback2, KeyEvent.Callback, AccessibilityEventSource { 640 private static final boolean DBG = false; 641 642 /** 643 * The logging tag used by this class with android.util.Log. 644 */ 645 protected static final String VIEW_LOG_TAG = "View"; 646 647 /** 648 * Used to mark a View that has no ID. 649 */ 650 public static final int NO_ID = -1; 651 652 /** 653 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 654 * calling setFlags. 655 */ 656 private static final int NOT_FOCUSABLE = 0x00000000; 657 658 /** 659 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 660 * setFlags. 661 */ 662 private static final int FOCUSABLE = 0x00000001; 663 664 /** 665 * Mask for use with setFlags indicating bits used for focus. 666 */ 667 private static final int FOCUSABLE_MASK = 0x00000001; 668 669 /** 670 * This view will adjust its padding to fit sytem windows (e.g. status bar) 671 */ 672 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 673 674 /** 675 * This view is visible. 676 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 677 * android:visibility}. 678 */ 679 public static final int VISIBLE = 0x00000000; 680 681 /** 682 * This view is invisible, but it still takes up space for layout purposes. 683 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 684 * android:visibility}. 685 */ 686 public static final int INVISIBLE = 0x00000004; 687 688 /** 689 * This view is invisible, and it doesn't take any space for layout 690 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 691 * android:visibility}. 692 */ 693 public static final int GONE = 0x00000008; 694 695 /** 696 * Mask for use with setFlags indicating bits used for visibility. 697 * {@hide} 698 */ 699 static final int VISIBILITY_MASK = 0x0000000C; 700 701 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 702 703 /** 704 * This view is enabled. Intrepretation varies by subclass. 705 * Use with ENABLED_MASK when calling setFlags. 706 * {@hide} 707 */ 708 static final int ENABLED = 0x00000000; 709 710 /** 711 * This view is disabled. Intrepretation varies by subclass. 712 * Use with ENABLED_MASK when calling setFlags. 713 * {@hide} 714 */ 715 static final int DISABLED = 0x00000020; 716 717 /** 718 * Mask for use with setFlags indicating bits used for indicating whether 719 * this view is enabled 720 * {@hide} 721 */ 722 static final int ENABLED_MASK = 0x00000020; 723 724 /** 725 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 726 * called and further optimizations will be performed. It is okay to have 727 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 728 * {@hide} 729 */ 730 static final int WILL_NOT_DRAW = 0x00000080; 731 732 /** 733 * Mask for use with setFlags indicating bits used for indicating whether 734 * this view is will draw 735 * {@hide} 736 */ 737 static final int DRAW_MASK = 0x00000080; 738 739 /** 740 * <p>This view doesn't show scrollbars.</p> 741 * {@hide} 742 */ 743 static final int SCROLLBARS_NONE = 0x00000000; 744 745 /** 746 * <p>This view shows horizontal scrollbars.</p> 747 * {@hide} 748 */ 749 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 750 751 /** 752 * <p>This view shows vertical scrollbars.</p> 753 * {@hide} 754 */ 755 static final int SCROLLBARS_VERTICAL = 0x00000200; 756 757 /** 758 * <p>Mask for use with setFlags indicating bits used for indicating which 759 * scrollbars are enabled.</p> 760 * {@hide} 761 */ 762 static final int SCROLLBARS_MASK = 0x00000300; 763 764 /** 765 * Indicates that the view should filter touches when its window is obscured. 766 * Refer to the class comments for more information about this security feature. 767 * {@hide} 768 */ 769 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 770 771 // note flag value 0x00000800 is now available for next flags... 772 773 /** 774 * <p>This view doesn't show fading edges.</p> 775 * {@hide} 776 */ 777 static final int FADING_EDGE_NONE = 0x00000000; 778 779 /** 780 * <p>This view shows horizontal fading edges.</p> 781 * {@hide} 782 */ 783 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 784 785 /** 786 * <p>This view shows vertical fading edges.</p> 787 * {@hide} 788 */ 789 static final int FADING_EDGE_VERTICAL = 0x00002000; 790 791 /** 792 * <p>Mask for use with setFlags indicating bits used for indicating which 793 * fading edges are enabled.</p> 794 * {@hide} 795 */ 796 static final int FADING_EDGE_MASK = 0x00003000; 797 798 /** 799 * <p>Indicates this view can be clicked. When clickable, a View reacts 800 * to clicks by notifying the OnClickListener.<p> 801 * {@hide} 802 */ 803 static final int CLICKABLE = 0x00004000; 804 805 /** 806 * <p>Indicates this view is caching its drawing into a bitmap.</p> 807 * {@hide} 808 */ 809 static final int DRAWING_CACHE_ENABLED = 0x00008000; 810 811 /** 812 * <p>Indicates that no icicle should be saved for this view.<p> 813 * {@hide} 814 */ 815 static final int SAVE_DISABLED = 0x000010000; 816 817 /** 818 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 819 * property.</p> 820 * {@hide} 821 */ 822 static final int SAVE_DISABLED_MASK = 0x000010000; 823 824 /** 825 * <p>Indicates that no drawing cache should ever be created for this view.<p> 826 * {@hide} 827 */ 828 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 829 830 /** 831 * <p>Indicates this view can take / keep focus when int touch mode.</p> 832 * {@hide} 833 */ 834 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 835 836 /** 837 * <p>Enables low quality mode for the drawing cache.</p> 838 */ 839 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 840 841 /** 842 * <p>Enables high quality mode for the drawing cache.</p> 843 */ 844 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 845 846 /** 847 * <p>Enables automatic quality mode for the drawing cache.</p> 848 */ 849 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 850 851 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 852 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 853 }; 854 855 /** 856 * <p>Mask for use with setFlags indicating bits used for the cache 857 * quality property.</p> 858 * {@hide} 859 */ 860 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 861 862 /** 863 * <p> 864 * Indicates this view can be long clicked. When long clickable, a View 865 * reacts to long clicks by notifying the OnLongClickListener or showing a 866 * context menu. 867 * </p> 868 * {@hide} 869 */ 870 static final int LONG_CLICKABLE = 0x00200000; 871 872 /** 873 * <p>Indicates that this view gets its drawable states from its direct parent 874 * and ignores its original internal states.</p> 875 * 876 * @hide 877 */ 878 static final int DUPLICATE_PARENT_STATE = 0x00400000; 879 880 /** 881 * The scrollbar style to display the scrollbars inside the content area, 882 * without increasing the padding. The scrollbars will be overlaid with 883 * translucency on the view's content. 884 */ 885 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 886 887 /** 888 * The scrollbar style to display the scrollbars inside the padded area, 889 * increasing the padding of the view. The scrollbars will not overlap the 890 * content area of the view. 891 */ 892 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 893 894 /** 895 * The scrollbar style to display the scrollbars at the edge of the view, 896 * without increasing the padding. The scrollbars will be overlaid with 897 * translucency. 898 */ 899 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 900 901 /** 902 * The scrollbar style to display the scrollbars at the edge of the view, 903 * increasing the padding of the view. The scrollbars will only overlap the 904 * background, if any. 905 */ 906 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 907 908 /** 909 * Mask to check if the scrollbar style is overlay or inset. 910 * {@hide} 911 */ 912 static final int SCROLLBARS_INSET_MASK = 0x01000000; 913 914 /** 915 * Mask to check if the scrollbar style is inside or outside. 916 * {@hide} 917 */ 918 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 919 920 /** 921 * Mask for scrollbar style. 922 * {@hide} 923 */ 924 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 925 926 /** 927 * View flag indicating that the screen should remain on while the 928 * window containing this view is visible to the user. This effectively 929 * takes care of automatically setting the WindowManager's 930 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 931 */ 932 public static final int KEEP_SCREEN_ON = 0x04000000; 933 934 /** 935 * View flag indicating whether this view should have sound effects enabled 936 * for events such as clicking and touching. 937 */ 938 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 939 940 /** 941 * View flag indicating whether this view should have haptic feedback 942 * enabled for events such as long presses. 943 */ 944 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 945 946 /** 947 * <p>Indicates that the view hierarchy should stop saving state when 948 * it reaches this view. If state saving is initiated immediately at 949 * the view, it will be allowed. 950 * {@hide} 951 */ 952 static final int PARENT_SAVE_DISABLED = 0x20000000; 953 954 /** 955 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 956 * {@hide} 957 */ 958 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 959 960 /** 961 * Horizontal direction of this view is from Left to Right. 962 * Use with {@link #setLayoutDirection}. 963 * {@hide} 964 */ 965 public static final int LAYOUT_DIRECTION_LTR = 0x00000000; 966 967 /** 968 * Horizontal direction of this view is from Right to Left. 969 * Use with {@link #setLayoutDirection}. 970 * {@hide} 971 */ 972 public static final int LAYOUT_DIRECTION_RTL = 0x40000000; 973 974 /** 975 * Horizontal direction of this view is inherited from its parent. 976 * Use with {@link #setLayoutDirection}. 977 * {@hide} 978 */ 979 public static final int LAYOUT_DIRECTION_INHERIT = 0x80000000; 980 981 /** 982 * Horizontal direction of this view is from deduced from the default language 983 * script for the locale. Use with {@link #setLayoutDirection}. 984 * {@hide} 985 */ 986 public static final int LAYOUT_DIRECTION_LOCALE = 0xC0000000; 987 988 /** 989 * Mask for use with setFlags indicating bits used for horizontalDirection. 990 * {@hide} 991 */ 992 static final int LAYOUT_DIRECTION_MASK = 0xC0000000; 993 994 /* 995 * Array of horizontal direction flags for mapping attribute "horizontalDirection" to correct 996 * flag value. 997 * {@hide} 998 */ 999 private static final int[] LAYOUT_DIRECTION_FLAGS = {LAYOUT_DIRECTION_LTR, 1000 LAYOUT_DIRECTION_RTL, LAYOUT_DIRECTION_INHERIT, LAYOUT_DIRECTION_LOCALE}; 1001 1002 /** 1003 * Default horizontalDirection. 1004 * {@hide} 1005 */ 1006 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 1007 1008 /** 1009 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1010 * should add all focusable Views regardless if they are focusable in touch mode. 1011 */ 1012 public static final int FOCUSABLES_ALL = 0x00000000; 1013 1014 /** 1015 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1016 * should add only Views focusable in touch mode. 1017 */ 1018 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1019 1020 /** 1021 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1022 * item. 1023 */ 1024 public static final int FOCUS_BACKWARD = 0x00000001; 1025 1026 /** 1027 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1028 * item. 1029 */ 1030 public static final int FOCUS_FORWARD = 0x00000002; 1031 1032 /** 1033 * Use with {@link #focusSearch(int)}. Move focus to the left. 1034 */ 1035 public static final int FOCUS_LEFT = 0x00000011; 1036 1037 /** 1038 * Use with {@link #focusSearch(int)}. Move focus up. 1039 */ 1040 public static final int FOCUS_UP = 0x00000021; 1041 1042 /** 1043 * Use with {@link #focusSearch(int)}. Move focus to the right. 1044 */ 1045 public static final int FOCUS_RIGHT = 0x00000042; 1046 1047 /** 1048 * Use with {@link #focusSearch(int)}. Move focus down. 1049 */ 1050 public static final int FOCUS_DOWN = 0x00000082; 1051 1052 /** 1053 * Bits of {@link #getMeasuredWidthAndState()} and 1054 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1055 */ 1056 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1057 1058 /** 1059 * Bits of {@link #getMeasuredWidthAndState()} and 1060 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1061 */ 1062 public static final int MEASURED_STATE_MASK = 0xff000000; 1063 1064 /** 1065 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1066 * for functions that combine both width and height into a single int, 1067 * such as {@link #getMeasuredState()} and the childState argument of 1068 * {@link #resolveSizeAndState(int, int, int)}. 1069 */ 1070 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1071 1072 /** 1073 * Bit of {@link #getMeasuredWidthAndState()} and 1074 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1075 * is smaller that the space the view would like to have. 1076 */ 1077 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1078 1079 /** 1080 * Base View state sets 1081 */ 1082 // Singles 1083 /** 1084 * Indicates the view has no states set. States are used with 1085 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1086 * view depending on its state. 1087 * 1088 * @see android.graphics.drawable.Drawable 1089 * @see #getDrawableState() 1090 */ 1091 protected static final int[] EMPTY_STATE_SET; 1092 /** 1093 * Indicates the view is enabled. States are used with 1094 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1095 * view depending on its state. 1096 * 1097 * @see android.graphics.drawable.Drawable 1098 * @see #getDrawableState() 1099 */ 1100 protected static final int[] ENABLED_STATE_SET; 1101 /** 1102 * Indicates the view is focused. States are used with 1103 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1104 * view depending on its state. 1105 * 1106 * @see android.graphics.drawable.Drawable 1107 * @see #getDrawableState() 1108 */ 1109 protected static final int[] FOCUSED_STATE_SET; 1110 /** 1111 * Indicates the view is selected. States are used with 1112 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1113 * view depending on its state. 1114 * 1115 * @see android.graphics.drawable.Drawable 1116 * @see #getDrawableState() 1117 */ 1118 protected static final int[] SELECTED_STATE_SET; 1119 /** 1120 * Indicates the view is pressed. States are used with 1121 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1122 * view depending on its state. 1123 * 1124 * @see android.graphics.drawable.Drawable 1125 * @see #getDrawableState() 1126 * @hide 1127 */ 1128 protected static final int[] PRESSED_STATE_SET; 1129 /** 1130 * Indicates the view's window has focus. States are used with 1131 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1132 * view depending on its state. 1133 * 1134 * @see android.graphics.drawable.Drawable 1135 * @see #getDrawableState() 1136 */ 1137 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1138 // Doubles 1139 /** 1140 * Indicates the view is enabled and has the focus. 1141 * 1142 * @see #ENABLED_STATE_SET 1143 * @see #FOCUSED_STATE_SET 1144 */ 1145 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1146 /** 1147 * Indicates the view is enabled and selected. 1148 * 1149 * @see #ENABLED_STATE_SET 1150 * @see #SELECTED_STATE_SET 1151 */ 1152 protected static final int[] ENABLED_SELECTED_STATE_SET; 1153 /** 1154 * Indicates the view is enabled and that its window has focus. 1155 * 1156 * @see #ENABLED_STATE_SET 1157 * @see #WINDOW_FOCUSED_STATE_SET 1158 */ 1159 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1160 /** 1161 * Indicates the view is focused and selected. 1162 * 1163 * @see #FOCUSED_STATE_SET 1164 * @see #SELECTED_STATE_SET 1165 */ 1166 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1167 /** 1168 * Indicates the view has the focus and that its window has the focus. 1169 * 1170 * @see #FOCUSED_STATE_SET 1171 * @see #WINDOW_FOCUSED_STATE_SET 1172 */ 1173 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1174 /** 1175 * Indicates the view is selected and that its window has the focus. 1176 * 1177 * @see #SELECTED_STATE_SET 1178 * @see #WINDOW_FOCUSED_STATE_SET 1179 */ 1180 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1181 // Triples 1182 /** 1183 * Indicates the view is enabled, focused and selected. 1184 * 1185 * @see #ENABLED_STATE_SET 1186 * @see #FOCUSED_STATE_SET 1187 * @see #SELECTED_STATE_SET 1188 */ 1189 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1190 /** 1191 * Indicates the view is enabled, focused and its window has the focus. 1192 * 1193 * @see #ENABLED_STATE_SET 1194 * @see #FOCUSED_STATE_SET 1195 * @see #WINDOW_FOCUSED_STATE_SET 1196 */ 1197 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1198 /** 1199 * Indicates the view is enabled, selected and its window has the focus. 1200 * 1201 * @see #ENABLED_STATE_SET 1202 * @see #SELECTED_STATE_SET 1203 * @see #WINDOW_FOCUSED_STATE_SET 1204 */ 1205 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1206 /** 1207 * Indicates the view is focused, selected and its window has the focus. 1208 * 1209 * @see #FOCUSED_STATE_SET 1210 * @see #SELECTED_STATE_SET 1211 * @see #WINDOW_FOCUSED_STATE_SET 1212 */ 1213 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1214 /** 1215 * Indicates the view is enabled, focused, selected and its window 1216 * has the focus. 1217 * 1218 * @see #ENABLED_STATE_SET 1219 * @see #FOCUSED_STATE_SET 1220 * @see #SELECTED_STATE_SET 1221 * @see #WINDOW_FOCUSED_STATE_SET 1222 */ 1223 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1224 /** 1225 * Indicates the view is pressed and its window has the focus. 1226 * 1227 * @see #PRESSED_STATE_SET 1228 * @see #WINDOW_FOCUSED_STATE_SET 1229 */ 1230 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1231 /** 1232 * Indicates the view is pressed and selected. 1233 * 1234 * @see #PRESSED_STATE_SET 1235 * @see #SELECTED_STATE_SET 1236 */ 1237 protected static final int[] PRESSED_SELECTED_STATE_SET; 1238 /** 1239 * Indicates the view is pressed, selected and its window has the focus. 1240 * 1241 * @see #PRESSED_STATE_SET 1242 * @see #SELECTED_STATE_SET 1243 * @see #WINDOW_FOCUSED_STATE_SET 1244 */ 1245 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1246 /** 1247 * Indicates the view is pressed and focused. 1248 * 1249 * @see #PRESSED_STATE_SET 1250 * @see #FOCUSED_STATE_SET 1251 */ 1252 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1253 /** 1254 * Indicates the view is pressed, focused and its window has the focus. 1255 * 1256 * @see #PRESSED_STATE_SET 1257 * @see #FOCUSED_STATE_SET 1258 * @see #WINDOW_FOCUSED_STATE_SET 1259 */ 1260 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1261 /** 1262 * Indicates the view is pressed, focused and selected. 1263 * 1264 * @see #PRESSED_STATE_SET 1265 * @see #SELECTED_STATE_SET 1266 * @see #FOCUSED_STATE_SET 1267 */ 1268 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1269 /** 1270 * Indicates the view is pressed, focused, selected and its window has the focus. 1271 * 1272 * @see #PRESSED_STATE_SET 1273 * @see #FOCUSED_STATE_SET 1274 * @see #SELECTED_STATE_SET 1275 * @see #WINDOW_FOCUSED_STATE_SET 1276 */ 1277 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1278 /** 1279 * Indicates the view is pressed and enabled. 1280 * 1281 * @see #PRESSED_STATE_SET 1282 * @see #ENABLED_STATE_SET 1283 */ 1284 protected static final int[] PRESSED_ENABLED_STATE_SET; 1285 /** 1286 * Indicates the view is pressed, enabled and its window has the focus. 1287 * 1288 * @see #PRESSED_STATE_SET 1289 * @see #ENABLED_STATE_SET 1290 * @see #WINDOW_FOCUSED_STATE_SET 1291 */ 1292 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1293 /** 1294 * Indicates the view is pressed, enabled and selected. 1295 * 1296 * @see #PRESSED_STATE_SET 1297 * @see #ENABLED_STATE_SET 1298 * @see #SELECTED_STATE_SET 1299 */ 1300 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1301 /** 1302 * Indicates the view is pressed, enabled, selected and its window has the 1303 * focus. 1304 * 1305 * @see #PRESSED_STATE_SET 1306 * @see #ENABLED_STATE_SET 1307 * @see #SELECTED_STATE_SET 1308 * @see #WINDOW_FOCUSED_STATE_SET 1309 */ 1310 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1311 /** 1312 * Indicates the view is pressed, enabled and focused. 1313 * 1314 * @see #PRESSED_STATE_SET 1315 * @see #ENABLED_STATE_SET 1316 * @see #FOCUSED_STATE_SET 1317 */ 1318 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1319 /** 1320 * Indicates the view is pressed, enabled, focused and its window has the 1321 * focus. 1322 * 1323 * @see #PRESSED_STATE_SET 1324 * @see #ENABLED_STATE_SET 1325 * @see #FOCUSED_STATE_SET 1326 * @see #WINDOW_FOCUSED_STATE_SET 1327 */ 1328 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1329 /** 1330 * Indicates the view is pressed, enabled, focused and selected. 1331 * 1332 * @see #PRESSED_STATE_SET 1333 * @see #ENABLED_STATE_SET 1334 * @see #SELECTED_STATE_SET 1335 * @see #FOCUSED_STATE_SET 1336 */ 1337 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1338 /** 1339 * Indicates the view is pressed, enabled, focused, selected and its window 1340 * has the focus. 1341 * 1342 * @see #PRESSED_STATE_SET 1343 * @see #ENABLED_STATE_SET 1344 * @see #SELECTED_STATE_SET 1345 * @see #FOCUSED_STATE_SET 1346 * @see #WINDOW_FOCUSED_STATE_SET 1347 */ 1348 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1349 1350 /** 1351 * The order here is very important to {@link #getDrawableState()} 1352 */ 1353 private static final int[][] VIEW_STATE_SETS; 1354 1355 static final int VIEW_STATE_WINDOW_FOCUSED = 1; 1356 static final int VIEW_STATE_SELECTED = 1 << 1; 1357 static final int VIEW_STATE_FOCUSED = 1 << 2; 1358 static final int VIEW_STATE_ENABLED = 1 << 3; 1359 static final int VIEW_STATE_PRESSED = 1 << 4; 1360 static final int VIEW_STATE_ACTIVATED = 1 << 5; 1361 static final int VIEW_STATE_ACCELERATED = 1 << 6; 1362 static final int VIEW_STATE_HOVERED = 1 << 7; 1363 static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8; 1364 static final int VIEW_STATE_DRAG_HOVERED = 1 << 9; 1365 1366 static final int[] VIEW_STATE_IDS = new int[] { 1367 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED, 1368 R.attr.state_selected, VIEW_STATE_SELECTED, 1369 R.attr.state_focused, VIEW_STATE_FOCUSED, 1370 R.attr.state_enabled, VIEW_STATE_ENABLED, 1371 R.attr.state_pressed, VIEW_STATE_PRESSED, 1372 R.attr.state_activated, VIEW_STATE_ACTIVATED, 1373 R.attr.state_accelerated, VIEW_STATE_ACCELERATED, 1374 R.attr.state_hovered, VIEW_STATE_HOVERED, 1375 R.attr.state_drag_can_accept, VIEW_STATE_DRAG_CAN_ACCEPT, 1376 R.attr.state_drag_hovered, VIEW_STATE_DRAG_HOVERED, 1377 }; 1378 1379 static { 1380 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) { 1381 throw new IllegalStateException( 1382 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array"); 1383 } 1384 int[] orderedIds = new int[VIEW_STATE_IDS.length]; 1385 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) { 1386 int viewState = R.styleable.ViewDrawableStates[i]; 1387 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) { 1388 if (VIEW_STATE_IDS[j] == viewState) { 1389 orderedIds[i * 2] = viewState; 1390 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1]; 1391 } 1392 } 1393 } 1394 final int NUM_BITS = VIEW_STATE_IDS.length / 2; 1395 VIEW_STATE_SETS = new int[1 << NUM_BITS][]; 1396 for (int i = 0; i < VIEW_STATE_SETS.length; i++) { 1397 int numBits = Integer.bitCount(i); 1398 int[] set = new int[numBits]; 1399 int pos = 0; 1400 for (int j = 0; j < orderedIds.length; j += 2) { 1401 if ((i & orderedIds[j+1]) != 0) { 1402 set[pos++] = orderedIds[j]; 1403 } 1404 } 1405 VIEW_STATE_SETS[i] = set; 1406 } 1407 1408 EMPTY_STATE_SET = VIEW_STATE_SETS[0]; 1409 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED]; 1410 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED]; 1411 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1412 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED]; 1413 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED]; 1414 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1415 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED]; 1416 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1417 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED]; 1418 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1419 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1420 | VIEW_STATE_FOCUSED]; 1421 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED]; 1422 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1423 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED]; 1424 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1425 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED]; 1426 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1427 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1428 | VIEW_STATE_ENABLED]; 1429 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1430 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED]; 1431 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1432 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1433 | VIEW_STATE_ENABLED]; 1434 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1435 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1436 | VIEW_STATE_ENABLED]; 1437 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1438 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1439 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED]; 1440 1441 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED]; 1442 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1443 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED]; 1444 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1445 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED]; 1446 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1447 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1448 | VIEW_STATE_PRESSED]; 1449 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1450 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1451 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1452 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1453 | VIEW_STATE_PRESSED]; 1454 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1455 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1456 | VIEW_STATE_PRESSED]; 1457 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1458 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1459 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1460 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[ 1461 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1462 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1463 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED 1464 | VIEW_STATE_PRESSED]; 1465 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1466 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED 1467 | VIEW_STATE_PRESSED]; 1468 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1469 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1470 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1471 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1472 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED 1473 | VIEW_STATE_PRESSED]; 1474 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1475 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1476 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1477 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1478 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1479 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1480 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1481 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1482 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED 1483 | VIEW_STATE_PRESSED]; 1484 } 1485 1486 /** 1487 * Temporary Rect currently for use in setBackground(). This will probably 1488 * be extended in the future to hold our own class with more than just 1489 * a Rect. :) 1490 */ 1491 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1492 1493 /** 1494 * Map used to store views' tags. 1495 */ 1496 private static WeakHashMap<View, SparseArray<Object>> sTags; 1497 1498 /** 1499 * Lock used to access sTags. 1500 */ 1501 private static final Object sTagsLock = new Object(); 1502 1503 /** 1504 * The next available accessiiblity id. 1505 */ 1506 private static int sNextAccessibilityViewId; 1507 1508 /** 1509 * The animation currently associated with this view. 1510 * @hide 1511 */ 1512 protected Animation mCurrentAnimation = null; 1513 1514 /** 1515 * Width as measured during measure pass. 1516 * {@hide} 1517 */ 1518 @ViewDebug.ExportedProperty(category = "measurement") 1519 int mMeasuredWidth; 1520 1521 /** 1522 * Height as measured during measure pass. 1523 * {@hide} 1524 */ 1525 @ViewDebug.ExportedProperty(category = "measurement") 1526 int mMeasuredHeight; 1527 1528 /** 1529 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1530 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1531 * its display list. This flag, used only when hw accelerated, allows us to clear the 1532 * flag while retaining this information until it's needed (at getDisplayList() time and 1533 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1534 * 1535 * {@hide} 1536 */ 1537 boolean mRecreateDisplayList = false; 1538 1539 /** 1540 * The view's identifier. 1541 * {@hide} 1542 * 1543 * @see #setId(int) 1544 * @see #getId() 1545 */ 1546 @ViewDebug.ExportedProperty(resolveId = true) 1547 int mID = NO_ID; 1548 1549 /** 1550 * The stable ID of this view for accessibility porposes. 1551 */ 1552 int mAccessibilityViewId = NO_ID; 1553 1554 /** 1555 * The view's tag. 1556 * {@hide} 1557 * 1558 * @see #setTag(Object) 1559 * @see #getTag() 1560 */ 1561 protected Object mTag; 1562 1563 // for mPrivateFlags: 1564 /** {@hide} */ 1565 static final int WANTS_FOCUS = 0x00000001; 1566 /** {@hide} */ 1567 static final int FOCUSED = 0x00000002; 1568 /** {@hide} */ 1569 static final int SELECTED = 0x00000004; 1570 /** {@hide} */ 1571 static final int IS_ROOT_NAMESPACE = 0x00000008; 1572 /** {@hide} */ 1573 static final int HAS_BOUNDS = 0x00000010; 1574 /** {@hide} */ 1575 static final int DRAWN = 0x00000020; 1576 /** 1577 * When this flag is set, this view is running an animation on behalf of its 1578 * children and should therefore not cancel invalidate requests, even if they 1579 * lie outside of this view's bounds. 1580 * 1581 * {@hide} 1582 */ 1583 static final int DRAW_ANIMATION = 0x00000040; 1584 /** {@hide} */ 1585 static final int SKIP_DRAW = 0x00000080; 1586 /** {@hide} */ 1587 static final int ONLY_DRAWS_BACKGROUND = 0x00000100; 1588 /** {@hide} */ 1589 static final int REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1590 /** {@hide} */ 1591 static final int DRAWABLE_STATE_DIRTY = 0x00000400; 1592 /** {@hide} */ 1593 static final int MEASURED_DIMENSION_SET = 0x00000800; 1594 /** {@hide} */ 1595 static final int FORCE_LAYOUT = 0x00001000; 1596 /** {@hide} */ 1597 static final int LAYOUT_REQUIRED = 0x00002000; 1598 1599 private static final int PRESSED = 0x00004000; 1600 1601 /** {@hide} */ 1602 static final int DRAWING_CACHE_VALID = 0x00008000; 1603 /** 1604 * Flag used to indicate that this view should be drawn once more (and only once 1605 * more) after its animation has completed. 1606 * {@hide} 1607 */ 1608 static final int ANIMATION_STARTED = 0x00010000; 1609 1610 private static final int SAVE_STATE_CALLED = 0x00020000; 1611 1612 /** 1613 * Indicates that the View returned true when onSetAlpha() was called and that 1614 * the alpha must be restored. 1615 * {@hide} 1616 */ 1617 static final int ALPHA_SET = 0x00040000; 1618 1619 /** 1620 * Set by {@link #setScrollContainer(boolean)}. 1621 */ 1622 static final int SCROLL_CONTAINER = 0x00080000; 1623 1624 /** 1625 * Set by {@link #setScrollContainer(boolean)}. 1626 */ 1627 static final int SCROLL_CONTAINER_ADDED = 0x00100000; 1628 1629 /** 1630 * View flag indicating whether this view was invalidated (fully or partially.) 1631 * 1632 * @hide 1633 */ 1634 static final int DIRTY = 0x00200000; 1635 1636 /** 1637 * View flag indicating whether this view was invalidated by an opaque 1638 * invalidate request. 1639 * 1640 * @hide 1641 */ 1642 static final int DIRTY_OPAQUE = 0x00400000; 1643 1644 /** 1645 * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}. 1646 * 1647 * @hide 1648 */ 1649 static final int DIRTY_MASK = 0x00600000; 1650 1651 /** 1652 * Indicates whether the background is opaque. 1653 * 1654 * @hide 1655 */ 1656 static final int OPAQUE_BACKGROUND = 0x00800000; 1657 1658 /** 1659 * Indicates whether the scrollbars are opaque. 1660 * 1661 * @hide 1662 */ 1663 static final int OPAQUE_SCROLLBARS = 0x01000000; 1664 1665 /** 1666 * Indicates whether the view is opaque. 1667 * 1668 * @hide 1669 */ 1670 static final int OPAQUE_MASK = 0x01800000; 1671 1672 /** 1673 * Indicates a prepressed state; 1674 * the short time between ACTION_DOWN and recognizing 1675 * a 'real' press. Prepressed is used to recognize quick taps 1676 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1677 * 1678 * @hide 1679 */ 1680 private static final int PREPRESSED = 0x02000000; 1681 1682 /** 1683 * Indicates whether the view is temporarily detached. 1684 * 1685 * @hide 1686 */ 1687 static final int CANCEL_NEXT_UP_EVENT = 0x04000000; 1688 1689 /** 1690 * Indicates that we should awaken scroll bars once attached 1691 * 1692 * @hide 1693 */ 1694 private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1695 1696 /** 1697 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1698 * @hide 1699 */ 1700 private static final int HOVERED = 0x10000000; 1701 1702 /** 1703 * Indicates that pivotX or pivotY were explicitly set and we should not assume the center 1704 * for transform operations 1705 * 1706 * @hide 1707 */ 1708 private static final int PIVOT_EXPLICITLY_SET = 0x20000000; 1709 1710 /** {@hide} */ 1711 static final int ACTIVATED = 0x40000000; 1712 1713 /** 1714 * Indicates that this view was specifically invalidated, not just dirtied because some 1715 * child view was invalidated. The flag is used to determine when we need to recreate 1716 * a view's display list (as opposed to just returning a reference to its existing 1717 * display list). 1718 * 1719 * @hide 1720 */ 1721 static final int INVALIDATED = 0x80000000; 1722 1723 /* Masks for mPrivateFlags2 */ 1724 1725 /** 1726 * Indicates that this view has reported that it can accept the current drag's content. 1727 * Cleared when the drag operation concludes. 1728 * @hide 1729 */ 1730 static final int DRAG_CAN_ACCEPT = 0x00000001; 1731 1732 /** 1733 * Indicates that this view is currently directly under the drag location in a 1734 * drag-and-drop operation involving content that it can accept. Cleared when 1735 * the drag exits the view, or when the drag operation concludes. 1736 * @hide 1737 */ 1738 static final int DRAG_HOVERED = 0x00000002; 1739 1740 /** 1741 * Indicates whether the view layout direction has been resolved and drawn to the 1742 * right-to-left direction. 1743 * 1744 * @hide 1745 */ 1746 static final int LAYOUT_DIRECTION_RESOLVED_RTL = 0x00000004; 1747 1748 /** 1749 * Indicates whether the view layout direction has been resolved. 1750 * 1751 * @hide 1752 */ 1753 static final int LAYOUT_DIRECTION_RESOLVED = 0x00000008; 1754 1755 1756 /* End of masks for mPrivateFlags2 */ 1757 1758 static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED; 1759 1760 /** 1761 * Always allow a user to over-scroll this view, provided it is a 1762 * view that can scroll. 1763 * 1764 * @see #getOverScrollMode() 1765 * @see #setOverScrollMode(int) 1766 */ 1767 public static final int OVER_SCROLL_ALWAYS = 0; 1768 1769 /** 1770 * Allow a user to over-scroll this view only if the content is large 1771 * enough to meaningfully scroll, provided it is a view that can scroll. 1772 * 1773 * @see #getOverScrollMode() 1774 * @see #setOverScrollMode(int) 1775 */ 1776 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 1777 1778 /** 1779 * Never allow a user to over-scroll this view. 1780 * 1781 * @see #getOverScrollMode() 1782 * @see #setOverScrollMode(int) 1783 */ 1784 public static final int OVER_SCROLL_NEVER = 2; 1785 1786 /** 1787 * View has requested the system UI (status bar) to be visible (the default). 1788 * 1789 * @see #setSystemUiVisibility(int) 1790 */ 1791 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 1792 1793 /** 1794 * View has requested the system UI to enter an unobtrusive "low profile" mode. 1795 * 1796 * This is for use in games, book readers, video players, or any other "immersive" application 1797 * where the usual system chrome is deemed too distracting. 1798 * 1799 * In low profile mode, the status bar and/or navigation icons may dim. 1800 * 1801 * @see #setSystemUiVisibility(int) 1802 */ 1803 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 1804 1805 /** 1806 * View has requested that the system navigation be temporarily hidden. 1807 * 1808 * This is an even less obtrusive state than that called for by 1809 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 1810 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 1811 * those to disappear. This is useful (in conjunction with the 1812 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 1813 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 1814 * window flags) for displaying content using every last pixel on the display. 1815 * 1816 * There is a limitation: because navigation controls are so important, the least user 1817 * interaction will cause them to reappear immediately. 1818 * 1819 * @see #setSystemUiVisibility(int) 1820 */ 1821 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 1822 1823 /** 1824 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 1825 */ 1826 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 1827 1828 /** 1829 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 1830 */ 1831 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 1832 1833 /** 1834 * @hide 1835 * 1836 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1837 * out of the public fields to keep the undefined bits out of the developer's way. 1838 * 1839 * Flag to make the status bar not expandable. Unless you also 1840 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 1841 */ 1842 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 1843 1844 /** 1845 * @hide 1846 * 1847 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1848 * out of the public fields to keep the undefined bits out of the developer's way. 1849 * 1850 * Flag to hide notification icons and scrolling ticker text. 1851 */ 1852 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 1853 1854 /** 1855 * @hide 1856 * 1857 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1858 * out of the public fields to keep the undefined bits out of the developer's way. 1859 * 1860 * Flag to disable incoming notification alerts. This will not block 1861 * icons, but it will block sound, vibrating and other visual or aural notifications. 1862 */ 1863 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 1864 1865 /** 1866 * @hide 1867 * 1868 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1869 * out of the public fields to keep the undefined bits out of the developer's way. 1870 * 1871 * Flag to hide only the scrolling ticker. Note that 1872 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 1873 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 1874 */ 1875 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 1876 1877 /** 1878 * @hide 1879 * 1880 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1881 * out of the public fields to keep the undefined bits out of the developer's way. 1882 * 1883 * Flag to hide the center system info area. 1884 */ 1885 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 1886 1887 /** 1888 * @hide 1889 * 1890 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1891 * out of the public fields to keep the undefined bits out of the developer's way. 1892 * 1893 * Flag to hide only the navigation buttons. Don't use this 1894 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 1895 * 1896 * THIS DOES NOT DISABLE THE BACK BUTTON 1897 */ 1898 public static final int STATUS_BAR_DISABLE_NAVIGATION = 0x00200000; 1899 1900 /** 1901 * @hide 1902 * 1903 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1904 * out of the public fields to keep the undefined bits out of the developer's way. 1905 * 1906 * Flag to hide only the back button. Don't use this 1907 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 1908 */ 1909 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 1910 1911 /** 1912 * @hide 1913 * 1914 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1915 * out of the public fields to keep the undefined bits out of the developer's way. 1916 * 1917 * Flag to hide only the clock. You might use this if your activity has 1918 * its own clock making the status bar's clock redundant. 1919 */ 1920 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 1921 1922 /** 1923 * @hide 1924 */ 1925 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF; 1926 1927 /** 1928 * Controls the over-scroll mode for this view. 1929 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 1930 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 1931 * and {@link #OVER_SCROLL_NEVER}. 1932 */ 1933 private int mOverScrollMode; 1934 1935 /** 1936 * The parent this view is attached to. 1937 * {@hide} 1938 * 1939 * @see #getParent() 1940 */ 1941 protected ViewParent mParent; 1942 1943 /** 1944 * {@hide} 1945 */ 1946 AttachInfo mAttachInfo; 1947 1948 /** 1949 * {@hide} 1950 */ 1951 @ViewDebug.ExportedProperty(flagMapping = { 1952 @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT, 1953 name = "FORCE_LAYOUT"), 1954 @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED, 1955 name = "LAYOUT_REQUIRED"), 1956 @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID, 1957 name = "DRAWING_CACHE_INVALID", outputIf = false), 1958 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true), 1959 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false), 1960 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 1961 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY") 1962 }) 1963 int mPrivateFlags; 1964 int mPrivateFlags2; 1965 1966 /** 1967 * This view's request for the visibility of the status bar. 1968 * @hide 1969 */ 1970 @ViewDebug.ExportedProperty(flagMapping = { 1971 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 1972 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 1973 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 1974 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 1975 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 1976 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 1977 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 1978 equals = SYSTEM_UI_FLAG_VISIBLE, 1979 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 1980 }) 1981 int mSystemUiVisibility; 1982 1983 /** 1984 * Count of how many windows this view has been attached to. 1985 */ 1986 int mWindowAttachCount; 1987 1988 /** 1989 * The layout parameters associated with this view and used by the parent 1990 * {@link android.view.ViewGroup} to determine how this view should be 1991 * laid out. 1992 * {@hide} 1993 */ 1994 protected ViewGroup.LayoutParams mLayoutParams; 1995 1996 /** 1997 * The view flags hold various views states. 1998 * {@hide} 1999 */ 2000 @ViewDebug.ExportedProperty 2001 int mViewFlags; 2002 2003 /** 2004 * The transform matrix for the View. This transform is calculated internally 2005 * based on the rotation, scaleX, and scaleY properties. The identity matrix 2006 * is used by default. Do *not* use this variable directly; instead call 2007 * getMatrix(), which will automatically recalculate the matrix if necessary 2008 * to get the correct matrix based on the latest rotation and scale properties. 2009 */ 2010 private final Matrix mMatrix = new Matrix(); 2011 2012 /** 2013 * The transform matrix for the View. This transform is calculated internally 2014 * based on the rotation, scaleX, and scaleY properties. The identity matrix 2015 * is used by default. Do *not* use this variable directly; instead call 2016 * getInverseMatrix(), which will automatically recalculate the matrix if necessary 2017 * to get the correct matrix based on the latest rotation and scale properties. 2018 */ 2019 private Matrix mInverseMatrix; 2020 2021 /** 2022 * An internal variable that tracks whether we need to recalculate the 2023 * transform matrix, based on whether the rotation or scaleX/Y properties 2024 * have changed since the matrix was last calculated. 2025 */ 2026 boolean mMatrixDirty = false; 2027 2028 /** 2029 * An internal variable that tracks whether we need to recalculate the 2030 * transform matrix, based on whether the rotation or scaleX/Y properties 2031 * have changed since the matrix was last calculated. 2032 */ 2033 private boolean mInverseMatrixDirty = true; 2034 2035 /** 2036 * A variable that tracks whether we need to recalculate the 2037 * transform matrix, based on whether the rotation or scaleX/Y properties 2038 * have changed since the matrix was last calculated. This variable 2039 * is only valid after a call to updateMatrix() or to a function that 2040 * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix(). 2041 */ 2042 private boolean mMatrixIsIdentity = true; 2043 2044 /** 2045 * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set. 2046 */ 2047 private Camera mCamera = null; 2048 2049 /** 2050 * This matrix is used when computing the matrix for 3D rotations. 2051 */ 2052 private Matrix matrix3D = null; 2053 2054 /** 2055 * These prev values are used to recalculate a centered pivot point when necessary. The 2056 * pivot point is only used in matrix operations (when rotation, scale, or translation are 2057 * set), so thes values are only used then as well. 2058 */ 2059 private int mPrevWidth = -1; 2060 private int mPrevHeight = -1; 2061 2062 private boolean mLastIsOpaque; 2063 2064 /** 2065 * Convenience value to check for float values that are close enough to zero to be considered 2066 * zero. 2067 */ 2068 private static final float NONZERO_EPSILON = .001f; 2069 2070 /** 2071 * The degrees rotation around the vertical axis through the pivot point. 2072 */ 2073 @ViewDebug.ExportedProperty 2074 float mRotationY = 0f; 2075 2076 /** 2077 * The degrees rotation around the horizontal axis through the pivot point. 2078 */ 2079 @ViewDebug.ExportedProperty 2080 float mRotationX = 0f; 2081 2082 /** 2083 * The degrees rotation around the pivot point. 2084 */ 2085 @ViewDebug.ExportedProperty 2086 float mRotation = 0f; 2087 2088 /** 2089 * The amount of translation of the object away from its left property (post-layout). 2090 */ 2091 @ViewDebug.ExportedProperty 2092 float mTranslationX = 0f; 2093 2094 /** 2095 * The amount of translation of the object away from its top property (post-layout). 2096 */ 2097 @ViewDebug.ExportedProperty 2098 float mTranslationY = 0f; 2099 2100 /** 2101 * The amount of scale in the x direction around the pivot point. A 2102 * value of 1 means no scaling is applied. 2103 */ 2104 @ViewDebug.ExportedProperty 2105 float mScaleX = 1f; 2106 2107 /** 2108 * The amount of scale in the y direction around the pivot point. A 2109 * value of 1 means no scaling is applied. 2110 */ 2111 @ViewDebug.ExportedProperty 2112 float mScaleY = 1f; 2113 2114 /** 2115 * The amount of scale in the x direction around the pivot point. A 2116 * value of 1 means no scaling is applied. 2117 */ 2118 @ViewDebug.ExportedProperty 2119 float mPivotX = 0f; 2120 2121 /** 2122 * The amount of scale in the y direction around the pivot point. A 2123 * value of 1 means no scaling is applied. 2124 */ 2125 @ViewDebug.ExportedProperty 2126 float mPivotY = 0f; 2127 2128 /** 2129 * The opacity of the View. This is a value from 0 to 1, where 0 means 2130 * completely transparent and 1 means completely opaque. 2131 */ 2132 @ViewDebug.ExportedProperty 2133 float mAlpha = 1f; 2134 2135 /** 2136 * The distance in pixels from the left edge of this view's parent 2137 * to the left edge of this view. 2138 * {@hide} 2139 */ 2140 @ViewDebug.ExportedProperty(category = "layout") 2141 protected int mLeft; 2142 /** 2143 * The distance in pixels from the left edge of this view's parent 2144 * to the right edge of this view. 2145 * {@hide} 2146 */ 2147 @ViewDebug.ExportedProperty(category = "layout") 2148 protected int mRight; 2149 /** 2150 * The distance in pixels from the top edge of this view's parent 2151 * to the top edge of this view. 2152 * {@hide} 2153 */ 2154 @ViewDebug.ExportedProperty(category = "layout") 2155 protected int mTop; 2156 /** 2157 * The distance in pixels from the top edge of this view's parent 2158 * to the bottom edge of this view. 2159 * {@hide} 2160 */ 2161 @ViewDebug.ExportedProperty(category = "layout") 2162 protected int mBottom; 2163 2164 /** 2165 * The offset, in pixels, by which the content of this view is scrolled 2166 * horizontally. 2167 * {@hide} 2168 */ 2169 @ViewDebug.ExportedProperty(category = "scrolling") 2170 protected int mScrollX; 2171 /** 2172 * The offset, in pixels, by which the content of this view is scrolled 2173 * vertically. 2174 * {@hide} 2175 */ 2176 @ViewDebug.ExportedProperty(category = "scrolling") 2177 protected int mScrollY; 2178 2179 /** 2180 * The left padding in pixels, that is the distance in pixels between the 2181 * left edge of this view and the left edge of its content. 2182 * {@hide} 2183 */ 2184 @ViewDebug.ExportedProperty(category = "padding") 2185 protected int mPaddingLeft; 2186 /** 2187 * The right padding in pixels, that is the distance in pixels between the 2188 * right edge of this view and the right edge of its content. 2189 * {@hide} 2190 */ 2191 @ViewDebug.ExportedProperty(category = "padding") 2192 protected int mPaddingRight; 2193 /** 2194 * The top padding in pixels, that is the distance in pixels between the 2195 * top edge of this view and the top edge of its content. 2196 * {@hide} 2197 */ 2198 @ViewDebug.ExportedProperty(category = "padding") 2199 protected int mPaddingTop; 2200 /** 2201 * The bottom padding in pixels, that is the distance in pixels between the 2202 * bottom edge of this view and the bottom edge of its content. 2203 * {@hide} 2204 */ 2205 @ViewDebug.ExportedProperty(category = "padding") 2206 protected int mPaddingBottom; 2207 2208 /** 2209 * Briefly describes the view and is primarily used for accessibility support. 2210 */ 2211 private CharSequence mContentDescription; 2212 2213 /** 2214 * Cache the paddingRight set by the user to append to the scrollbar's size. 2215 * 2216 * @hide 2217 */ 2218 @ViewDebug.ExportedProperty(category = "padding") 2219 protected int mUserPaddingRight; 2220 2221 /** 2222 * Cache the paddingBottom set by the user to append to the scrollbar's size. 2223 * 2224 * @hide 2225 */ 2226 @ViewDebug.ExportedProperty(category = "padding") 2227 protected int mUserPaddingBottom; 2228 2229 /** 2230 * Cache the paddingLeft set by the user to append to the scrollbar's size. 2231 * 2232 * @hide 2233 */ 2234 @ViewDebug.ExportedProperty(category = "padding") 2235 protected int mUserPaddingLeft; 2236 2237 /** 2238 * Cache if the user padding is relative. 2239 * 2240 */ 2241 @ViewDebug.ExportedProperty(category = "padding") 2242 boolean mUserPaddingRelative; 2243 2244 /** 2245 * Cache the paddingStart set by the user to append to the scrollbar's size. 2246 * 2247 */ 2248 @ViewDebug.ExportedProperty(category = "padding") 2249 int mUserPaddingStart; 2250 2251 /** 2252 * Cache the paddingEnd set by the user to append to the scrollbar's size. 2253 * 2254 */ 2255 @ViewDebug.ExportedProperty(category = "padding") 2256 int mUserPaddingEnd; 2257 2258 /** 2259 * @hide 2260 */ 2261 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 2262 /** 2263 * @hide 2264 */ 2265 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 2266 2267 private Resources mResources = null; 2268 2269 private Drawable mBGDrawable; 2270 2271 private int mBackgroundResource; 2272 private boolean mBackgroundSizeChanged; 2273 2274 /** 2275 * Listener used to dispatch focus change events. 2276 * This field should be made private, so it is hidden from the SDK. 2277 * {@hide} 2278 */ 2279 protected OnFocusChangeListener mOnFocusChangeListener; 2280 2281 /** 2282 * Listeners for layout change events. 2283 */ 2284 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 2285 2286 /** 2287 * Listeners for attach events. 2288 */ 2289 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 2290 2291 /** 2292 * Listener used to dispatch click events. 2293 * This field should be made private, so it is hidden from the SDK. 2294 * {@hide} 2295 */ 2296 protected OnClickListener mOnClickListener; 2297 2298 /** 2299 * Listener used to dispatch long click events. 2300 * This field should be made private, so it is hidden from the SDK. 2301 * {@hide} 2302 */ 2303 protected OnLongClickListener mOnLongClickListener; 2304 2305 /** 2306 * Listener used to build the context menu. 2307 * This field should be made private, so it is hidden from the SDK. 2308 * {@hide} 2309 */ 2310 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 2311 2312 private OnKeyListener mOnKeyListener; 2313 2314 private OnTouchListener mOnTouchListener; 2315 2316 private OnHoverListener mOnHoverListener; 2317 2318 private OnGenericMotionListener mOnGenericMotionListener; 2319 2320 private OnDragListener mOnDragListener; 2321 2322 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 2323 2324 /** 2325 * The application environment this view lives in. 2326 * This field should be made private, so it is hidden from the SDK. 2327 * {@hide} 2328 */ 2329 protected Context mContext; 2330 2331 private ScrollabilityCache mScrollCache; 2332 2333 private int[] mDrawableState = null; 2334 2335 /** 2336 * Set to true when drawing cache is enabled and cannot be created. 2337 * 2338 * @hide 2339 */ 2340 public boolean mCachingFailed; 2341 2342 private Bitmap mDrawingCache; 2343 private Bitmap mUnscaledDrawingCache; 2344 private HardwareLayer mHardwareLayer; 2345 DisplayList mDisplayList; 2346 2347 /** 2348 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 2349 * the user may specify which view to go to next. 2350 */ 2351 private int mNextFocusLeftId = View.NO_ID; 2352 2353 /** 2354 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 2355 * the user may specify which view to go to next. 2356 */ 2357 private int mNextFocusRightId = View.NO_ID; 2358 2359 /** 2360 * When this view has focus and the next focus is {@link #FOCUS_UP}, 2361 * the user may specify which view to go to next. 2362 */ 2363 private int mNextFocusUpId = View.NO_ID; 2364 2365 /** 2366 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 2367 * the user may specify which view to go to next. 2368 */ 2369 private int mNextFocusDownId = View.NO_ID; 2370 2371 /** 2372 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 2373 * the user may specify which view to go to next. 2374 */ 2375 int mNextFocusForwardId = View.NO_ID; 2376 2377 private CheckForLongPress mPendingCheckForLongPress; 2378 private CheckForTap mPendingCheckForTap = null; 2379 private PerformClick mPerformClick; 2380 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 2381 2382 private UnsetPressedState mUnsetPressedState; 2383 2384 /** 2385 * Whether the long press's action has been invoked. The tap's action is invoked on the 2386 * up event while a long press is invoked as soon as the long press duration is reached, so 2387 * a long press could be performed before the tap is checked, in which case the tap's action 2388 * should not be invoked. 2389 */ 2390 private boolean mHasPerformedLongPress; 2391 2392 /** 2393 * The minimum height of the view. We'll try our best to have the height 2394 * of this view to at least this amount. 2395 */ 2396 @ViewDebug.ExportedProperty(category = "measurement") 2397 private int mMinHeight; 2398 2399 /** 2400 * The minimum width of the view. We'll try our best to have the width 2401 * of this view to at least this amount. 2402 */ 2403 @ViewDebug.ExportedProperty(category = "measurement") 2404 private int mMinWidth; 2405 2406 /** 2407 * The delegate to handle touch events that are physically in this view 2408 * but should be handled by another view. 2409 */ 2410 private TouchDelegate mTouchDelegate = null; 2411 2412 /** 2413 * Solid color to use as a background when creating the drawing cache. Enables 2414 * the cache to use 16 bit bitmaps instead of 32 bit. 2415 */ 2416 private int mDrawingCacheBackgroundColor = 0; 2417 2418 /** 2419 * Special tree observer used when mAttachInfo is null. 2420 */ 2421 private ViewTreeObserver mFloatingTreeObserver; 2422 2423 /** 2424 * Cache the touch slop from the context that created the view. 2425 */ 2426 private int mTouchSlop; 2427 2428 /** 2429 * Object that handles automatic animation of view properties. 2430 */ 2431 private ViewPropertyAnimator mAnimator = null; 2432 2433 /** 2434 * Flag indicating that a drag can cross window boundaries. When 2435 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 2436 * with this flag set, all visible applications will be able to participate 2437 * in the drag operation and receive the dragged content. 2438 * 2439 * @hide 2440 */ 2441 public static final int DRAG_FLAG_GLOBAL = 1; 2442 2443 /** 2444 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 2445 */ 2446 private float mVerticalScrollFactor; 2447 2448 /** 2449 * Position of the vertical scroll bar. 2450 */ 2451 private int mVerticalScrollbarPosition; 2452 2453 /** 2454 * Position the scroll bar at the default position as determined by the system. 2455 */ 2456 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 2457 2458 /** 2459 * Position the scroll bar along the left edge. 2460 */ 2461 public static final int SCROLLBAR_POSITION_LEFT = 1; 2462 2463 /** 2464 * Position the scroll bar along the right edge. 2465 */ 2466 public static final int SCROLLBAR_POSITION_RIGHT = 2; 2467 2468 /** 2469 * Indicates that the view does not have a layer. 2470 * 2471 * @see #getLayerType() 2472 * @see #setLayerType(int, android.graphics.Paint) 2473 * @see #LAYER_TYPE_SOFTWARE 2474 * @see #LAYER_TYPE_HARDWARE 2475 */ 2476 public static final int LAYER_TYPE_NONE = 0; 2477 2478 /** 2479 * <p>Indicates that the view has a software layer. A software layer is backed 2480 * by a bitmap and causes the view to be rendered using Android's software 2481 * rendering pipeline, even if hardware acceleration is enabled.</p> 2482 * 2483 * <p>Software layers have various usages:</p> 2484 * <p>When the application is not using hardware acceleration, a software layer 2485 * is useful to apply a specific color filter and/or blending mode and/or 2486 * translucency to a view and all its children.</p> 2487 * <p>When the application is using hardware acceleration, a software layer 2488 * is useful to render drawing primitives not supported by the hardware 2489 * accelerated pipeline. It can also be used to cache a complex view tree 2490 * into a texture and reduce the complexity of drawing operations. For instance, 2491 * when animating a complex view tree with a translation, a software layer can 2492 * be used to render the view tree only once.</p> 2493 * <p>Software layers should be avoided when the affected view tree updates 2494 * often. Every update will require to re-render the software layer, which can 2495 * potentially be slow (particularly when hardware acceleration is turned on 2496 * since the layer will have to be uploaded into a hardware texture after every 2497 * update.)</p> 2498 * 2499 * @see #getLayerType() 2500 * @see #setLayerType(int, android.graphics.Paint) 2501 * @see #LAYER_TYPE_NONE 2502 * @see #LAYER_TYPE_HARDWARE 2503 */ 2504 public static final int LAYER_TYPE_SOFTWARE = 1; 2505 2506 /** 2507 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 2508 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 2509 * OpenGL hardware) and causes the view to be rendered using Android's hardware 2510 * rendering pipeline, but only if hardware acceleration is turned on for the 2511 * view hierarchy. When hardware acceleration is turned off, hardware layers 2512 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 2513 * 2514 * <p>A hardware layer is useful to apply a specific color filter and/or 2515 * blending mode and/or translucency to a view and all its children.</p> 2516 * <p>A hardware layer can be used to cache a complex view tree into a 2517 * texture and reduce the complexity of drawing operations. For instance, 2518 * when animating a complex view tree with a translation, a hardware layer can 2519 * be used to render the view tree only once.</p> 2520 * <p>A hardware layer can also be used to increase the rendering quality when 2521 * rotation transformations are applied on a view. It can also be used to 2522 * prevent potential clipping issues when applying 3D transforms on a view.</p> 2523 * 2524 * @see #getLayerType() 2525 * @see #setLayerType(int, android.graphics.Paint) 2526 * @see #LAYER_TYPE_NONE 2527 * @see #LAYER_TYPE_SOFTWARE 2528 */ 2529 public static final int LAYER_TYPE_HARDWARE = 2; 2530 2531 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 2532 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 2533 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 2534 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 2535 }) 2536 int mLayerType = LAYER_TYPE_NONE; 2537 Paint mLayerPaint; 2538 Rect mLocalDirtyRect; 2539 2540 /** 2541 * Set to true when the view is sending hover accessibility events because it 2542 * is the innermost hovered view. 2543 */ 2544 private boolean mSendingHoverAccessibilityEvents; 2545 2546 /** 2547 * Text direction is inherited thru {@link ViewGroup} 2548 * @hide 2549 */ 2550 public static final int TEXT_DIRECTION_INHERIT = 0; 2551 2552 /** 2553 * Text direction is using "first strong algorithm". The first strong directional character 2554 * determines the paragraph direction. If there is no strong directional character, the 2555 * paragraph direction is the view's resolved ayout direction. 2556 * 2557 * @hide 2558 */ 2559 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 2560 2561 /** 2562 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 2563 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 2564 * If there are neither, the paragraph direction is the view's resolved layout direction. 2565 * 2566 * @hide 2567 */ 2568 public static final int TEXT_DIRECTION_ANY_RTL = 2; 2569 2570 /** 2571 * Text direction is forced to LTR. 2572 * 2573 * @hide 2574 */ 2575 public static final int TEXT_DIRECTION_LTR = 3; 2576 2577 /** 2578 * Text direction is forced to RTL. 2579 * 2580 * @hide 2581 */ 2582 public static final int TEXT_DIRECTION_RTL = 4; 2583 2584 /** 2585 * Default text direction is inherited 2586 * 2587 * @hide 2588 */ 2589 protected static int DEFAULT_TEXT_DIRECTION = TEXT_DIRECTION_INHERIT; 2590 2591 /** 2592 * The text direction that has been defined by {@link #setTextDirection(int)}. 2593 * 2594 * {@hide} 2595 */ 2596 @ViewDebug.ExportedProperty(category = "text", mapping = { 2597 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 2598 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 2599 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 2600 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 2601 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL") 2602 }) 2603 private int mTextDirection = DEFAULT_TEXT_DIRECTION; 2604 2605 /** 2606 * The resolved text direction. This needs resolution if the value is 2607 * TEXT_DIRECTION_INHERIT. The resolution matches mTextDirection if that is 2608 * not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds up the parent 2609 * chain of the view. 2610 * 2611 * {@hide} 2612 */ 2613 @ViewDebug.ExportedProperty(category = "text", mapping = { 2614 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 2615 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 2616 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 2617 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 2618 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL") 2619 }) 2620 private int mResolvedTextDirection = TEXT_DIRECTION_INHERIT; 2621 2622 /** 2623 * Consistency verifier for debugging purposes. 2624 * @hide 2625 */ 2626 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 2627 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 2628 new InputEventConsistencyVerifier(this, 0) : null; 2629 2630 /** 2631 * Simple constructor to use when creating a view from code. 2632 * 2633 * @param context The Context the view is running in, through which it can 2634 * access the current theme, resources, etc. 2635 */ 2636 public View(Context context) { 2637 mContext = context; 2638 mResources = context != null ? context.getResources() : null; 2639 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED | LAYOUT_DIRECTION_INHERIT; 2640 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 2641 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 2642 mUserPaddingStart = -1; 2643 mUserPaddingEnd = -1; 2644 mUserPaddingRelative = false; 2645 } 2646 2647 /** 2648 * Constructor that is called when inflating a view from XML. This is called 2649 * when a view is being constructed from an XML file, supplying attributes 2650 * that were specified in the XML file. This version uses a default style of 2651 * 0, so the only attribute values applied are those in the Context's Theme 2652 * and the given AttributeSet. 2653 * 2654 * <p> 2655 * The method onFinishInflate() will be called after all children have been 2656 * added. 2657 * 2658 * @param context The Context the view is running in, through which it can 2659 * access the current theme, resources, etc. 2660 * @param attrs The attributes of the XML tag that is inflating the view. 2661 * @see #View(Context, AttributeSet, int) 2662 */ 2663 public View(Context context, AttributeSet attrs) { 2664 this(context, attrs, 0); 2665 } 2666 2667 /** 2668 * Perform inflation from XML and apply a class-specific base style. This 2669 * constructor of View allows subclasses to use their own base style when 2670 * they are inflating. For example, a Button class's constructor would call 2671 * this version of the super class constructor and supply 2672 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows 2673 * the theme's button style to modify all of the base view attributes (in 2674 * particular its background) as well as the Button class's attributes. 2675 * 2676 * @param context The Context the view is running in, through which it can 2677 * access the current theme, resources, etc. 2678 * @param attrs The attributes of the XML tag that is inflating the view. 2679 * @param defStyle The default style to apply to this view. If 0, no style 2680 * will be applied (beyond what is included in the theme). This may 2681 * either be an attribute resource, whose value will be retrieved 2682 * from the current theme, or an explicit style resource. 2683 * @see #View(Context, AttributeSet) 2684 */ 2685 public View(Context context, AttributeSet attrs, int defStyle) { 2686 this(context); 2687 2688 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View, 2689 defStyle, 0); 2690 2691 Drawable background = null; 2692 2693 int leftPadding = -1; 2694 int topPadding = -1; 2695 int rightPadding = -1; 2696 int bottomPadding = -1; 2697 int startPadding = -1; 2698 int endPadding = -1; 2699 2700 int padding = -1; 2701 2702 int viewFlagValues = 0; 2703 int viewFlagMasks = 0; 2704 2705 boolean setScrollContainer = false; 2706 2707 int x = 0; 2708 int y = 0; 2709 2710 float tx = 0; 2711 float ty = 0; 2712 float rotation = 0; 2713 float rotationX = 0; 2714 float rotationY = 0; 2715 float sx = 1f; 2716 float sy = 1f; 2717 boolean transformSet = false; 2718 2719 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 2720 2721 int overScrollMode = mOverScrollMode; 2722 final int N = a.getIndexCount(); 2723 for (int i = 0; i < N; i++) { 2724 int attr = a.getIndex(i); 2725 switch (attr) { 2726 case com.android.internal.R.styleable.View_background: 2727 background = a.getDrawable(attr); 2728 break; 2729 case com.android.internal.R.styleable.View_padding: 2730 padding = a.getDimensionPixelSize(attr, -1); 2731 break; 2732 case com.android.internal.R.styleable.View_paddingLeft: 2733 leftPadding = a.getDimensionPixelSize(attr, -1); 2734 break; 2735 case com.android.internal.R.styleable.View_paddingTop: 2736 topPadding = a.getDimensionPixelSize(attr, -1); 2737 break; 2738 case com.android.internal.R.styleable.View_paddingRight: 2739 rightPadding = a.getDimensionPixelSize(attr, -1); 2740 break; 2741 case com.android.internal.R.styleable.View_paddingBottom: 2742 bottomPadding = a.getDimensionPixelSize(attr, -1); 2743 break; 2744 case com.android.internal.R.styleable.View_paddingStart: 2745 startPadding = a.getDimensionPixelSize(attr, -1); 2746 break; 2747 case com.android.internal.R.styleable.View_paddingEnd: 2748 endPadding = a.getDimensionPixelSize(attr, -1); 2749 break; 2750 case com.android.internal.R.styleable.View_scrollX: 2751 x = a.getDimensionPixelOffset(attr, 0); 2752 break; 2753 case com.android.internal.R.styleable.View_scrollY: 2754 y = a.getDimensionPixelOffset(attr, 0); 2755 break; 2756 case com.android.internal.R.styleable.View_alpha: 2757 setAlpha(a.getFloat(attr, 1f)); 2758 break; 2759 case com.android.internal.R.styleable.View_transformPivotX: 2760 setPivotX(a.getDimensionPixelOffset(attr, 0)); 2761 break; 2762 case com.android.internal.R.styleable.View_transformPivotY: 2763 setPivotY(a.getDimensionPixelOffset(attr, 0)); 2764 break; 2765 case com.android.internal.R.styleable.View_translationX: 2766 tx = a.getDimensionPixelOffset(attr, 0); 2767 transformSet = true; 2768 break; 2769 case com.android.internal.R.styleable.View_translationY: 2770 ty = a.getDimensionPixelOffset(attr, 0); 2771 transformSet = true; 2772 break; 2773 case com.android.internal.R.styleable.View_rotation: 2774 rotation = a.getFloat(attr, 0); 2775 transformSet = true; 2776 break; 2777 case com.android.internal.R.styleable.View_rotationX: 2778 rotationX = a.getFloat(attr, 0); 2779 transformSet = true; 2780 break; 2781 case com.android.internal.R.styleable.View_rotationY: 2782 rotationY = a.getFloat(attr, 0); 2783 transformSet = true; 2784 break; 2785 case com.android.internal.R.styleable.View_scaleX: 2786 sx = a.getFloat(attr, 1f); 2787 transformSet = true; 2788 break; 2789 case com.android.internal.R.styleable.View_scaleY: 2790 sy = a.getFloat(attr, 1f); 2791 transformSet = true; 2792 break; 2793 case com.android.internal.R.styleable.View_id: 2794 mID = a.getResourceId(attr, NO_ID); 2795 break; 2796 case com.android.internal.R.styleable.View_tag: 2797 mTag = a.getText(attr); 2798 break; 2799 case com.android.internal.R.styleable.View_fitsSystemWindows: 2800 if (a.getBoolean(attr, false)) { 2801 viewFlagValues |= FITS_SYSTEM_WINDOWS; 2802 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 2803 } 2804 break; 2805 case com.android.internal.R.styleable.View_focusable: 2806 if (a.getBoolean(attr, false)) { 2807 viewFlagValues |= FOCUSABLE; 2808 viewFlagMasks |= FOCUSABLE_MASK; 2809 } 2810 break; 2811 case com.android.internal.R.styleable.View_focusableInTouchMode: 2812 if (a.getBoolean(attr, false)) { 2813 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 2814 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 2815 } 2816 break; 2817 case com.android.internal.R.styleable.View_clickable: 2818 if (a.getBoolean(attr, false)) { 2819 viewFlagValues |= CLICKABLE; 2820 viewFlagMasks |= CLICKABLE; 2821 } 2822 break; 2823 case com.android.internal.R.styleable.View_longClickable: 2824 if (a.getBoolean(attr, false)) { 2825 viewFlagValues |= LONG_CLICKABLE; 2826 viewFlagMasks |= LONG_CLICKABLE; 2827 } 2828 break; 2829 case com.android.internal.R.styleable.View_saveEnabled: 2830 if (!a.getBoolean(attr, true)) { 2831 viewFlagValues |= SAVE_DISABLED; 2832 viewFlagMasks |= SAVE_DISABLED_MASK; 2833 } 2834 break; 2835 case com.android.internal.R.styleable.View_duplicateParentState: 2836 if (a.getBoolean(attr, false)) { 2837 viewFlagValues |= DUPLICATE_PARENT_STATE; 2838 viewFlagMasks |= DUPLICATE_PARENT_STATE; 2839 } 2840 break; 2841 case com.android.internal.R.styleable.View_visibility: 2842 final int visibility = a.getInt(attr, 0); 2843 if (visibility != 0) { 2844 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 2845 viewFlagMasks |= VISIBILITY_MASK; 2846 } 2847 break; 2848 case com.android.internal.R.styleable.View_layoutDirection: 2849 // Clear any HORIZONTAL_DIRECTION flag already set 2850 viewFlagValues &= ~LAYOUT_DIRECTION_MASK; 2851 // Set the HORIZONTAL_DIRECTION flags depending on the value of the attribute 2852 final int layoutDirection = a.getInt(attr, -1); 2853 if (layoutDirection != -1) { 2854 viewFlagValues |= LAYOUT_DIRECTION_FLAGS[layoutDirection]; 2855 } else { 2856 // Set to default (LAYOUT_DIRECTION_INHERIT) 2857 viewFlagValues |= LAYOUT_DIRECTION_DEFAULT; 2858 } 2859 viewFlagMasks |= LAYOUT_DIRECTION_MASK; 2860 break; 2861 case com.android.internal.R.styleable.View_drawingCacheQuality: 2862 final int cacheQuality = a.getInt(attr, 0); 2863 if (cacheQuality != 0) { 2864 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 2865 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 2866 } 2867 break; 2868 case com.android.internal.R.styleable.View_contentDescription: 2869 mContentDescription = a.getString(attr); 2870 break; 2871 case com.android.internal.R.styleable.View_soundEffectsEnabled: 2872 if (!a.getBoolean(attr, true)) { 2873 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 2874 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 2875 } 2876 break; 2877 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 2878 if (!a.getBoolean(attr, true)) { 2879 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 2880 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 2881 } 2882 break; 2883 case R.styleable.View_scrollbars: 2884 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 2885 if (scrollbars != SCROLLBARS_NONE) { 2886 viewFlagValues |= scrollbars; 2887 viewFlagMasks |= SCROLLBARS_MASK; 2888 initializeScrollbars(a); 2889 } 2890 break; 2891 case R.styleable.View_fadingEdge: 2892 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 2893 if (fadingEdge != FADING_EDGE_NONE) { 2894 viewFlagValues |= fadingEdge; 2895 viewFlagMasks |= FADING_EDGE_MASK; 2896 initializeFadingEdge(a); 2897 } 2898 break; 2899 case R.styleable.View_scrollbarStyle: 2900 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 2901 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 2902 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 2903 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 2904 } 2905 break; 2906 case R.styleable.View_isScrollContainer: 2907 setScrollContainer = true; 2908 if (a.getBoolean(attr, false)) { 2909 setScrollContainer(true); 2910 } 2911 break; 2912 case com.android.internal.R.styleable.View_keepScreenOn: 2913 if (a.getBoolean(attr, false)) { 2914 viewFlagValues |= KEEP_SCREEN_ON; 2915 viewFlagMasks |= KEEP_SCREEN_ON; 2916 } 2917 break; 2918 case R.styleable.View_filterTouchesWhenObscured: 2919 if (a.getBoolean(attr, false)) { 2920 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 2921 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 2922 } 2923 break; 2924 case R.styleable.View_nextFocusLeft: 2925 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 2926 break; 2927 case R.styleable.View_nextFocusRight: 2928 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 2929 break; 2930 case R.styleable.View_nextFocusUp: 2931 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 2932 break; 2933 case R.styleable.View_nextFocusDown: 2934 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 2935 break; 2936 case R.styleable.View_nextFocusForward: 2937 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 2938 break; 2939 case R.styleable.View_minWidth: 2940 mMinWidth = a.getDimensionPixelSize(attr, 0); 2941 break; 2942 case R.styleable.View_minHeight: 2943 mMinHeight = a.getDimensionPixelSize(attr, 0); 2944 break; 2945 case R.styleable.View_onClick: 2946 if (context.isRestricted()) { 2947 throw new IllegalStateException("The android:onClick attribute cannot " 2948 + "be used within a restricted context"); 2949 } 2950 2951 final String handlerName = a.getString(attr); 2952 if (handlerName != null) { 2953 setOnClickListener(new OnClickListener() { 2954 private Method mHandler; 2955 2956 public void onClick(View v) { 2957 if (mHandler == null) { 2958 try { 2959 mHandler = getContext().getClass().getMethod(handlerName, 2960 View.class); 2961 } catch (NoSuchMethodException e) { 2962 int id = getId(); 2963 String idText = id == NO_ID ? "" : " with id '" 2964 + getContext().getResources().getResourceEntryName( 2965 id) + "'"; 2966 throw new IllegalStateException("Could not find a method " + 2967 handlerName + "(View) in the activity " 2968 + getContext().getClass() + " for onClick handler" 2969 + " on view " + View.this.getClass() + idText, e); 2970 } 2971 } 2972 2973 try { 2974 mHandler.invoke(getContext(), View.this); 2975 } catch (IllegalAccessException e) { 2976 throw new IllegalStateException("Could not execute non " 2977 + "public method of the activity", e); 2978 } catch (InvocationTargetException e) { 2979 throw new IllegalStateException("Could not execute " 2980 + "method of the activity", e); 2981 } 2982 } 2983 }); 2984 } 2985 break; 2986 case R.styleable.View_overScrollMode: 2987 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 2988 break; 2989 case R.styleable.View_verticalScrollbarPosition: 2990 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 2991 break; 2992 case R.styleable.View_layerType: 2993 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 2994 break; 2995 case R.styleable.View_textDirection: 2996 mTextDirection = a.getInt(attr, DEFAULT_TEXT_DIRECTION); 2997 break; 2998 } 2999 } 3000 3001 setOverScrollMode(overScrollMode); 3002 3003 if (background != null) { 3004 setBackgroundDrawable(background); 3005 } 3006 3007 mUserPaddingRelative = (startPadding >= 0 || endPadding >= 0); 3008 3009 // Cache user padding as we cannot fully resolve padding here (we dont have yet the resolved 3010 // layout direction). Those cached values will be used later during padding resolution. 3011 mUserPaddingStart = startPadding; 3012 mUserPaddingEnd = endPadding; 3013 3014 if (padding >= 0) { 3015 leftPadding = padding; 3016 topPadding = padding; 3017 rightPadding = padding; 3018 bottomPadding = padding; 3019 } 3020 3021 // If the user specified the padding (either with android:padding or 3022 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise 3023 // use the default padding or the padding from the background drawable 3024 // (stored at this point in mPadding*) 3025 setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft, 3026 topPadding >= 0 ? topPadding : mPaddingTop, 3027 rightPadding >= 0 ? rightPadding : mPaddingRight, 3028 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 3029 3030 if (viewFlagMasks != 0) { 3031 setFlags(viewFlagValues, viewFlagMasks); 3032 } 3033 3034 // Needs to be called after mViewFlags is set 3035 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3036 recomputePadding(); 3037 } 3038 3039 if (x != 0 || y != 0) { 3040 scrollTo(x, y); 3041 } 3042 3043 if (transformSet) { 3044 setTranslationX(tx); 3045 setTranslationY(ty); 3046 setRotation(rotation); 3047 setRotationX(rotationX); 3048 setRotationY(rotationY); 3049 setScaleX(sx); 3050 setScaleY(sy); 3051 } 3052 3053 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 3054 setScrollContainer(true); 3055 } 3056 3057 computeOpaqueFlags(); 3058 3059 a.recycle(); 3060 } 3061 3062 /** 3063 * Non-public constructor for use in testing 3064 */ 3065 View() { 3066 } 3067 3068 /** 3069 * <p> 3070 * Initializes the fading edges from a given set of styled attributes. This 3071 * method should be called by subclasses that need fading edges and when an 3072 * instance of these subclasses is created programmatically rather than 3073 * being inflated from XML. This method is automatically called when the XML 3074 * is inflated. 3075 * </p> 3076 * 3077 * @param a the styled attributes set to initialize the fading edges from 3078 */ 3079 protected void initializeFadingEdge(TypedArray a) { 3080 initScrollCache(); 3081 3082 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 3083 R.styleable.View_fadingEdgeLength, 3084 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 3085 } 3086 3087 /** 3088 * Returns the size of the vertical faded edges used to indicate that more 3089 * content in this view is visible. 3090 * 3091 * @return The size in pixels of the vertical faded edge or 0 if vertical 3092 * faded edges are not enabled for this view. 3093 * @attr ref android.R.styleable#View_fadingEdgeLength 3094 */ 3095 public int getVerticalFadingEdgeLength() { 3096 if (isVerticalFadingEdgeEnabled()) { 3097 ScrollabilityCache cache = mScrollCache; 3098 if (cache != null) { 3099 return cache.fadingEdgeLength; 3100 } 3101 } 3102 return 0; 3103 } 3104 3105 /** 3106 * Set the size of the faded edge used to indicate that more content in this 3107 * view is available. Will not change whether the fading edge is enabled; use 3108 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 3109 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 3110 * for the vertical or horizontal fading edges. 3111 * 3112 * @param length The size in pixels of the faded edge used to indicate that more 3113 * content in this view is visible. 3114 */ 3115 public void setFadingEdgeLength(int length) { 3116 initScrollCache(); 3117 mScrollCache.fadingEdgeLength = length; 3118 } 3119 3120 /** 3121 * Returns the size of the horizontal faded edges used to indicate that more 3122 * content in this view is visible. 3123 * 3124 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 3125 * faded edges are not enabled for this view. 3126 * @attr ref android.R.styleable#View_fadingEdgeLength 3127 */ 3128 public int getHorizontalFadingEdgeLength() { 3129 if (isHorizontalFadingEdgeEnabled()) { 3130 ScrollabilityCache cache = mScrollCache; 3131 if (cache != null) { 3132 return cache.fadingEdgeLength; 3133 } 3134 } 3135 return 0; 3136 } 3137 3138 /** 3139 * Returns the width of the vertical scrollbar. 3140 * 3141 * @return The width in pixels of the vertical scrollbar or 0 if there 3142 * is no vertical scrollbar. 3143 */ 3144 public int getVerticalScrollbarWidth() { 3145 ScrollabilityCache cache = mScrollCache; 3146 if (cache != null) { 3147 ScrollBarDrawable scrollBar = cache.scrollBar; 3148 if (scrollBar != null) { 3149 int size = scrollBar.getSize(true); 3150 if (size <= 0) { 3151 size = cache.scrollBarSize; 3152 } 3153 return size; 3154 } 3155 return 0; 3156 } 3157 return 0; 3158 } 3159 3160 /** 3161 * Returns the height of the horizontal scrollbar. 3162 * 3163 * @return The height in pixels of the horizontal scrollbar or 0 if 3164 * there is no horizontal scrollbar. 3165 */ 3166 protected int getHorizontalScrollbarHeight() { 3167 ScrollabilityCache cache = mScrollCache; 3168 if (cache != null) { 3169 ScrollBarDrawable scrollBar = cache.scrollBar; 3170 if (scrollBar != null) { 3171 int size = scrollBar.getSize(false); 3172 if (size <= 0) { 3173 size = cache.scrollBarSize; 3174 } 3175 return size; 3176 } 3177 return 0; 3178 } 3179 return 0; 3180 } 3181 3182 /** 3183 * <p> 3184 * Initializes the scrollbars from a given set of styled attributes. This 3185 * method should be called by subclasses that need scrollbars and when an 3186 * instance of these subclasses is created programmatically rather than 3187 * being inflated from XML. This method is automatically called when the XML 3188 * is inflated. 3189 * </p> 3190 * 3191 * @param a the styled attributes set to initialize the scrollbars from 3192 */ 3193 protected void initializeScrollbars(TypedArray a) { 3194 initScrollCache(); 3195 3196 final ScrollabilityCache scrollabilityCache = mScrollCache; 3197 3198 if (scrollabilityCache.scrollBar == null) { 3199 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 3200 } 3201 3202 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 3203 3204 if (!fadeScrollbars) { 3205 scrollabilityCache.state = ScrollabilityCache.ON; 3206 } 3207 scrollabilityCache.fadeScrollBars = fadeScrollbars; 3208 3209 3210 scrollabilityCache.scrollBarFadeDuration = a.getInt( 3211 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 3212 .getScrollBarFadeDuration()); 3213 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 3214 R.styleable.View_scrollbarDefaultDelayBeforeFade, 3215 ViewConfiguration.getScrollDefaultDelay()); 3216 3217 3218 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 3219 com.android.internal.R.styleable.View_scrollbarSize, 3220 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 3221 3222 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 3223 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 3224 3225 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 3226 if (thumb != null) { 3227 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 3228 } 3229 3230 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 3231 false); 3232 if (alwaysDraw) { 3233 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 3234 } 3235 3236 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 3237 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 3238 3239 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 3240 if (thumb != null) { 3241 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 3242 } 3243 3244 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 3245 false); 3246 if (alwaysDraw) { 3247 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 3248 } 3249 3250 // Re-apply user/background padding so that scrollbar(s) get added 3251 resolvePadding(); 3252 } 3253 3254 /** 3255 * <p> 3256 * Initalizes the scrollability cache if necessary. 3257 * </p> 3258 */ 3259 private void initScrollCache() { 3260 if (mScrollCache == null) { 3261 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 3262 } 3263 } 3264 3265 /** 3266 * Set the position of the vertical scroll bar. Should be one of 3267 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 3268 * {@link #SCROLLBAR_POSITION_RIGHT}. 3269 * 3270 * @param position Where the vertical scroll bar should be positioned. 3271 */ 3272 public void setVerticalScrollbarPosition(int position) { 3273 if (mVerticalScrollbarPosition != position) { 3274 mVerticalScrollbarPosition = position; 3275 computeOpaqueFlags(); 3276 resolvePadding(); 3277 } 3278 } 3279 3280 /** 3281 * @return The position where the vertical scroll bar will show, if applicable. 3282 * @see #setVerticalScrollbarPosition(int) 3283 */ 3284 public int getVerticalScrollbarPosition() { 3285 return mVerticalScrollbarPosition; 3286 } 3287 3288 /** 3289 * Register a callback to be invoked when focus of this view changed. 3290 * 3291 * @param l The callback that will run. 3292 */ 3293 public void setOnFocusChangeListener(OnFocusChangeListener l) { 3294 mOnFocusChangeListener = l; 3295 } 3296 3297 /** 3298 * Add a listener that will be called when the bounds of the view change due to 3299 * layout processing. 3300 * 3301 * @param listener The listener that will be called when layout bounds change. 3302 */ 3303 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 3304 if (mOnLayoutChangeListeners == null) { 3305 mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 3306 } 3307 mOnLayoutChangeListeners.add(listener); 3308 } 3309 3310 /** 3311 * Remove a listener for layout changes. 3312 * 3313 * @param listener The listener for layout bounds change. 3314 */ 3315 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 3316 if (mOnLayoutChangeListeners == null) { 3317 return; 3318 } 3319 mOnLayoutChangeListeners.remove(listener); 3320 } 3321 3322 /** 3323 * Add a listener for attach state changes. 3324 * 3325 * This listener will be called whenever this view is attached or detached 3326 * from a window. Remove the listener using 3327 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 3328 * 3329 * @param listener Listener to attach 3330 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 3331 */ 3332 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 3333 if (mOnAttachStateChangeListeners == null) { 3334 mOnAttachStateChangeListeners = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 3335 } 3336 mOnAttachStateChangeListeners.add(listener); 3337 } 3338 3339 /** 3340 * Remove a listener for attach state changes. The listener will receive no further 3341 * notification of window attach/detach events. 3342 * 3343 * @param listener Listener to remove 3344 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 3345 */ 3346 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 3347 if (mOnAttachStateChangeListeners == null) { 3348 return; 3349 } 3350 mOnAttachStateChangeListeners.remove(listener); 3351 } 3352 3353 /** 3354 * Returns the focus-change callback registered for this view. 3355 * 3356 * @return The callback, or null if one is not registered. 3357 */ 3358 public OnFocusChangeListener getOnFocusChangeListener() { 3359 return mOnFocusChangeListener; 3360 } 3361 3362 /** 3363 * Register a callback to be invoked when this view is clicked. If this view is not 3364 * clickable, it becomes clickable. 3365 * 3366 * @param l The callback that will run 3367 * 3368 * @see #setClickable(boolean) 3369 */ 3370 public void setOnClickListener(OnClickListener l) { 3371 if (!isClickable()) { 3372 setClickable(true); 3373 } 3374 mOnClickListener = l; 3375 } 3376 3377 /** 3378 * Register a callback to be invoked when this view is clicked and held. If this view is not 3379 * long clickable, it becomes long clickable. 3380 * 3381 * @param l The callback that will run 3382 * 3383 * @see #setLongClickable(boolean) 3384 */ 3385 public void setOnLongClickListener(OnLongClickListener l) { 3386 if (!isLongClickable()) { 3387 setLongClickable(true); 3388 } 3389 mOnLongClickListener = l; 3390 } 3391 3392 /** 3393 * Register a callback to be invoked when the context menu for this view is 3394 * being built. If this view is not long clickable, it becomes long clickable. 3395 * 3396 * @param l The callback that will run 3397 * 3398 */ 3399 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 3400 if (!isLongClickable()) { 3401 setLongClickable(true); 3402 } 3403 mOnCreateContextMenuListener = l; 3404 } 3405 3406 /** 3407 * Call this view's OnClickListener, if it is defined. 3408 * 3409 * @return True there was an assigned OnClickListener that was called, false 3410 * otherwise is returned. 3411 */ 3412 public boolean performClick() { 3413 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 3414 3415 if (mOnClickListener != null) { 3416 playSoundEffect(SoundEffectConstants.CLICK); 3417 mOnClickListener.onClick(this); 3418 return true; 3419 } 3420 3421 return false; 3422 } 3423 3424 /** 3425 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 3426 * OnLongClickListener did not consume the event. 3427 * 3428 * @return True if one of the above receivers consumed the event, false otherwise. 3429 */ 3430 public boolean performLongClick() { 3431 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 3432 3433 boolean handled = false; 3434 if (mOnLongClickListener != null) { 3435 handled = mOnLongClickListener.onLongClick(View.this); 3436 } 3437 if (!handled) { 3438 handled = showContextMenu(); 3439 } 3440 if (handled) { 3441 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 3442 } 3443 return handled; 3444 } 3445 3446 /** 3447 * Performs button-related actions during a touch down event. 3448 * 3449 * @param event The event. 3450 * @return True if the down was consumed. 3451 * 3452 * @hide 3453 */ 3454 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 3455 if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 3456 if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) { 3457 return true; 3458 } 3459 } 3460 return false; 3461 } 3462 3463 /** 3464 * Bring up the context menu for this view. 3465 * 3466 * @return Whether a context menu was displayed. 3467 */ 3468 public boolean showContextMenu() { 3469 return getParent().showContextMenuForChild(this); 3470 } 3471 3472 /** 3473 * Bring up the context menu for this view, referring to the item under the specified point. 3474 * 3475 * @param x The referenced x coordinate. 3476 * @param y The referenced y coordinate. 3477 * @param metaState The keyboard modifiers that were pressed. 3478 * @return Whether a context menu was displayed. 3479 * 3480 * @hide 3481 */ 3482 public boolean showContextMenu(float x, float y, int metaState) { 3483 return showContextMenu(); 3484 } 3485 3486 /** 3487 * Start an action mode. 3488 * 3489 * @param callback Callback that will control the lifecycle of the action mode 3490 * @return The new action mode if it is started, null otherwise 3491 * 3492 * @see ActionMode 3493 */ 3494 public ActionMode startActionMode(ActionMode.Callback callback) { 3495 return getParent().startActionModeForChild(this, callback); 3496 } 3497 3498 /** 3499 * Register a callback to be invoked when a key is pressed in this view. 3500 * @param l the key listener to attach to this view 3501 */ 3502 public void setOnKeyListener(OnKeyListener l) { 3503 mOnKeyListener = l; 3504 } 3505 3506 /** 3507 * Register a callback to be invoked when a touch event is sent to this view. 3508 * @param l the touch listener to attach to this view 3509 */ 3510 public void setOnTouchListener(OnTouchListener l) { 3511 mOnTouchListener = l; 3512 } 3513 3514 /** 3515 * Register a callback to be invoked when a generic motion event is sent to this view. 3516 * @param l the generic motion listener to attach to this view 3517 */ 3518 public void setOnGenericMotionListener(OnGenericMotionListener l) { 3519 mOnGenericMotionListener = l; 3520 } 3521 3522 /** 3523 * Register a callback to be invoked when a hover event is sent to this view. 3524 * @param l the hover listener to attach to this view 3525 */ 3526 public void setOnHoverListener(OnHoverListener l) { 3527 mOnHoverListener = l; 3528 } 3529 3530 /** 3531 * Register a drag event listener callback object for this View. The parameter is 3532 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 3533 * View, the system calls the 3534 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 3535 * @param l An implementation of {@link android.view.View.OnDragListener}. 3536 */ 3537 public void setOnDragListener(OnDragListener l) { 3538 mOnDragListener = l; 3539 } 3540 3541 /** 3542 * Give this view focus. This will cause 3543 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 3544 * 3545 * Note: this does not check whether this {@link View} should get focus, it just 3546 * gives it focus no matter what. It should only be called internally by framework 3547 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 3548 * 3549 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 3550 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 3551 * focus moved when requestFocus() is called. It may not always 3552 * apply, in which case use the default View.FOCUS_DOWN. 3553 * @param previouslyFocusedRect The rectangle of the view that had focus 3554 * prior in this View's coordinate system. 3555 */ 3556 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) { 3557 if (DBG) { 3558 System.out.println(this + " requestFocus()"); 3559 } 3560 3561 if ((mPrivateFlags & FOCUSED) == 0) { 3562 mPrivateFlags |= FOCUSED; 3563 3564 if (mParent != null) { 3565 mParent.requestChildFocus(this, this); 3566 } 3567 3568 onFocusChanged(true, direction, previouslyFocusedRect); 3569 refreshDrawableState(); 3570 } 3571 } 3572 3573 /** 3574 * Request that a rectangle of this view be visible on the screen, 3575 * scrolling if necessary just enough. 3576 * 3577 * <p>A View should call this if it maintains some notion of which part 3578 * of its content is interesting. For example, a text editing view 3579 * should call this when its cursor moves. 3580 * 3581 * @param rectangle The rectangle. 3582 * @return Whether any parent scrolled. 3583 */ 3584 public boolean requestRectangleOnScreen(Rect rectangle) { 3585 return requestRectangleOnScreen(rectangle, false); 3586 } 3587 3588 /** 3589 * Request that a rectangle of this view be visible on the screen, 3590 * scrolling if necessary just enough. 3591 * 3592 * <p>A View should call this if it maintains some notion of which part 3593 * of its content is interesting. For example, a text editing view 3594 * should call this when its cursor moves. 3595 * 3596 * <p>When <code>immediate</code> is set to true, scrolling will not be 3597 * animated. 3598 * 3599 * @param rectangle The rectangle. 3600 * @param immediate True to forbid animated scrolling, false otherwise 3601 * @return Whether any parent scrolled. 3602 */ 3603 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 3604 View child = this; 3605 ViewParent parent = mParent; 3606 boolean scrolled = false; 3607 while (parent != null) { 3608 scrolled |= parent.requestChildRectangleOnScreen(child, 3609 rectangle, immediate); 3610 3611 // offset rect so next call has the rectangle in the 3612 // coordinate system of its direct child. 3613 rectangle.offset(child.getLeft(), child.getTop()); 3614 rectangle.offset(-child.getScrollX(), -child.getScrollY()); 3615 3616 if (!(parent instanceof View)) { 3617 break; 3618 } 3619 3620 child = (View) parent; 3621 parent = child.getParent(); 3622 } 3623 return scrolled; 3624 } 3625 3626 /** 3627 * Called when this view wants to give up focus. This will cause 3628 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 3629 */ 3630 public void clearFocus() { 3631 if (DBG) { 3632 System.out.println(this + " clearFocus()"); 3633 } 3634 3635 if ((mPrivateFlags & FOCUSED) != 0) { 3636 mPrivateFlags &= ~FOCUSED; 3637 3638 if (mParent != null) { 3639 mParent.clearChildFocus(this); 3640 } 3641 3642 onFocusChanged(false, 0, null); 3643 refreshDrawableState(); 3644 } 3645 } 3646 3647 /** 3648 * Called to clear the focus of a view that is about to be removed. 3649 * Doesn't call clearChildFocus, which prevents this view from taking 3650 * focus again before it has been removed from the parent 3651 */ 3652 void clearFocusForRemoval() { 3653 if ((mPrivateFlags & FOCUSED) != 0) { 3654 mPrivateFlags &= ~FOCUSED; 3655 3656 onFocusChanged(false, 0, null); 3657 refreshDrawableState(); 3658 } 3659 } 3660 3661 /** 3662 * Called internally by the view system when a new view is getting focus. 3663 * This is what clears the old focus. 3664 */ 3665 void unFocus() { 3666 if (DBG) { 3667 System.out.println(this + " unFocus()"); 3668 } 3669 3670 if ((mPrivateFlags & FOCUSED) != 0) { 3671 mPrivateFlags &= ~FOCUSED; 3672 3673 onFocusChanged(false, 0, null); 3674 refreshDrawableState(); 3675 } 3676 } 3677 3678 /** 3679 * Returns true if this view has focus iteself, or is the ancestor of the 3680 * view that has focus. 3681 * 3682 * @return True if this view has or contains focus, false otherwise. 3683 */ 3684 @ViewDebug.ExportedProperty(category = "focus") 3685 public boolean hasFocus() { 3686 return (mPrivateFlags & FOCUSED) != 0; 3687 } 3688 3689 /** 3690 * Returns true if this view is focusable or if it contains a reachable View 3691 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 3692 * is a View whose parents do not block descendants focus. 3693 * 3694 * Only {@link #VISIBLE} views are considered focusable. 3695 * 3696 * @return True if the view is focusable or if the view contains a focusable 3697 * View, false otherwise. 3698 * 3699 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 3700 */ 3701 public boolean hasFocusable() { 3702 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 3703 } 3704 3705 /** 3706 * Called by the view system when the focus state of this view changes. 3707 * When the focus change event is caused by directional navigation, direction 3708 * and previouslyFocusedRect provide insight into where the focus is coming from. 3709 * When overriding, be sure to call up through to the super class so that 3710 * the standard focus handling will occur. 3711 * 3712 * @param gainFocus True if the View has focus; false otherwise. 3713 * @param direction The direction focus has moved when requestFocus() 3714 * is called to give this view focus. Values are 3715 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 3716 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 3717 * It may not always apply, in which case use the default. 3718 * @param previouslyFocusedRect The rectangle, in this view's coordinate 3719 * system, of the previously focused view. If applicable, this will be 3720 * passed in as finer grained information about where the focus is coming 3721 * from (in addition to direction). Will be <code>null</code> otherwise. 3722 */ 3723 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) { 3724 if (gainFocus) { 3725 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 3726 } 3727 3728 InputMethodManager imm = InputMethodManager.peekInstance(); 3729 if (!gainFocus) { 3730 if (isPressed()) { 3731 setPressed(false); 3732 } 3733 if (imm != null && mAttachInfo != null 3734 && mAttachInfo.mHasWindowFocus) { 3735 imm.focusOut(this); 3736 } 3737 onFocusLost(); 3738 } else if (imm != null && mAttachInfo != null 3739 && mAttachInfo.mHasWindowFocus) { 3740 imm.focusIn(this); 3741 } 3742 3743 invalidate(true); 3744 if (mOnFocusChangeListener != null) { 3745 mOnFocusChangeListener.onFocusChange(this, gainFocus); 3746 } 3747 3748 if (mAttachInfo != null) { 3749 mAttachInfo.mKeyDispatchState.reset(this); 3750 } 3751 } 3752 3753 /** 3754 * Sends an accessibility event of the given type. If accessiiblity is 3755 * not enabled this method has no effect. The default implementation calls 3756 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 3757 * to populate information about the event source (this View), then calls 3758 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 3759 * populate the text content of the event source including its descendants, 3760 * and last calls 3761 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 3762 * on its parent to resuest sending of the event to interested parties. 3763 * 3764 * @param eventType The type of the event to send. 3765 * 3766 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 3767 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 3768 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 3769 */ 3770 public void sendAccessibilityEvent(int eventType) { 3771 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 3772 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 3773 } 3774 } 3775 3776 /** 3777 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 3778 * takes as an argument an empty {@link AccessibilityEvent} and does not 3779 * perfrom a check whether accessibility is enabled. 3780 * 3781 * @param event The event to send. 3782 * 3783 * @see #sendAccessibilityEvent(int) 3784 */ 3785 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 3786 if (!isShown()) { 3787 return; 3788 } 3789 onInitializeAccessibilityEvent(event); 3790 dispatchPopulateAccessibilityEvent(event); 3791 // In the beginning we called #isShown(), so we know that getParent() is not null. 3792 getParent().requestSendAccessibilityEvent(this, event); 3793 } 3794 3795 /** 3796 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 3797 * to its children for adding their text content to the event. Note that the 3798 * event text is populated in a separate dispatch path since we add to the 3799 * event not only the text of the source but also the text of all its descendants. 3800 * </p> 3801 * A typical implementation will call 3802 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 3803 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 3804 * on each child. Override this method if custom population of the event text 3805 * content is required. 3806 * 3807 * @param event The event. 3808 * 3809 * @return True if the event population was completed. 3810 */ 3811 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 3812 onPopulateAccessibilityEvent(event); 3813 return false; 3814 } 3815 3816 /** 3817 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 3818 * giving a chance to this View to populate the accessibility event with its 3819 * text content. While the implementation is free to modify other event 3820 * attributes this should be performed in 3821 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 3822 * <p> 3823 * Example: Adding formatted date string to an accessibility event in addition 3824 * to the text added by the super implementation. 3825 * </p><p><pre><code> 3826 * public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 3827 * super.onPopulateAccessibilityEvent(event); 3828 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 3829 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 3830 * mCurrentDate.getTimeInMillis(), flags); 3831 * event.getText().add(selectedDateUtterance); 3832 * } 3833 * </code></pre></p> 3834 * 3835 * @param event The accessibility event which to populate. 3836 * 3837 * @see #sendAccessibilityEvent(int) 3838 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 3839 */ 3840 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 3841 } 3842 3843 /** 3844 * Initializes an {@link AccessibilityEvent} with information about the 3845 * the type of the event and this View which is the event source. In other 3846 * words, the source of an accessibility event is the view whose state 3847 * change triggered firing the event. 3848 * <p> 3849 * Example: Setting the password property of an event in addition 3850 * to properties set by the super implementation. 3851 * </p><p><pre><code> 3852 * public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 3853 * super.onInitializeAccessibilityEvent(event); 3854 * event.setPassword(true); 3855 * } 3856 * </code></pre></p> 3857 * @param event The event to initialeze. 3858 * 3859 * @see #sendAccessibilityEvent(int) 3860 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 3861 */ 3862 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 3863 event.setSource(this); 3864 event.setClassName(getClass().getName()); 3865 event.setPackageName(getContext().getPackageName()); 3866 event.setEnabled(isEnabled()); 3867 event.setContentDescription(mContentDescription); 3868 3869 final int eventType = event.getEventType(); 3870 switch (eventType) { 3871 case AccessibilityEvent.TYPE_VIEW_FOCUSED: { 3872 if (mAttachInfo != null) { 3873 ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList; 3874 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, 3875 FOCUSABLES_ALL); 3876 event.setItemCount(focusablesTempList.size()); 3877 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 3878 focusablesTempList.clear(); 3879 } 3880 } break; 3881 case AccessibilityEvent.TYPE_VIEW_SCROLLED: { 3882 event.setScrollX(mScrollX); 3883 event.setScrollY(mScrollY); 3884 event.setItemCount(getHeight()); 3885 } break; 3886 } 3887 } 3888 3889 /** 3890 * Returns an {@link AccessibilityNodeInfo} representing this view from the 3891 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 3892 * This method is responsible for obtaining an accessibility node info from a 3893 * pool of reusable instances and calling 3894 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 3895 * initialize the former. 3896 * <p> 3897 * Note: The client is responsible for recycling the obtained instance by calling 3898 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 3899 * </p> 3900 * @return A populated {@link AccessibilityNodeInfo}. 3901 * 3902 * @see AccessibilityNodeInfo 3903 */ 3904 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 3905 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 3906 onInitializeAccessibilityNodeInfo(info); 3907 return info; 3908 } 3909 3910 /** 3911 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 3912 * The base implementation sets: 3913 * <ul> 3914 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 3915 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 3916 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 3917 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 3918 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 3919 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 3920 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 3921 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 3922 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 3923 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 3924 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 3925 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 3926 * </ul> 3927 * <p> 3928 * Subclasses should override this method, call the super implementation, 3929 * and set additional attributes. 3930 * </p> 3931 * @param info The instance to initialize. 3932 */ 3933 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 3934 Rect bounds = mAttachInfo.mTmpInvalRect; 3935 getDrawingRect(bounds); 3936 info.setBoundsInParent(bounds); 3937 3938 int[] locationOnScreen = mAttachInfo.mInvalidateChildLocation; 3939 getLocationOnScreen(locationOnScreen); 3940 bounds.offsetTo(0, 0); 3941 bounds.offset(locationOnScreen[0], locationOnScreen[1]); 3942 info.setBoundsInScreen(bounds); 3943 3944 ViewParent parent = getParent(); 3945 if (parent instanceof View) { 3946 View parentView = (View) parent; 3947 info.setParent(parentView); 3948 } 3949 3950 info.setPackageName(mContext.getPackageName()); 3951 info.setClassName(getClass().getName()); 3952 info.setContentDescription(getContentDescription()); 3953 3954 info.setEnabled(isEnabled()); 3955 info.setClickable(isClickable()); 3956 info.setFocusable(isFocusable()); 3957 info.setFocused(isFocused()); 3958 info.setSelected(isSelected()); 3959 info.setLongClickable(isLongClickable()); 3960 3961 // TODO: These make sense only if we are in an AdapterView but all 3962 // views can be selected. Maybe from accessiiblity perspective 3963 // we should report as selectable view in an AdapterView. 3964 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 3965 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 3966 3967 if (isFocusable()) { 3968 if (isFocused()) { 3969 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 3970 } else { 3971 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 3972 } 3973 } 3974 } 3975 3976 /** 3977 * Gets the unique identifier of this view on the screen for accessibility purposes. 3978 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 3979 * 3980 * @return The view accessibility id. 3981 * 3982 * @hide 3983 */ 3984 public int getAccessibilityViewId() { 3985 if (mAccessibilityViewId == NO_ID) { 3986 mAccessibilityViewId = sNextAccessibilityViewId++; 3987 } 3988 return mAccessibilityViewId; 3989 } 3990 3991 /** 3992 * Gets the unique identifier of the window in which this View reseides. 3993 * 3994 * @return The window accessibility id. 3995 * 3996 * @hide 3997 */ 3998 public int getAccessibilityWindowId() { 3999 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID; 4000 } 4001 4002 /** 4003 * Gets the {@link View} description. It briefly describes the view and is 4004 * primarily used for accessibility support. Set this property to enable 4005 * better accessibility support for your application. This is especially 4006 * true for views that do not have textual representation (For example, 4007 * ImageButton). 4008 * 4009 * @return The content descriptiopn. 4010 * 4011 * @attr ref android.R.styleable#View_contentDescription 4012 */ 4013 public CharSequence getContentDescription() { 4014 return mContentDescription; 4015 } 4016 4017 /** 4018 * Sets the {@link View} description. It briefly describes the view and is 4019 * primarily used for accessibility support. Set this property to enable 4020 * better accessibility support for your application. This is especially 4021 * true for views that do not have textual representation (For example, 4022 * ImageButton). 4023 * 4024 * @param contentDescription The content description. 4025 * 4026 * @attr ref android.R.styleable#View_contentDescription 4027 */ 4028 public void setContentDescription(CharSequence contentDescription) { 4029 mContentDescription = contentDescription; 4030 } 4031 4032 /** 4033 * Invoked whenever this view loses focus, either by losing window focus or by losing 4034 * focus within its window. This method can be used to clear any state tied to the 4035 * focus. For instance, if a button is held pressed with the trackball and the window 4036 * loses focus, this method can be used to cancel the press. 4037 * 4038 * Subclasses of View overriding this method should always call super.onFocusLost(). 4039 * 4040 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 4041 * @see #onWindowFocusChanged(boolean) 4042 * 4043 * @hide pending API council approval 4044 */ 4045 protected void onFocusLost() { 4046 resetPressedState(); 4047 } 4048 4049 private void resetPressedState() { 4050 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 4051 return; 4052 } 4053 4054 if (isPressed()) { 4055 setPressed(false); 4056 4057 if (!mHasPerformedLongPress) { 4058 removeLongPressCallback(); 4059 } 4060 } 4061 } 4062 4063 /** 4064 * Returns true if this view has focus 4065 * 4066 * @return True if this view has focus, false otherwise. 4067 */ 4068 @ViewDebug.ExportedProperty(category = "focus") 4069 public boolean isFocused() { 4070 return (mPrivateFlags & FOCUSED) != 0; 4071 } 4072 4073 /** 4074 * Find the view in the hierarchy rooted at this view that currently has 4075 * focus. 4076 * 4077 * @return The view that currently has focus, or null if no focused view can 4078 * be found. 4079 */ 4080 public View findFocus() { 4081 return (mPrivateFlags & FOCUSED) != 0 ? this : null; 4082 } 4083 4084 /** 4085 * Change whether this view is one of the set of scrollable containers in 4086 * its window. This will be used to determine whether the window can 4087 * resize or must pan when a soft input area is open -- scrollable 4088 * containers allow the window to use resize mode since the container 4089 * will appropriately shrink. 4090 */ 4091 public void setScrollContainer(boolean isScrollContainer) { 4092 if (isScrollContainer) { 4093 if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) { 4094 mAttachInfo.mScrollContainers.add(this); 4095 mPrivateFlags |= SCROLL_CONTAINER_ADDED; 4096 } 4097 mPrivateFlags |= SCROLL_CONTAINER; 4098 } else { 4099 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) { 4100 mAttachInfo.mScrollContainers.remove(this); 4101 } 4102 mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED); 4103 } 4104 } 4105 4106 /** 4107 * Returns the quality of the drawing cache. 4108 * 4109 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 4110 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 4111 * 4112 * @see #setDrawingCacheQuality(int) 4113 * @see #setDrawingCacheEnabled(boolean) 4114 * @see #isDrawingCacheEnabled() 4115 * 4116 * @attr ref android.R.styleable#View_drawingCacheQuality 4117 */ 4118 public int getDrawingCacheQuality() { 4119 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 4120 } 4121 4122 /** 4123 * Set the drawing cache quality of this view. This value is used only when the 4124 * drawing cache is enabled 4125 * 4126 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 4127 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 4128 * 4129 * @see #getDrawingCacheQuality() 4130 * @see #setDrawingCacheEnabled(boolean) 4131 * @see #isDrawingCacheEnabled() 4132 * 4133 * @attr ref android.R.styleable#View_drawingCacheQuality 4134 */ 4135 public void setDrawingCacheQuality(int quality) { 4136 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 4137 } 4138 4139 /** 4140 * Returns whether the screen should remain on, corresponding to the current 4141 * value of {@link #KEEP_SCREEN_ON}. 4142 * 4143 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 4144 * 4145 * @see #setKeepScreenOn(boolean) 4146 * 4147 * @attr ref android.R.styleable#View_keepScreenOn 4148 */ 4149 public boolean getKeepScreenOn() { 4150 return (mViewFlags & KEEP_SCREEN_ON) != 0; 4151 } 4152 4153 /** 4154 * Controls whether the screen should remain on, modifying the 4155 * value of {@link #KEEP_SCREEN_ON}. 4156 * 4157 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 4158 * 4159 * @see #getKeepScreenOn() 4160 * 4161 * @attr ref android.R.styleable#View_keepScreenOn 4162 */ 4163 public void setKeepScreenOn(boolean keepScreenOn) { 4164 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 4165 } 4166 4167 /** 4168 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 4169 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4170 * 4171 * @attr ref android.R.styleable#View_nextFocusLeft 4172 */ 4173 public int getNextFocusLeftId() { 4174 return mNextFocusLeftId; 4175 } 4176 4177 /** 4178 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 4179 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 4180 * decide automatically. 4181 * 4182 * @attr ref android.R.styleable#View_nextFocusLeft 4183 */ 4184 public void setNextFocusLeftId(int nextFocusLeftId) { 4185 mNextFocusLeftId = nextFocusLeftId; 4186 } 4187 4188 /** 4189 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 4190 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4191 * 4192 * @attr ref android.R.styleable#View_nextFocusRight 4193 */ 4194 public int getNextFocusRightId() { 4195 return mNextFocusRightId; 4196 } 4197 4198 /** 4199 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 4200 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 4201 * decide automatically. 4202 * 4203 * @attr ref android.R.styleable#View_nextFocusRight 4204 */ 4205 public void setNextFocusRightId(int nextFocusRightId) { 4206 mNextFocusRightId = nextFocusRightId; 4207 } 4208 4209 /** 4210 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 4211 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4212 * 4213 * @attr ref android.R.styleable#View_nextFocusUp 4214 */ 4215 public int getNextFocusUpId() { 4216 return mNextFocusUpId; 4217 } 4218 4219 /** 4220 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 4221 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 4222 * decide automatically. 4223 * 4224 * @attr ref android.R.styleable#View_nextFocusUp 4225 */ 4226 public void setNextFocusUpId(int nextFocusUpId) { 4227 mNextFocusUpId = nextFocusUpId; 4228 } 4229 4230 /** 4231 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 4232 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4233 * 4234 * @attr ref android.R.styleable#View_nextFocusDown 4235 */ 4236 public int getNextFocusDownId() { 4237 return mNextFocusDownId; 4238 } 4239 4240 /** 4241 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 4242 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 4243 * decide automatically. 4244 * 4245 * @attr ref android.R.styleable#View_nextFocusDown 4246 */ 4247 public void setNextFocusDownId(int nextFocusDownId) { 4248 mNextFocusDownId = nextFocusDownId; 4249 } 4250 4251 /** 4252 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 4253 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 4254 * 4255 * @attr ref android.R.styleable#View_nextFocusForward 4256 */ 4257 public int getNextFocusForwardId() { 4258 return mNextFocusForwardId; 4259 } 4260 4261 /** 4262 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 4263 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 4264 * decide automatically. 4265 * 4266 * @attr ref android.R.styleable#View_nextFocusForward 4267 */ 4268 public void setNextFocusForwardId(int nextFocusForwardId) { 4269 mNextFocusForwardId = nextFocusForwardId; 4270 } 4271 4272 /** 4273 * Returns the visibility of this view and all of its ancestors 4274 * 4275 * @return True if this view and all of its ancestors are {@link #VISIBLE} 4276 */ 4277 public boolean isShown() { 4278 View current = this; 4279 //noinspection ConstantConditions 4280 do { 4281 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 4282 return false; 4283 } 4284 ViewParent parent = current.mParent; 4285 if (parent == null) { 4286 return false; // We are not attached to the view root 4287 } 4288 if (!(parent instanceof View)) { 4289 return true; 4290 } 4291 current = (View) parent; 4292 } while (current != null); 4293 4294 return false; 4295 } 4296 4297 /** 4298 * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag 4299 * is set 4300 * 4301 * @param insets Insets for system windows 4302 * 4303 * @return True if this view applied the insets, false otherwise 4304 */ 4305 protected boolean fitSystemWindows(Rect insets) { 4306 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 4307 mPaddingLeft = insets.left; 4308 mPaddingTop = insets.top; 4309 mPaddingRight = insets.right; 4310 mPaddingBottom = insets.bottom; 4311 requestLayout(); 4312 return true; 4313 } 4314 return false; 4315 } 4316 4317 /** 4318 * Set whether or not this view should account for system screen decorations 4319 * such as the status bar and inset its content. This allows this view to be 4320 * positioned in absolute screen coordinates and remain visible to the user. 4321 * 4322 * <p>This should only be used by top-level window decor views. 4323 * 4324 * @param fitSystemWindows true to inset content for system screen decorations, false for 4325 * default behavior. 4326 * 4327 * @attr ref android.R.styleable#View_fitsSystemWindows 4328 */ 4329 public void setFitsSystemWindows(boolean fitSystemWindows) { 4330 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 4331 } 4332 4333 /** 4334 * Check for the FITS_SYSTEM_WINDOWS flag. If this method returns true, this view 4335 * will account for system screen decorations such as the status bar and inset its 4336 * content. This allows the view to be positioned in absolute screen coordinates 4337 * and remain visible to the user. 4338 * 4339 * @return true if this view will adjust its content bounds for system screen decorations. 4340 * 4341 * @attr ref android.R.styleable#View_fitsSystemWindows 4342 */ 4343 public boolean fitsSystemWindows() { 4344 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 4345 } 4346 4347 /** 4348 * Returns the visibility status for this view. 4349 * 4350 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 4351 * @attr ref android.R.styleable#View_visibility 4352 */ 4353 @ViewDebug.ExportedProperty(mapping = { 4354 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 4355 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 4356 @ViewDebug.IntToString(from = GONE, to = "GONE") 4357 }) 4358 public int getVisibility() { 4359 return mViewFlags & VISIBILITY_MASK; 4360 } 4361 4362 /** 4363 * Set the enabled state of this view. 4364 * 4365 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 4366 * @attr ref android.R.styleable#View_visibility 4367 */ 4368 @RemotableViewMethod 4369 public void setVisibility(int visibility) { 4370 setFlags(visibility, VISIBILITY_MASK); 4371 if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false); 4372 } 4373 4374 /** 4375 * Returns the enabled status for this view. The interpretation of the 4376 * enabled state varies by subclass. 4377 * 4378 * @return True if this view is enabled, false otherwise. 4379 */ 4380 @ViewDebug.ExportedProperty 4381 public boolean isEnabled() { 4382 return (mViewFlags & ENABLED_MASK) == ENABLED; 4383 } 4384 4385 /** 4386 * Set the enabled state of this view. The interpretation of the enabled 4387 * state varies by subclass. 4388 * 4389 * @param enabled True if this view is enabled, false otherwise. 4390 */ 4391 @RemotableViewMethod 4392 public void setEnabled(boolean enabled) { 4393 if (enabled == isEnabled()) return; 4394 4395 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 4396 4397 /* 4398 * The View most likely has to change its appearance, so refresh 4399 * the drawable state. 4400 */ 4401 refreshDrawableState(); 4402 4403 // Invalidate too, since the default behavior for views is to be 4404 // be drawn at 50% alpha rather than to change the drawable. 4405 invalidate(true); 4406 } 4407 4408 /** 4409 * Set whether this view can receive the focus. 4410 * 4411 * Setting this to false will also ensure that this view is not focusable 4412 * in touch mode. 4413 * 4414 * @param focusable If true, this view can receive the focus. 4415 * 4416 * @see #setFocusableInTouchMode(boolean) 4417 * @attr ref android.R.styleable#View_focusable 4418 */ 4419 public void setFocusable(boolean focusable) { 4420 if (!focusable) { 4421 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 4422 } 4423 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 4424 } 4425 4426 /** 4427 * Set whether this view can receive focus while in touch mode. 4428 * 4429 * Setting this to true will also ensure that this view is focusable. 4430 * 4431 * @param focusableInTouchMode If true, this view can receive the focus while 4432 * in touch mode. 4433 * 4434 * @see #setFocusable(boolean) 4435 * @attr ref android.R.styleable#View_focusableInTouchMode 4436 */ 4437 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 4438 // Focusable in touch mode should always be set before the focusable flag 4439 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 4440 // which, in touch mode, will not successfully request focus on this view 4441 // because the focusable in touch mode flag is not set 4442 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 4443 if (focusableInTouchMode) { 4444 setFlags(FOCUSABLE, FOCUSABLE_MASK); 4445 } 4446 } 4447 4448 /** 4449 * Set whether this view should have sound effects enabled for events such as 4450 * clicking and touching. 4451 * 4452 * <p>You may wish to disable sound effects for a view if you already play sounds, 4453 * for instance, a dial key that plays dtmf tones. 4454 * 4455 * @param soundEffectsEnabled whether sound effects are enabled for this view. 4456 * @see #isSoundEffectsEnabled() 4457 * @see #playSoundEffect(int) 4458 * @attr ref android.R.styleable#View_soundEffectsEnabled 4459 */ 4460 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 4461 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 4462 } 4463 4464 /** 4465 * @return whether this view should have sound effects enabled for events such as 4466 * clicking and touching. 4467 * 4468 * @see #setSoundEffectsEnabled(boolean) 4469 * @see #playSoundEffect(int) 4470 * @attr ref android.R.styleable#View_soundEffectsEnabled 4471 */ 4472 @ViewDebug.ExportedProperty 4473 public boolean isSoundEffectsEnabled() { 4474 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 4475 } 4476 4477 /** 4478 * Set whether this view should have haptic feedback for events such as 4479 * long presses. 4480 * 4481 * <p>You may wish to disable haptic feedback if your view already controls 4482 * its own haptic feedback. 4483 * 4484 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 4485 * @see #isHapticFeedbackEnabled() 4486 * @see #performHapticFeedback(int) 4487 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 4488 */ 4489 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 4490 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 4491 } 4492 4493 /** 4494 * @return whether this view should have haptic feedback enabled for events 4495 * long presses. 4496 * 4497 * @see #setHapticFeedbackEnabled(boolean) 4498 * @see #performHapticFeedback(int) 4499 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 4500 */ 4501 @ViewDebug.ExportedProperty 4502 public boolean isHapticFeedbackEnabled() { 4503 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 4504 } 4505 4506 /** 4507 * Returns the layout direction for this view. 4508 * 4509 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 4510 * {@link #LAYOUT_DIRECTION_RTL}, 4511 * {@link #LAYOUT_DIRECTION_INHERIT} or 4512 * {@link #LAYOUT_DIRECTION_LOCALE}. 4513 * @attr ref android.R.styleable#View_layoutDirection 4514 * 4515 * @hide 4516 */ 4517 @ViewDebug.ExportedProperty(category = "layout", mapping = { 4518 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 4519 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 4520 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 4521 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 4522 }) 4523 public int getLayoutDirection() { 4524 return mViewFlags & LAYOUT_DIRECTION_MASK; 4525 } 4526 4527 /** 4528 * Set the layout direction for this view. This will propagate a reset of layout direction 4529 * resolution to the view's children and resolve layout direction for this view. 4530 * 4531 * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR}, 4532 * {@link #LAYOUT_DIRECTION_RTL}, 4533 * {@link #LAYOUT_DIRECTION_INHERIT} or 4534 * {@link #LAYOUT_DIRECTION_LOCALE}. 4535 * 4536 * @attr ref android.R.styleable#View_layoutDirection 4537 * 4538 * @hide 4539 */ 4540 @RemotableViewMethod 4541 public void setLayoutDirection(int layoutDirection) { 4542 if (getLayoutDirection() != layoutDirection) { 4543 resetResolvedLayoutDirection(); 4544 // Setting the flag will also request a layout. 4545 setFlags(layoutDirection, LAYOUT_DIRECTION_MASK); 4546 } 4547 } 4548 4549 /** 4550 * Returns the resolved layout direction for this view. 4551 * 4552 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 4553 * {@link #LAYOUT_DIRECTION_LTR} id the layout direction is not RTL. 4554 * 4555 * @hide 4556 */ 4557 @ViewDebug.ExportedProperty(category = "layout", mapping = { 4558 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 4559 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 4560 }) 4561 public int getResolvedLayoutDirection() { 4562 resolveLayoutDirectionIfNeeded(); 4563 return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ? 4564 LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 4565 } 4566 4567 /** 4568 * <p>Indicates whether or not this view's layout is right-to-left. This is resolved from 4569 * layout attribute and/or the inherited value from the parent.</p> 4570 * 4571 * @return true if the layout is right-to-left. 4572 * 4573 * @hide 4574 */ 4575 @ViewDebug.ExportedProperty(category = "layout") 4576 public boolean isLayoutRtl() { 4577 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL); 4578 } 4579 4580 /** 4581 * If this view doesn't do any drawing on its own, set this flag to 4582 * allow further optimizations. By default, this flag is not set on 4583 * View, but could be set on some View subclasses such as ViewGroup. 4584 * 4585 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 4586 * you should clear this flag. 4587 * 4588 * @param willNotDraw whether or not this View draw on its own 4589 */ 4590 public void setWillNotDraw(boolean willNotDraw) { 4591 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 4592 } 4593 4594 /** 4595 * Returns whether or not this View draws on its own. 4596 * 4597 * @return true if this view has nothing to draw, false otherwise 4598 */ 4599 @ViewDebug.ExportedProperty(category = "drawing") 4600 public boolean willNotDraw() { 4601 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 4602 } 4603 4604 /** 4605 * When a View's drawing cache is enabled, drawing is redirected to an 4606 * offscreen bitmap. Some views, like an ImageView, must be able to 4607 * bypass this mechanism if they already draw a single bitmap, to avoid 4608 * unnecessary usage of the memory. 4609 * 4610 * @param willNotCacheDrawing true if this view does not cache its 4611 * drawing, false otherwise 4612 */ 4613 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 4614 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 4615 } 4616 4617 /** 4618 * Returns whether or not this View can cache its drawing or not. 4619 * 4620 * @return true if this view does not cache its drawing, false otherwise 4621 */ 4622 @ViewDebug.ExportedProperty(category = "drawing") 4623 public boolean willNotCacheDrawing() { 4624 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 4625 } 4626 4627 /** 4628 * Indicates whether this view reacts to click events or not. 4629 * 4630 * @return true if the view is clickable, false otherwise 4631 * 4632 * @see #setClickable(boolean) 4633 * @attr ref android.R.styleable#View_clickable 4634 */ 4635 @ViewDebug.ExportedProperty 4636 public boolean isClickable() { 4637 return (mViewFlags & CLICKABLE) == CLICKABLE; 4638 } 4639 4640 /** 4641 * Enables or disables click events for this view. When a view 4642 * is clickable it will change its state to "pressed" on every click. 4643 * Subclasses should set the view clickable to visually react to 4644 * user's clicks. 4645 * 4646 * @param clickable true to make the view clickable, false otherwise 4647 * 4648 * @see #isClickable() 4649 * @attr ref android.R.styleable#View_clickable 4650 */ 4651 public void setClickable(boolean clickable) { 4652 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 4653 } 4654 4655 /** 4656 * Indicates whether this view reacts to long click events or not. 4657 * 4658 * @return true if the view is long clickable, false otherwise 4659 * 4660 * @see #setLongClickable(boolean) 4661 * @attr ref android.R.styleable#View_longClickable 4662 */ 4663 public boolean isLongClickable() { 4664 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 4665 } 4666 4667 /** 4668 * Enables or disables long click events for this view. When a view is long 4669 * clickable it reacts to the user holding down the button for a longer 4670 * duration than a tap. This event can either launch the listener or a 4671 * context menu. 4672 * 4673 * @param longClickable true to make the view long clickable, false otherwise 4674 * @see #isLongClickable() 4675 * @attr ref android.R.styleable#View_longClickable 4676 */ 4677 public void setLongClickable(boolean longClickable) { 4678 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 4679 } 4680 4681 /** 4682 * Sets the pressed state for this view. 4683 * 4684 * @see #isClickable() 4685 * @see #setClickable(boolean) 4686 * 4687 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 4688 * the View's internal state from a previously set "pressed" state. 4689 */ 4690 public void setPressed(boolean pressed) { 4691 if (pressed) { 4692 mPrivateFlags |= PRESSED; 4693 } else { 4694 mPrivateFlags &= ~PRESSED; 4695 } 4696 refreshDrawableState(); 4697 dispatchSetPressed(pressed); 4698 } 4699 4700 /** 4701 * Dispatch setPressed to all of this View's children. 4702 * 4703 * @see #setPressed(boolean) 4704 * 4705 * @param pressed The new pressed state 4706 */ 4707 protected void dispatchSetPressed(boolean pressed) { 4708 } 4709 4710 /** 4711 * Indicates whether the view is currently in pressed state. Unless 4712 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 4713 * the pressed state. 4714 * 4715 * @see #setPressed(boolean) 4716 * @see #isClickable() 4717 * @see #setClickable(boolean) 4718 * 4719 * @return true if the view is currently pressed, false otherwise 4720 */ 4721 public boolean isPressed() { 4722 return (mPrivateFlags & PRESSED) == PRESSED; 4723 } 4724 4725 /** 4726 * Indicates whether this view will save its state (that is, 4727 * whether its {@link #onSaveInstanceState} method will be called). 4728 * 4729 * @return Returns true if the view state saving is enabled, else false. 4730 * 4731 * @see #setSaveEnabled(boolean) 4732 * @attr ref android.R.styleable#View_saveEnabled 4733 */ 4734 public boolean isSaveEnabled() { 4735 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 4736 } 4737 4738 /** 4739 * Controls whether the saving of this view's state is 4740 * enabled (that is, whether its {@link #onSaveInstanceState} method 4741 * will be called). Note that even if freezing is enabled, the 4742 * view still must have an id assigned to it (via {@link #setId(int)}) 4743 * for its state to be saved. This flag can only disable the 4744 * saving of this view; any child views may still have their state saved. 4745 * 4746 * @param enabled Set to false to <em>disable</em> state saving, or true 4747 * (the default) to allow it. 4748 * 4749 * @see #isSaveEnabled() 4750 * @see #setId(int) 4751 * @see #onSaveInstanceState() 4752 * @attr ref android.R.styleable#View_saveEnabled 4753 */ 4754 public void setSaveEnabled(boolean enabled) { 4755 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 4756 } 4757 4758 /** 4759 * Gets whether the framework should discard touches when the view's 4760 * window is obscured by another visible window. 4761 * Refer to the {@link View} security documentation for more details. 4762 * 4763 * @return True if touch filtering is enabled. 4764 * 4765 * @see #setFilterTouchesWhenObscured(boolean) 4766 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 4767 */ 4768 @ViewDebug.ExportedProperty 4769 public boolean getFilterTouchesWhenObscured() { 4770 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 4771 } 4772 4773 /** 4774 * Sets whether the framework should discard touches when the view's 4775 * window is obscured by another visible window. 4776 * Refer to the {@link View} security documentation for more details. 4777 * 4778 * @param enabled True if touch filtering should be enabled. 4779 * 4780 * @see #getFilterTouchesWhenObscured 4781 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 4782 */ 4783 public void setFilterTouchesWhenObscured(boolean enabled) { 4784 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED, 4785 FILTER_TOUCHES_WHEN_OBSCURED); 4786 } 4787 4788 /** 4789 * Indicates whether the entire hierarchy under this view will save its 4790 * state when a state saving traversal occurs from its parent. The default 4791 * is true; if false, these views will not be saved unless 4792 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 4793 * 4794 * @return Returns true if the view state saving from parent is enabled, else false. 4795 * 4796 * @see #setSaveFromParentEnabled(boolean) 4797 */ 4798 public boolean isSaveFromParentEnabled() { 4799 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 4800 } 4801 4802 /** 4803 * Controls whether the entire hierarchy under this view will save its 4804 * state when a state saving traversal occurs from its parent. The default 4805 * is true; if false, these views will not be saved unless 4806 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 4807 * 4808 * @param enabled Set to false to <em>disable</em> state saving, or true 4809 * (the default) to allow it. 4810 * 4811 * @see #isSaveFromParentEnabled() 4812 * @see #setId(int) 4813 * @see #onSaveInstanceState() 4814 */ 4815 public void setSaveFromParentEnabled(boolean enabled) { 4816 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 4817 } 4818 4819 4820 /** 4821 * Returns whether this View is able to take focus. 4822 * 4823 * @return True if this view can take focus, or false otherwise. 4824 * @attr ref android.R.styleable#View_focusable 4825 */ 4826 @ViewDebug.ExportedProperty(category = "focus") 4827 public final boolean isFocusable() { 4828 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 4829 } 4830 4831 /** 4832 * When a view is focusable, it may not want to take focus when in touch mode. 4833 * For example, a button would like focus when the user is navigating via a D-pad 4834 * so that the user can click on it, but once the user starts touching the screen, 4835 * the button shouldn't take focus 4836 * @return Whether the view is focusable in touch mode. 4837 * @attr ref android.R.styleable#View_focusableInTouchMode 4838 */ 4839 @ViewDebug.ExportedProperty 4840 public final boolean isFocusableInTouchMode() { 4841 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 4842 } 4843 4844 /** 4845 * Find the nearest view in the specified direction that can take focus. 4846 * This does not actually give focus to that view. 4847 * 4848 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 4849 * 4850 * @return The nearest focusable in the specified direction, or null if none 4851 * can be found. 4852 */ 4853 public View focusSearch(int direction) { 4854 if (mParent != null) { 4855 return mParent.focusSearch(this, direction); 4856 } else { 4857 return null; 4858 } 4859 } 4860 4861 /** 4862 * This method is the last chance for the focused view and its ancestors to 4863 * respond to an arrow key. This is called when the focused view did not 4864 * consume the key internally, nor could the view system find a new view in 4865 * the requested direction to give focus to. 4866 * 4867 * @param focused The currently focused view. 4868 * @param direction The direction focus wants to move. One of FOCUS_UP, 4869 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 4870 * @return True if the this view consumed this unhandled move. 4871 */ 4872 public boolean dispatchUnhandledMove(View focused, int direction) { 4873 return false; 4874 } 4875 4876 /** 4877 * If a user manually specified the next view id for a particular direction, 4878 * use the root to look up the view. 4879 * @param root The root view of the hierarchy containing this view. 4880 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 4881 * or FOCUS_BACKWARD. 4882 * @return The user specified next view, or null if there is none. 4883 */ 4884 View findUserSetNextFocus(View root, int direction) { 4885 switch (direction) { 4886 case FOCUS_LEFT: 4887 if (mNextFocusLeftId == View.NO_ID) return null; 4888 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 4889 case FOCUS_RIGHT: 4890 if (mNextFocusRightId == View.NO_ID) return null; 4891 return findViewInsideOutShouldExist(root, mNextFocusRightId); 4892 case FOCUS_UP: 4893 if (mNextFocusUpId == View.NO_ID) return null; 4894 return findViewInsideOutShouldExist(root, mNextFocusUpId); 4895 case FOCUS_DOWN: 4896 if (mNextFocusDownId == View.NO_ID) return null; 4897 return findViewInsideOutShouldExist(root, mNextFocusDownId); 4898 case FOCUS_FORWARD: 4899 if (mNextFocusForwardId == View.NO_ID) return null; 4900 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 4901 case FOCUS_BACKWARD: { 4902 final int id = mID; 4903 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 4904 @Override 4905 public boolean apply(View t) { 4906 return t.mNextFocusForwardId == id; 4907 } 4908 }); 4909 } 4910 } 4911 return null; 4912 } 4913 4914 private View findViewInsideOutShouldExist(View root, final int childViewId) { 4915 View result = root.findViewByPredicateInsideOut(this, new Predicate<View>() { 4916 @Override 4917 public boolean apply(View t) { 4918 return t.mID == childViewId; 4919 } 4920 }); 4921 4922 if (result == null) { 4923 Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified " 4924 + "by user for id " + childViewId); 4925 } 4926 return result; 4927 } 4928 4929 /** 4930 * Find and return all focusable views that are descendants of this view, 4931 * possibly including this view if it is focusable itself. 4932 * 4933 * @param direction The direction of the focus 4934 * @return A list of focusable views 4935 */ 4936 public ArrayList<View> getFocusables(int direction) { 4937 ArrayList<View> result = new ArrayList<View>(24); 4938 addFocusables(result, direction); 4939 return result; 4940 } 4941 4942 /** 4943 * Add any focusable views that are descendants of this view (possibly 4944 * including this view if it is focusable itself) to views. If we are in touch mode, 4945 * only add views that are also focusable in touch mode. 4946 * 4947 * @param views Focusable views found so far 4948 * @param direction The direction of the focus 4949 */ 4950 public void addFocusables(ArrayList<View> views, int direction) { 4951 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 4952 } 4953 4954 /** 4955 * Adds any focusable views that are descendants of this view (possibly 4956 * including this view if it is focusable itself) to views. This method 4957 * adds all focusable views regardless if we are in touch mode or 4958 * only views focusable in touch mode if we are in touch mode depending on 4959 * the focusable mode paramater. 4960 * 4961 * @param views Focusable views found so far or null if all we are interested is 4962 * the number of focusables. 4963 * @param direction The direction of the focus. 4964 * @param focusableMode The type of focusables to be added. 4965 * 4966 * @see #FOCUSABLES_ALL 4967 * @see #FOCUSABLES_TOUCH_MODE 4968 */ 4969 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { 4970 if (!isFocusable()) { 4971 return; 4972 } 4973 4974 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE && 4975 isInTouchMode() && !isFocusableInTouchMode()) { 4976 return; 4977 } 4978 4979 if (views != null) { 4980 views.add(this); 4981 } 4982 } 4983 4984 /** 4985 * Finds the Views that contain given text. The containment is case insensitive. 4986 * As View's text is considered any text content that View renders. 4987 * 4988 * @param outViews The output list of matching Views. 4989 * @param text The text to match against. 4990 */ 4991 public void findViewsWithText(ArrayList<View> outViews, CharSequence text) { 4992 } 4993 4994 /** 4995 * Find and return all touchable views that are descendants of this view, 4996 * possibly including this view if it is touchable itself. 4997 * 4998 * @return A list of touchable views 4999 */ 5000 public ArrayList<View> getTouchables() { 5001 ArrayList<View> result = new ArrayList<View>(); 5002 addTouchables(result); 5003 return result; 5004 } 5005 5006 /** 5007 * Add any touchable views that are descendants of this view (possibly 5008 * including this view if it is touchable itself) to views. 5009 * 5010 * @param views Touchable views found so far 5011 */ 5012 public void addTouchables(ArrayList<View> views) { 5013 final int viewFlags = mViewFlags; 5014 5015 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 5016 && (viewFlags & ENABLED_MASK) == ENABLED) { 5017 views.add(this); 5018 } 5019 } 5020 5021 /** 5022 * Call this to try to give focus to a specific view or to one of its 5023 * descendants. 5024 * 5025 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 5026 * false), or if it is focusable and it is not focusable in touch mode 5027 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 5028 * 5029 * See also {@link #focusSearch(int)}, which is what you call to say that you 5030 * have focus, and you want your parent to look for the next one. 5031 * 5032 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 5033 * {@link #FOCUS_DOWN} and <code>null</code>. 5034 * 5035 * @return Whether this view or one of its descendants actually took focus. 5036 */ 5037 public final boolean requestFocus() { 5038 return requestFocus(View.FOCUS_DOWN); 5039 } 5040 5041 5042 /** 5043 * Call this to try to give focus to a specific view or to one of its 5044 * descendants and give it a hint about what direction focus is heading. 5045 * 5046 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 5047 * false), or if it is focusable and it is not focusable in touch mode 5048 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 5049 * 5050 * See also {@link #focusSearch(int)}, which is what you call to say that you 5051 * have focus, and you want your parent to look for the next one. 5052 * 5053 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 5054 * <code>null</code> set for the previously focused rectangle. 5055 * 5056 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 5057 * @return Whether this view or one of its descendants actually took focus. 5058 */ 5059 public final boolean requestFocus(int direction) { 5060 return requestFocus(direction, null); 5061 } 5062 5063 /** 5064 * Call this to try to give focus to a specific view or to one of its descendants 5065 * and give it hints about the direction and a specific rectangle that the focus 5066 * is coming from. The rectangle can help give larger views a finer grained hint 5067 * about where focus is coming from, and therefore, where to show selection, or 5068 * forward focus change internally. 5069 * 5070 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 5071 * false), or if it is focusable and it is not focusable in touch mode 5072 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 5073 * 5074 * A View will not take focus if it is not visible. 5075 * 5076 * A View will not take focus if one of its parents has 5077 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 5078 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 5079 * 5080 * See also {@link #focusSearch(int)}, which is what you call to say that you 5081 * have focus, and you want your parent to look for the next one. 5082 * 5083 * You may wish to override this method if your custom {@link View} has an internal 5084 * {@link View} that it wishes to forward the request to. 5085 * 5086 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 5087 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 5088 * to give a finer grained hint about where focus is coming from. May be null 5089 * if there is no hint. 5090 * @return Whether this view or one of its descendants actually took focus. 5091 */ 5092 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 5093 // need to be focusable 5094 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 5095 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 5096 return false; 5097 } 5098 5099 // need to be focusable in touch mode if in touch mode 5100 if (isInTouchMode() && 5101 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 5102 return false; 5103 } 5104 5105 // need to not have any parents blocking us 5106 if (hasAncestorThatBlocksDescendantFocus()) { 5107 return false; 5108 } 5109 5110 handleFocusGainInternal(direction, previouslyFocusedRect); 5111 return true; 5112 } 5113 5114 /** Gets the ViewAncestor, or null if not attached. */ 5115 /*package*/ ViewRootImpl getViewRootImpl() { 5116 View root = getRootView(); 5117 return root != null ? (ViewRootImpl)root.getParent() : null; 5118 } 5119 5120 /** 5121 * Call this to try to give focus to a specific view or to one of its descendants. This is a 5122 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 5123 * touch mode to request focus when they are touched. 5124 * 5125 * @return Whether this view or one of its descendants actually took focus. 5126 * 5127 * @see #isInTouchMode() 5128 * 5129 */ 5130 public final boolean requestFocusFromTouch() { 5131 // Leave touch mode if we need to 5132 if (isInTouchMode()) { 5133 ViewRootImpl viewRoot = getViewRootImpl(); 5134 if (viewRoot != null) { 5135 viewRoot.ensureTouchMode(false); 5136 } 5137 } 5138 return requestFocus(View.FOCUS_DOWN); 5139 } 5140 5141 /** 5142 * @return Whether any ancestor of this view blocks descendant focus. 5143 */ 5144 private boolean hasAncestorThatBlocksDescendantFocus() { 5145 ViewParent ancestor = mParent; 5146 while (ancestor instanceof ViewGroup) { 5147 final ViewGroup vgAncestor = (ViewGroup) ancestor; 5148 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) { 5149 return true; 5150 } else { 5151 ancestor = vgAncestor.getParent(); 5152 } 5153 } 5154 return false; 5155 } 5156 5157 /** 5158 * @hide 5159 */ 5160 public void dispatchStartTemporaryDetach() { 5161 onStartTemporaryDetach(); 5162 } 5163 5164 /** 5165 * This is called when a container is going to temporarily detach a child, with 5166 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 5167 * It will either be followed by {@link #onFinishTemporaryDetach()} or 5168 * {@link #onDetachedFromWindow()} when the container is done. 5169 */ 5170 public void onStartTemporaryDetach() { 5171 removeUnsetPressCallback(); 5172 mPrivateFlags |= CANCEL_NEXT_UP_EVENT; 5173 } 5174 5175 /** 5176 * @hide 5177 */ 5178 public void dispatchFinishTemporaryDetach() { 5179 onFinishTemporaryDetach(); 5180 } 5181 5182 /** 5183 * Called after {@link #onStartTemporaryDetach} when the container is done 5184 * changing the view. 5185 */ 5186 public void onFinishTemporaryDetach() { 5187 } 5188 5189 /** 5190 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 5191 * for this view's window. Returns null if the view is not currently attached 5192 * to the window. Normally you will not need to use this directly, but 5193 * just use the standard high-level event callbacks like 5194 * {@link #onKeyDown(int, KeyEvent)}. 5195 */ 5196 public KeyEvent.DispatcherState getKeyDispatcherState() { 5197 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 5198 } 5199 5200 /** 5201 * Dispatch a key event before it is processed by any input method 5202 * associated with the view hierarchy. This can be used to intercept 5203 * key events in special situations before the IME consumes them; a 5204 * typical example would be handling the BACK key to update the application's 5205 * UI instead of allowing the IME to see it and close itself. 5206 * 5207 * @param event The key event to be dispatched. 5208 * @return True if the event was handled, false otherwise. 5209 */ 5210 public boolean dispatchKeyEventPreIme(KeyEvent event) { 5211 return onKeyPreIme(event.getKeyCode(), event); 5212 } 5213 5214 /** 5215 * Dispatch a key event to the next view on the focus path. This path runs 5216 * from the top of the view tree down to the currently focused view. If this 5217 * view has focus, it will dispatch to itself. Otherwise it will dispatch 5218 * the next node down the focus path. This method also fires any key 5219 * listeners. 5220 * 5221 * @param event The key event to be dispatched. 5222 * @return True if the event was handled, false otherwise. 5223 */ 5224 public boolean dispatchKeyEvent(KeyEvent event) { 5225 if (mInputEventConsistencyVerifier != null) { 5226 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 5227 } 5228 5229 // Give any attached key listener a first crack at the event. 5230 //noinspection SimplifiableIfStatement 5231 if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 5232 && mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 5233 return true; 5234 } 5235 5236 if (event.dispatch(this, mAttachInfo != null 5237 ? mAttachInfo.mKeyDispatchState : null, this)) { 5238 return true; 5239 } 5240 5241 if (mInputEventConsistencyVerifier != null) { 5242 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5243 } 5244 return false; 5245 } 5246 5247 /** 5248 * Dispatches a key shortcut event. 5249 * 5250 * @param event The key event to be dispatched. 5251 * @return True if the event was handled by the view, false otherwise. 5252 */ 5253 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 5254 return onKeyShortcut(event.getKeyCode(), event); 5255 } 5256 5257 /** 5258 * Pass the touch screen motion event down to the target view, or this 5259 * view if it is the target. 5260 * 5261 * @param event The motion event to be dispatched. 5262 * @return True if the event was handled by the view, false otherwise. 5263 */ 5264 public boolean dispatchTouchEvent(MotionEvent event) { 5265 if (mInputEventConsistencyVerifier != null) { 5266 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 5267 } 5268 5269 if (onFilterTouchEventForSecurity(event)) { 5270 //noinspection SimplifiableIfStatement 5271 if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED && 5272 mOnTouchListener.onTouch(this, event)) { 5273 return true; 5274 } 5275 5276 if (onTouchEvent(event)) { 5277 return true; 5278 } 5279 } 5280 5281 if (mInputEventConsistencyVerifier != null) { 5282 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5283 } 5284 return false; 5285 } 5286 5287 /** 5288 * Filter the touch event to apply security policies. 5289 * 5290 * @param event The motion event to be filtered. 5291 * @return True if the event should be dispatched, false if the event should be dropped. 5292 * 5293 * @see #getFilterTouchesWhenObscured 5294 */ 5295 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 5296 //noinspection RedundantIfStatement 5297 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 5298 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 5299 // Window is obscured, drop this touch. 5300 return false; 5301 } 5302 return true; 5303 } 5304 5305 /** 5306 * Pass a trackball motion event down to the focused view. 5307 * 5308 * @param event The motion event to be dispatched. 5309 * @return True if the event was handled by the view, false otherwise. 5310 */ 5311 public boolean dispatchTrackballEvent(MotionEvent event) { 5312 if (mInputEventConsistencyVerifier != null) { 5313 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 5314 } 5315 5316 return onTrackballEvent(event); 5317 } 5318 5319 /** 5320 * Dispatch a generic motion event. 5321 * <p> 5322 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 5323 * are delivered to the view under the pointer. All other generic motion events are 5324 * delivered to the focused view. Hover events are handled specially and are delivered 5325 * to {@link #onHoverEvent(MotionEvent)}. 5326 * </p> 5327 * 5328 * @param event The motion event to be dispatched. 5329 * @return True if the event was handled by the view, false otherwise. 5330 */ 5331 public boolean dispatchGenericMotionEvent(MotionEvent event) { 5332 if (mInputEventConsistencyVerifier != null) { 5333 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 5334 } 5335 5336 final int source = event.getSource(); 5337 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 5338 final int action = event.getAction(); 5339 if (action == MotionEvent.ACTION_HOVER_ENTER 5340 || action == MotionEvent.ACTION_HOVER_MOVE 5341 || action == MotionEvent.ACTION_HOVER_EXIT) { 5342 if (dispatchHoverEvent(event)) { 5343 return true; 5344 } 5345 } else if (dispatchGenericPointerEvent(event)) { 5346 return true; 5347 } 5348 } else if (dispatchGenericFocusedEvent(event)) { 5349 return true; 5350 } 5351 5352 if (dispatchGenericMotionEventInternal(event)) { 5353 return true; 5354 } 5355 5356 if (mInputEventConsistencyVerifier != null) { 5357 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5358 } 5359 return false; 5360 } 5361 5362 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 5363 //noinspection SimplifiableIfStatement 5364 if (mOnGenericMotionListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 5365 && mOnGenericMotionListener.onGenericMotion(this, event)) { 5366 return true; 5367 } 5368 5369 if (onGenericMotionEvent(event)) { 5370 return true; 5371 } 5372 5373 if (mInputEventConsistencyVerifier != null) { 5374 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 5375 } 5376 return false; 5377 } 5378 5379 /** 5380 * Dispatch a hover event. 5381 * <p> 5382 * Do not call this method directly. 5383 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 5384 * </p> 5385 * 5386 * @param event The motion event to be dispatched. 5387 * @return True if the event was handled by the view, false otherwise. 5388 */ 5389 protected boolean dispatchHoverEvent(MotionEvent event) { 5390 //noinspection SimplifiableIfStatement 5391 if (mOnHoverListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 5392 && mOnHoverListener.onHover(this, event)) { 5393 return true; 5394 } 5395 5396 return onHoverEvent(event); 5397 } 5398 5399 /** 5400 * Returns true if the view has a child to which it has recently sent 5401 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 5402 * it does not have a hovered child, then it must be the innermost hovered view. 5403 * @hide 5404 */ 5405 protected boolean hasHoveredChild() { 5406 return false; 5407 } 5408 5409 /** 5410 * Dispatch a generic motion event to the view under the first pointer. 5411 * <p> 5412 * Do not call this method directly. 5413 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 5414 * </p> 5415 * 5416 * @param event The motion event to be dispatched. 5417 * @return True if the event was handled by the view, false otherwise. 5418 */ 5419 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 5420 return false; 5421 } 5422 5423 /** 5424 * Dispatch a generic motion event to the currently focused view. 5425 * <p> 5426 * Do not call this method directly. 5427 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 5428 * </p> 5429 * 5430 * @param event The motion event to be dispatched. 5431 * @return True if the event was handled by the view, false otherwise. 5432 */ 5433 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 5434 return false; 5435 } 5436 5437 /** 5438 * Dispatch a pointer event. 5439 * <p> 5440 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 5441 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 5442 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 5443 * and should not be expected to handle other pointing device features. 5444 * </p> 5445 * 5446 * @param event The motion event to be dispatched. 5447 * @return True if the event was handled by the view, false otherwise. 5448 * @hide 5449 */ 5450 public final boolean dispatchPointerEvent(MotionEvent event) { 5451 if (event.isTouchEvent()) { 5452 return dispatchTouchEvent(event); 5453 } else { 5454 return dispatchGenericMotionEvent(event); 5455 } 5456 } 5457 5458 /** 5459 * Called when the window containing this view gains or loses window focus. 5460 * ViewGroups should override to route to their children. 5461 * 5462 * @param hasFocus True if the window containing this view now has focus, 5463 * false otherwise. 5464 */ 5465 public void dispatchWindowFocusChanged(boolean hasFocus) { 5466 onWindowFocusChanged(hasFocus); 5467 } 5468 5469 /** 5470 * Called when the window containing this view gains or loses focus. Note 5471 * that this is separate from view focus: to receive key events, both 5472 * your view and its window must have focus. If a window is displayed 5473 * on top of yours that takes input focus, then your own window will lose 5474 * focus but the view focus will remain unchanged. 5475 * 5476 * @param hasWindowFocus True if the window containing this view now has 5477 * focus, false otherwise. 5478 */ 5479 public void onWindowFocusChanged(boolean hasWindowFocus) { 5480 InputMethodManager imm = InputMethodManager.peekInstance(); 5481 if (!hasWindowFocus) { 5482 if (isPressed()) { 5483 setPressed(false); 5484 } 5485 if (imm != null && (mPrivateFlags & FOCUSED) != 0) { 5486 imm.focusOut(this); 5487 } 5488 removeLongPressCallback(); 5489 removeTapCallback(); 5490 onFocusLost(); 5491 } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) { 5492 imm.focusIn(this); 5493 } 5494 refreshDrawableState(); 5495 } 5496 5497 /** 5498 * Returns true if this view is in a window that currently has window focus. 5499 * Note that this is not the same as the view itself having focus. 5500 * 5501 * @return True if this view is in a window that currently has window focus. 5502 */ 5503 public boolean hasWindowFocus() { 5504 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 5505 } 5506 5507 /** 5508 * Dispatch a view visibility change down the view hierarchy. 5509 * ViewGroups should override to route to their children. 5510 * @param changedView The view whose visibility changed. Could be 'this' or 5511 * an ancestor view. 5512 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 5513 * {@link #INVISIBLE} or {@link #GONE}. 5514 */ 5515 protected void dispatchVisibilityChanged(View changedView, int visibility) { 5516 onVisibilityChanged(changedView, visibility); 5517 } 5518 5519 /** 5520 * Called when the visibility of the view or an ancestor of the view is changed. 5521 * @param changedView The view whose visibility changed. Could be 'this' or 5522 * an ancestor view. 5523 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 5524 * {@link #INVISIBLE} or {@link #GONE}. 5525 */ 5526 protected void onVisibilityChanged(View changedView, int visibility) { 5527 if (visibility == VISIBLE) { 5528 if (mAttachInfo != null) { 5529 initialAwakenScrollBars(); 5530 } else { 5531 mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH; 5532 } 5533 } 5534 } 5535 5536 /** 5537 * Dispatch a hint about whether this view is displayed. For instance, when 5538 * a View moves out of the screen, it might receives a display hint indicating 5539 * the view is not displayed. Applications should not <em>rely</em> on this hint 5540 * as there is no guarantee that they will receive one. 5541 * 5542 * @param hint A hint about whether or not this view is displayed: 5543 * {@link #VISIBLE} or {@link #INVISIBLE}. 5544 */ 5545 public void dispatchDisplayHint(int hint) { 5546 onDisplayHint(hint); 5547 } 5548 5549 /** 5550 * Gives this view a hint about whether is displayed or not. For instance, when 5551 * a View moves out of the screen, it might receives a display hint indicating 5552 * the view is not displayed. Applications should not <em>rely</em> on this hint 5553 * as there is no guarantee that they will receive one. 5554 * 5555 * @param hint A hint about whether or not this view is displayed: 5556 * {@link #VISIBLE} or {@link #INVISIBLE}. 5557 */ 5558 protected void onDisplayHint(int hint) { 5559 } 5560 5561 /** 5562 * Dispatch a window visibility change down the view hierarchy. 5563 * ViewGroups should override to route to their children. 5564 * 5565 * @param visibility The new visibility of the window. 5566 * 5567 * @see #onWindowVisibilityChanged(int) 5568 */ 5569 public void dispatchWindowVisibilityChanged(int visibility) { 5570 onWindowVisibilityChanged(visibility); 5571 } 5572 5573 /** 5574 * Called when the window containing has change its visibility 5575 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 5576 * that this tells you whether or not your window is being made visible 5577 * to the window manager; this does <em>not</em> tell you whether or not 5578 * your window is obscured by other windows on the screen, even if it 5579 * is itself visible. 5580 * 5581 * @param visibility The new visibility of the window. 5582 */ 5583 protected void onWindowVisibilityChanged(int visibility) { 5584 if (visibility == VISIBLE) { 5585 initialAwakenScrollBars(); 5586 } 5587 } 5588 5589 /** 5590 * Returns the current visibility of the window this view is attached to 5591 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 5592 * 5593 * @return Returns the current visibility of the view's window. 5594 */ 5595 public int getWindowVisibility() { 5596 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 5597 } 5598 5599 /** 5600 * Retrieve the overall visible display size in which the window this view is 5601 * attached to has been positioned in. This takes into account screen 5602 * decorations above the window, for both cases where the window itself 5603 * is being position inside of them or the window is being placed under 5604 * then and covered insets are used for the window to position its content 5605 * inside. In effect, this tells you the available area where content can 5606 * be placed and remain visible to users. 5607 * 5608 * <p>This function requires an IPC back to the window manager to retrieve 5609 * the requested information, so should not be used in performance critical 5610 * code like drawing. 5611 * 5612 * @param outRect Filled in with the visible display frame. If the view 5613 * is not attached to a window, this is simply the raw display size. 5614 */ 5615 public void getWindowVisibleDisplayFrame(Rect outRect) { 5616 if (mAttachInfo != null) { 5617 try { 5618 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 5619 } catch (RemoteException e) { 5620 return; 5621 } 5622 // XXX This is really broken, and probably all needs to be done 5623 // in the window manager, and we need to know more about whether 5624 // we want the area behind or in front of the IME. 5625 final Rect insets = mAttachInfo.mVisibleInsets; 5626 outRect.left += insets.left; 5627 outRect.top += insets.top; 5628 outRect.right -= insets.right; 5629 outRect.bottom -= insets.bottom; 5630 return; 5631 } 5632 Display d = WindowManagerImpl.getDefault().getDefaultDisplay(); 5633 d.getRectSize(outRect); 5634 } 5635 5636 /** 5637 * Dispatch a notification about a resource configuration change down 5638 * the view hierarchy. 5639 * ViewGroups should override to route to their children. 5640 * 5641 * @param newConfig The new resource configuration. 5642 * 5643 * @see #onConfigurationChanged(android.content.res.Configuration) 5644 */ 5645 public void dispatchConfigurationChanged(Configuration newConfig) { 5646 onConfigurationChanged(newConfig); 5647 } 5648 5649 /** 5650 * Called when the current configuration of the resources being used 5651 * by the application have changed. You can use this to decide when 5652 * to reload resources that can changed based on orientation and other 5653 * configuration characterstics. You only need to use this if you are 5654 * not relying on the normal {@link android.app.Activity} mechanism of 5655 * recreating the activity instance upon a configuration change. 5656 * 5657 * @param newConfig The new resource configuration. 5658 */ 5659 protected void onConfigurationChanged(Configuration newConfig) { 5660 } 5661 5662 /** 5663 * Private function to aggregate all per-view attributes in to the view 5664 * root. 5665 */ 5666 void dispatchCollectViewAttributes(int visibility) { 5667 performCollectViewAttributes(visibility); 5668 } 5669 5670 void performCollectViewAttributes(int visibility) { 5671 if ((visibility & VISIBILITY_MASK) == VISIBLE && mAttachInfo != null) { 5672 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 5673 mAttachInfo.mKeepScreenOn = true; 5674 } 5675 mAttachInfo.mSystemUiVisibility |= mSystemUiVisibility; 5676 if (mOnSystemUiVisibilityChangeListener != null) { 5677 mAttachInfo.mHasSystemUiListeners = true; 5678 } 5679 } 5680 } 5681 5682 void needGlobalAttributesUpdate(boolean force) { 5683 final AttachInfo ai = mAttachInfo; 5684 if (ai != null) { 5685 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 5686 || ai.mHasSystemUiListeners) { 5687 ai.mRecomputeGlobalAttributes = true; 5688 } 5689 } 5690 } 5691 5692 /** 5693 * Returns whether the device is currently in touch mode. Touch mode is entered 5694 * once the user begins interacting with the device by touch, and affects various 5695 * things like whether focus is always visible to the user. 5696 * 5697 * @return Whether the device is in touch mode. 5698 */ 5699 @ViewDebug.ExportedProperty 5700 public boolean isInTouchMode() { 5701 if (mAttachInfo != null) { 5702 return mAttachInfo.mInTouchMode; 5703 } else { 5704 return ViewRootImpl.isInTouchMode(); 5705 } 5706 } 5707 5708 /** 5709 * Returns the context the view is running in, through which it can 5710 * access the current theme, resources, etc. 5711 * 5712 * @return The view's Context. 5713 */ 5714 @ViewDebug.CapturedViewProperty 5715 public final Context getContext() { 5716 return mContext; 5717 } 5718 5719 /** 5720 * Handle a key event before it is processed by any input method 5721 * associated with the view hierarchy. This can be used to intercept 5722 * key events in special situations before the IME consumes them; a 5723 * typical example would be handling the BACK key to update the application's 5724 * UI instead of allowing the IME to see it and close itself. 5725 * 5726 * @param keyCode The value in event.getKeyCode(). 5727 * @param event Description of the key event. 5728 * @return If you handled the event, return true. If you want to allow the 5729 * event to be handled by the next receiver, return false. 5730 */ 5731 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 5732 return false; 5733 } 5734 5735 /** 5736 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 5737 * KeyEvent.Callback.onKeyDown()}: perform press of the view 5738 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 5739 * is released, if the view is enabled and clickable. 5740 * 5741 * @param keyCode A key code that represents the button pressed, from 5742 * {@link android.view.KeyEvent}. 5743 * @param event The KeyEvent object that defines the button action. 5744 */ 5745 public boolean onKeyDown(int keyCode, KeyEvent event) { 5746 boolean result = false; 5747 5748 switch (keyCode) { 5749 case KeyEvent.KEYCODE_DPAD_CENTER: 5750 case KeyEvent.KEYCODE_ENTER: { 5751 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 5752 return true; 5753 } 5754 // Long clickable items don't necessarily have to be clickable 5755 if (((mViewFlags & CLICKABLE) == CLICKABLE || 5756 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 5757 (event.getRepeatCount() == 0)) { 5758 setPressed(true); 5759 checkForLongClick(0); 5760 return true; 5761 } 5762 break; 5763 } 5764 } 5765 return result; 5766 } 5767 5768 /** 5769 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 5770 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 5771 * the event). 5772 */ 5773 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 5774 return false; 5775 } 5776 5777 /** 5778 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 5779 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 5780 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 5781 * {@link KeyEvent#KEYCODE_ENTER} is released. 5782 * 5783 * @param keyCode A key code that represents the button pressed, from 5784 * {@link android.view.KeyEvent}. 5785 * @param event The KeyEvent object that defines the button action. 5786 */ 5787 public boolean onKeyUp(int keyCode, KeyEvent event) { 5788 boolean result = false; 5789 5790 switch (keyCode) { 5791 case KeyEvent.KEYCODE_DPAD_CENTER: 5792 case KeyEvent.KEYCODE_ENTER: { 5793 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 5794 return true; 5795 } 5796 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 5797 setPressed(false); 5798 5799 if (!mHasPerformedLongPress) { 5800 // This is a tap, so remove the longpress check 5801 removeLongPressCallback(); 5802 5803 result = performClick(); 5804 } 5805 } 5806 break; 5807 } 5808 } 5809 return result; 5810 } 5811 5812 /** 5813 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 5814 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 5815 * the event). 5816 * 5817 * @param keyCode A key code that represents the button pressed, from 5818 * {@link android.view.KeyEvent}. 5819 * @param repeatCount The number of times the action was made. 5820 * @param event The KeyEvent object that defines the button action. 5821 */ 5822 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 5823 return false; 5824 } 5825 5826 /** 5827 * Called on the focused view when a key shortcut event is not handled. 5828 * Override this method to implement local key shortcuts for the View. 5829 * Key shortcuts can also be implemented by setting the 5830 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 5831 * 5832 * @param keyCode The value in event.getKeyCode(). 5833 * @param event Description of the key event. 5834 * @return If you handled the event, return true. If you want to allow the 5835 * event to be handled by the next receiver, return false. 5836 */ 5837 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 5838 return false; 5839 } 5840 5841 /** 5842 * Check whether the called view is a text editor, in which case it 5843 * would make sense to automatically display a soft input window for 5844 * it. Subclasses should override this if they implement 5845 * {@link #onCreateInputConnection(EditorInfo)} to return true if 5846 * a call on that method would return a non-null InputConnection, and 5847 * they are really a first-class editor that the user would normally 5848 * start typing on when the go into a window containing your view. 5849 * 5850 * <p>The default implementation always returns false. This does 5851 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 5852 * will not be called or the user can not otherwise perform edits on your 5853 * view; it is just a hint to the system that this is not the primary 5854 * purpose of this view. 5855 * 5856 * @return Returns true if this view is a text editor, else false. 5857 */ 5858 public boolean onCheckIsTextEditor() { 5859 return false; 5860 } 5861 5862 /** 5863 * Create a new InputConnection for an InputMethod to interact 5864 * with the view. The default implementation returns null, since it doesn't 5865 * support input methods. You can override this to implement such support. 5866 * This is only needed for views that take focus and text input. 5867 * 5868 * <p>When implementing this, you probably also want to implement 5869 * {@link #onCheckIsTextEditor()} to indicate you will return a 5870 * non-null InputConnection. 5871 * 5872 * @param outAttrs Fill in with attribute information about the connection. 5873 */ 5874 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 5875 return null; 5876 } 5877 5878 /** 5879 * Called by the {@link android.view.inputmethod.InputMethodManager} 5880 * when a view who is not the current 5881 * input connection target is trying to make a call on the manager. The 5882 * default implementation returns false; you can override this to return 5883 * true for certain views if you are performing InputConnection proxying 5884 * to them. 5885 * @param view The View that is making the InputMethodManager call. 5886 * @return Return true to allow the call, false to reject. 5887 */ 5888 public boolean checkInputConnectionProxy(View view) { 5889 return false; 5890 } 5891 5892 /** 5893 * Show the context menu for this view. It is not safe to hold on to the 5894 * menu after returning from this method. 5895 * 5896 * You should normally not overload this method. Overload 5897 * {@link #onCreateContextMenu(ContextMenu)} or define an 5898 * {@link OnCreateContextMenuListener} to add items to the context menu. 5899 * 5900 * @param menu The context menu to populate 5901 */ 5902 public void createContextMenu(ContextMenu menu) { 5903 ContextMenuInfo menuInfo = getContextMenuInfo(); 5904 5905 // Sets the current menu info so all items added to menu will have 5906 // my extra info set. 5907 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 5908 5909 onCreateContextMenu(menu); 5910 if (mOnCreateContextMenuListener != null) { 5911 mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 5912 } 5913 5914 // Clear the extra information so subsequent items that aren't mine don't 5915 // have my extra info. 5916 ((MenuBuilder)menu).setCurrentMenuInfo(null); 5917 5918 if (mParent != null) { 5919 mParent.createContextMenu(menu); 5920 } 5921 } 5922 5923 /** 5924 * Views should implement this if they have extra information to associate 5925 * with the context menu. The return result is supplied as a parameter to 5926 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 5927 * callback. 5928 * 5929 * @return Extra information about the item for which the context menu 5930 * should be shown. This information will vary across different 5931 * subclasses of View. 5932 */ 5933 protected ContextMenuInfo getContextMenuInfo() { 5934 return null; 5935 } 5936 5937 /** 5938 * Views should implement this if the view itself is going to add items to 5939 * the context menu. 5940 * 5941 * @param menu the context menu to populate 5942 */ 5943 protected void onCreateContextMenu(ContextMenu menu) { 5944 } 5945 5946 /** 5947 * Implement this method to handle trackball motion events. The 5948 * <em>relative</em> movement of the trackball since the last event 5949 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 5950 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 5951 * that a movement of 1 corresponds to the user pressing one DPAD key (so 5952 * they will often be fractional values, representing the more fine-grained 5953 * movement information available from a trackball). 5954 * 5955 * @param event The motion event. 5956 * @return True if the event was handled, false otherwise. 5957 */ 5958 public boolean onTrackballEvent(MotionEvent event) { 5959 return false; 5960 } 5961 5962 /** 5963 * Implement this method to handle generic motion events. 5964 * <p> 5965 * Generic motion events describe joystick movements, mouse hovers, track pad 5966 * touches, scroll wheel movements and other input events. The 5967 * {@link MotionEvent#getSource() source} of the motion event specifies 5968 * the class of input that was received. Implementations of this method 5969 * must examine the bits in the source before processing the event. 5970 * The following code example shows how this is done. 5971 * </p><p> 5972 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 5973 * are delivered to the view under the pointer. All other generic motion events are 5974 * delivered to the focused view. 5975 * </p> 5976 * <code> 5977 * public boolean onGenericMotionEvent(MotionEvent event) { 5978 * if ((event.getSource() & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) { 5979 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 5980 * // process the joystick movement... 5981 * return true; 5982 * } 5983 * } 5984 * if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) { 5985 * switch (event.getAction()) { 5986 * case MotionEvent.ACTION_HOVER_MOVE: 5987 * // process the mouse hover movement... 5988 * return true; 5989 * case MotionEvent.ACTION_SCROLL: 5990 * // process the scroll wheel movement... 5991 * return true; 5992 * } 5993 * } 5994 * return super.onGenericMotionEvent(event); 5995 * } 5996 * </code> 5997 * 5998 * @param event The generic motion event being processed. 5999 * @return True if the event was handled, false otherwise. 6000 */ 6001 public boolean onGenericMotionEvent(MotionEvent event) { 6002 return false; 6003 } 6004 6005 /** 6006 * Implement this method to handle hover events. 6007 * <p> 6008 * This method is called whenever a pointer is hovering into, over, or out of the 6009 * bounds of a view and the view is not currently being touched. 6010 * Hover events are represented as pointer events with action 6011 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 6012 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 6013 * </p> 6014 * <ul> 6015 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 6016 * when the pointer enters the bounds of the view.</li> 6017 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 6018 * when the pointer has already entered the bounds of the view and has moved.</li> 6019 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 6020 * when the pointer has exited the bounds of the view or when the pointer is 6021 * about to go down due to a button click, tap, or similar user action that 6022 * causes the view to be touched.</li> 6023 * </ul> 6024 * <p> 6025 * The view should implement this method to return true to indicate that it is 6026 * handling the hover event, such as by changing its drawable state. 6027 * </p><p> 6028 * The default implementation calls {@link #setHovered} to update the hovered state 6029 * of the view when a hover enter or hover exit event is received, if the view 6030 * is enabled and is clickable. The default implementation also sends hover 6031 * accessibility events. 6032 * </p> 6033 * 6034 * @param event The motion event that describes the hover. 6035 * @return True if the view handled the hover event. 6036 * 6037 * @see #isHovered 6038 * @see #setHovered 6039 * @see #onHoverChanged 6040 */ 6041 public boolean onHoverEvent(MotionEvent event) { 6042 // The root view may receive hover (or touch) events that are outside the bounds of 6043 // the window. This code ensures that we only send accessibility events for 6044 // hovers that are actually within the bounds of the root view. 6045 final int action = event.getAction(); 6046 if (!mSendingHoverAccessibilityEvents) { 6047 if ((action == MotionEvent.ACTION_HOVER_ENTER 6048 || action == MotionEvent.ACTION_HOVER_MOVE) 6049 && !hasHoveredChild() 6050 && pointInView(event.getX(), event.getY())) { 6051 mSendingHoverAccessibilityEvents = true; 6052 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 6053 } 6054 } else { 6055 if (action == MotionEvent.ACTION_HOVER_EXIT 6056 || (action == MotionEvent.ACTION_HOVER_MOVE 6057 && !pointInView(event.getX(), event.getY()))) { 6058 mSendingHoverAccessibilityEvents = false; 6059 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 6060 } 6061 } 6062 6063 if (isHoverable()) { 6064 switch (action) { 6065 case MotionEvent.ACTION_HOVER_ENTER: 6066 setHovered(true); 6067 break; 6068 case MotionEvent.ACTION_HOVER_EXIT: 6069 setHovered(false); 6070 break; 6071 } 6072 6073 // Dispatch the event to onGenericMotionEvent before returning true. 6074 // This is to provide compatibility with existing applications that 6075 // handled HOVER_MOVE events in onGenericMotionEvent and that would 6076 // break because of the new default handling for hoverable views 6077 // in onHoverEvent. 6078 // Note that onGenericMotionEvent will be called by default when 6079 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 6080 dispatchGenericMotionEventInternal(event); 6081 return true; 6082 } 6083 return false; 6084 } 6085 6086 /** 6087 * Returns true if the view should handle {@link #onHoverEvent} 6088 * by calling {@link #setHovered} to change its hovered state. 6089 * 6090 * @return True if the view is hoverable. 6091 */ 6092 private boolean isHoverable() { 6093 final int viewFlags = mViewFlags; 6094 //noinspection SimplifiableIfStatement 6095 if ((viewFlags & ENABLED_MASK) == DISABLED) { 6096 return false; 6097 } 6098 6099 return (viewFlags & CLICKABLE) == CLICKABLE 6100 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 6101 } 6102 6103 /** 6104 * Returns true if the view is currently hovered. 6105 * 6106 * @return True if the view is currently hovered. 6107 * 6108 * @see #setHovered 6109 * @see #onHoverChanged 6110 */ 6111 @ViewDebug.ExportedProperty 6112 public boolean isHovered() { 6113 return (mPrivateFlags & HOVERED) != 0; 6114 } 6115 6116 /** 6117 * Sets whether the view is currently hovered. 6118 * <p> 6119 * Calling this method also changes the drawable state of the view. This 6120 * enables the view to react to hover by using different drawable resources 6121 * to change its appearance. 6122 * </p><p> 6123 * The {@link #onHoverChanged} method is called when the hovered state changes. 6124 * </p> 6125 * 6126 * @param hovered True if the view is hovered. 6127 * 6128 * @see #isHovered 6129 * @see #onHoverChanged 6130 */ 6131 public void setHovered(boolean hovered) { 6132 if (hovered) { 6133 if ((mPrivateFlags & HOVERED) == 0) { 6134 mPrivateFlags |= HOVERED; 6135 refreshDrawableState(); 6136 onHoverChanged(true); 6137 } 6138 } else { 6139 if ((mPrivateFlags & HOVERED) != 0) { 6140 mPrivateFlags &= ~HOVERED; 6141 refreshDrawableState(); 6142 onHoverChanged(false); 6143 } 6144 } 6145 } 6146 6147 /** 6148 * Implement this method to handle hover state changes. 6149 * <p> 6150 * This method is called whenever the hover state changes as a result of a 6151 * call to {@link #setHovered}. 6152 * </p> 6153 * 6154 * @param hovered The current hover state, as returned by {@link #isHovered}. 6155 * 6156 * @see #isHovered 6157 * @see #setHovered 6158 */ 6159 public void onHoverChanged(boolean hovered) { 6160 } 6161 6162 /** 6163 * Implement this method to handle touch screen motion events. 6164 * 6165 * @param event The motion event. 6166 * @return True if the event was handled, false otherwise. 6167 */ 6168 public boolean onTouchEvent(MotionEvent event) { 6169 final int viewFlags = mViewFlags; 6170 6171 if ((viewFlags & ENABLED_MASK) == DISABLED) { 6172 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) { 6173 mPrivateFlags &= ~PRESSED; 6174 refreshDrawableState(); 6175 } 6176 // A disabled view that is clickable still consumes the touch 6177 // events, it just doesn't respond to them. 6178 return (((viewFlags & CLICKABLE) == CLICKABLE || 6179 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 6180 } 6181 6182 if (mTouchDelegate != null) { 6183 if (mTouchDelegate.onTouchEvent(event)) { 6184 return true; 6185 } 6186 } 6187 6188 if (((viewFlags & CLICKABLE) == CLICKABLE || 6189 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 6190 switch (event.getAction()) { 6191 case MotionEvent.ACTION_UP: 6192 boolean prepressed = (mPrivateFlags & PREPRESSED) != 0; 6193 if ((mPrivateFlags & PRESSED) != 0 || prepressed) { 6194 // take focus if we don't have it already and we should in 6195 // touch mode. 6196 boolean focusTaken = false; 6197 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 6198 focusTaken = requestFocus(); 6199 } 6200 6201 if (prepressed) { 6202 // The button is being released before we actually 6203 // showed it as pressed. Make it show the pressed 6204 // state now (before scheduling the click) to ensure 6205 // the user sees it. 6206 mPrivateFlags |= PRESSED; 6207 refreshDrawableState(); 6208 } 6209 6210 if (!mHasPerformedLongPress) { 6211 // This is a tap, so remove the longpress check 6212 removeLongPressCallback(); 6213 6214 // Only perform take click actions if we were in the pressed state 6215 if (!focusTaken) { 6216 // Use a Runnable and post this rather than calling 6217 // performClick directly. This lets other visual state 6218 // of the view update before click actions start. 6219 if (mPerformClick == null) { 6220 mPerformClick = new PerformClick(); 6221 } 6222 if (!post(mPerformClick)) { 6223 performClick(); 6224 } 6225 } 6226 } 6227 6228 if (mUnsetPressedState == null) { 6229 mUnsetPressedState = new UnsetPressedState(); 6230 } 6231 6232 if (prepressed) { 6233 postDelayed(mUnsetPressedState, 6234 ViewConfiguration.getPressedStateDuration()); 6235 } else if (!post(mUnsetPressedState)) { 6236 // If the post failed, unpress right now 6237 mUnsetPressedState.run(); 6238 } 6239 removeTapCallback(); 6240 } 6241 break; 6242 6243 case MotionEvent.ACTION_DOWN: 6244 mHasPerformedLongPress = false; 6245 6246 if (performButtonActionOnTouchDown(event)) { 6247 break; 6248 } 6249 6250 // Walk up the hierarchy to determine if we're inside a scrolling container. 6251 boolean isInScrollingContainer = isInScrollingContainer(); 6252 6253 // For views inside a scrolling container, delay the pressed feedback for 6254 // a short period in case this is a scroll. 6255 if (isInScrollingContainer) { 6256 mPrivateFlags |= PREPRESSED; 6257 if (mPendingCheckForTap == null) { 6258 mPendingCheckForTap = new CheckForTap(); 6259 } 6260 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 6261 } else { 6262 // Not inside a scrolling container, so show the feedback right away 6263 mPrivateFlags |= PRESSED; 6264 refreshDrawableState(); 6265 checkForLongClick(0); 6266 } 6267 break; 6268 6269 case MotionEvent.ACTION_CANCEL: 6270 mPrivateFlags &= ~PRESSED; 6271 refreshDrawableState(); 6272 removeTapCallback(); 6273 break; 6274 6275 case MotionEvent.ACTION_MOVE: 6276 final int x = (int) event.getX(); 6277 final int y = (int) event.getY(); 6278 6279 // Be lenient about moving outside of buttons 6280 if (!pointInView(x, y, mTouchSlop)) { 6281 // Outside button 6282 removeTapCallback(); 6283 if ((mPrivateFlags & PRESSED) != 0) { 6284 // Remove any future long press/tap checks 6285 removeLongPressCallback(); 6286 6287 // Need to switch from pressed to not pressed 6288 mPrivateFlags &= ~PRESSED; 6289 refreshDrawableState(); 6290 } 6291 } 6292 break; 6293 } 6294 return true; 6295 } 6296 6297 return false; 6298 } 6299 6300 /** 6301 * @hide 6302 */ 6303 public boolean isInScrollingContainer() { 6304 ViewParent p = getParent(); 6305 while (p != null && p instanceof ViewGroup) { 6306 if (((ViewGroup) p).shouldDelayChildPressedState()) { 6307 return true; 6308 } 6309 p = p.getParent(); 6310 } 6311 return false; 6312 } 6313 6314 /** 6315 * Remove the longpress detection timer. 6316 */ 6317 private void removeLongPressCallback() { 6318 if (mPendingCheckForLongPress != null) { 6319 removeCallbacks(mPendingCheckForLongPress); 6320 } 6321 } 6322 6323 /** 6324 * Remove the pending click action 6325 */ 6326 private void removePerformClickCallback() { 6327 if (mPerformClick != null) { 6328 removeCallbacks(mPerformClick); 6329 } 6330 } 6331 6332 /** 6333 * Remove the prepress detection timer. 6334 */ 6335 private void removeUnsetPressCallback() { 6336 if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) { 6337 setPressed(false); 6338 removeCallbacks(mUnsetPressedState); 6339 } 6340 } 6341 6342 /** 6343 * Remove the tap detection timer. 6344 */ 6345 private void removeTapCallback() { 6346 if (mPendingCheckForTap != null) { 6347 mPrivateFlags &= ~PREPRESSED; 6348 removeCallbacks(mPendingCheckForTap); 6349 } 6350 } 6351 6352 /** 6353 * Cancels a pending long press. Your subclass can use this if you 6354 * want the context menu to come up if the user presses and holds 6355 * at the same place, but you don't want it to come up if they press 6356 * and then move around enough to cause scrolling. 6357 */ 6358 public void cancelLongPress() { 6359 removeLongPressCallback(); 6360 6361 /* 6362 * The prepressed state handled by the tap callback is a display 6363 * construct, but the tap callback will post a long press callback 6364 * less its own timeout. Remove it here. 6365 */ 6366 removeTapCallback(); 6367 } 6368 6369 /** 6370 * Remove the pending callback for sending a 6371 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 6372 */ 6373 private void removeSendViewScrolledAccessibilityEventCallback() { 6374 if (mSendViewScrolledAccessibilityEvent != null) { 6375 removeCallbacks(mSendViewScrolledAccessibilityEvent); 6376 } 6377 } 6378 6379 /** 6380 * Sets the TouchDelegate for this View. 6381 */ 6382 public void setTouchDelegate(TouchDelegate delegate) { 6383 mTouchDelegate = delegate; 6384 } 6385 6386 /** 6387 * Gets the TouchDelegate for this View. 6388 */ 6389 public TouchDelegate getTouchDelegate() { 6390 return mTouchDelegate; 6391 } 6392 6393 /** 6394 * Set flags controlling behavior of this view. 6395 * 6396 * @param flags Constant indicating the value which should be set 6397 * @param mask Constant indicating the bit range that should be changed 6398 */ 6399 void setFlags(int flags, int mask) { 6400 int old = mViewFlags; 6401 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 6402 6403 int changed = mViewFlags ^ old; 6404 if (changed == 0) { 6405 return; 6406 } 6407 int privateFlags = mPrivateFlags; 6408 6409 /* Check if the FOCUSABLE bit has changed */ 6410 if (((changed & FOCUSABLE_MASK) != 0) && 6411 ((privateFlags & HAS_BOUNDS) !=0)) { 6412 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 6413 && ((privateFlags & FOCUSED) != 0)) { 6414 /* Give up focus if we are no longer focusable */ 6415 clearFocus(); 6416 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 6417 && ((privateFlags & FOCUSED) == 0)) { 6418 /* 6419 * Tell the view system that we are now available to take focus 6420 * if no one else already has it. 6421 */ 6422 if (mParent != null) mParent.focusableViewAvailable(this); 6423 } 6424 } 6425 6426 if ((flags & VISIBILITY_MASK) == VISIBLE) { 6427 if ((changed & VISIBILITY_MASK) != 0) { 6428 /* 6429 * If this view is becoming visible, invalidate it in case it changed while 6430 * it was not visible. Marking it drawn ensures that the invalidation will 6431 * go through. 6432 */ 6433 mPrivateFlags |= DRAWN; 6434 invalidate(true); 6435 6436 needGlobalAttributesUpdate(true); 6437 6438 // a view becoming visible is worth notifying the parent 6439 // about in case nothing has focus. even if this specific view 6440 // isn't focusable, it may contain something that is, so let 6441 // the root view try to give this focus if nothing else does. 6442 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 6443 mParent.focusableViewAvailable(this); 6444 } 6445 } 6446 } 6447 6448 /* Check if the GONE bit has changed */ 6449 if ((changed & GONE) != 0) { 6450 needGlobalAttributesUpdate(false); 6451 requestLayout(); 6452 6453 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 6454 if (hasFocus()) clearFocus(); 6455 destroyDrawingCache(); 6456 if (mParent instanceof View) { 6457 // GONE views noop invalidation, so invalidate the parent 6458 ((View) mParent).invalidate(true); 6459 } 6460 // Mark the view drawn to ensure that it gets invalidated properly the next 6461 // time it is visible and gets invalidated 6462 mPrivateFlags |= DRAWN; 6463 } 6464 if (mAttachInfo != null) { 6465 mAttachInfo.mViewVisibilityChanged = true; 6466 } 6467 } 6468 6469 /* Check if the VISIBLE bit has changed */ 6470 if ((changed & INVISIBLE) != 0) { 6471 needGlobalAttributesUpdate(false); 6472 /* 6473 * If this view is becoming invisible, set the DRAWN flag so that 6474 * the next invalidate() will not be skipped. 6475 */ 6476 mPrivateFlags |= DRAWN; 6477 6478 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) { 6479 // root view becoming invisible shouldn't clear focus 6480 if (getRootView() != this) { 6481 clearFocus(); 6482 } 6483 } 6484 if (mAttachInfo != null) { 6485 mAttachInfo.mViewVisibilityChanged = true; 6486 } 6487 } 6488 6489 if ((changed & VISIBILITY_MASK) != 0) { 6490 if (mParent instanceof ViewGroup) { 6491 ((ViewGroup) mParent).onChildVisibilityChanged(this, (flags & VISIBILITY_MASK)); 6492 ((View) mParent).invalidate(true); 6493 } else if (mParent != null) { 6494 mParent.invalidateChild(this, null); 6495 } 6496 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK)); 6497 } 6498 6499 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 6500 destroyDrawingCache(); 6501 } 6502 6503 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 6504 destroyDrawingCache(); 6505 mPrivateFlags &= ~DRAWING_CACHE_VALID; 6506 invalidateParentCaches(); 6507 } 6508 6509 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 6510 destroyDrawingCache(); 6511 mPrivateFlags &= ~DRAWING_CACHE_VALID; 6512 } 6513 6514 if ((changed & DRAW_MASK) != 0) { 6515 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 6516 if (mBGDrawable != null) { 6517 mPrivateFlags &= ~SKIP_DRAW; 6518 mPrivateFlags |= ONLY_DRAWS_BACKGROUND; 6519 } else { 6520 mPrivateFlags |= SKIP_DRAW; 6521 } 6522 } else { 6523 mPrivateFlags &= ~SKIP_DRAW; 6524 } 6525 requestLayout(); 6526 invalidate(true); 6527 } 6528 6529 if ((changed & KEEP_SCREEN_ON) != 0) { 6530 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 6531 mParent.recomputeViewAttributes(this); 6532 } 6533 } 6534 6535 if ((changed & LAYOUT_DIRECTION_MASK) != 0) { 6536 requestLayout(); 6537 } 6538 } 6539 6540 /** 6541 * Change the view's z order in the tree, so it's on top of other sibling 6542 * views 6543 */ 6544 public void bringToFront() { 6545 if (mParent != null) { 6546 mParent.bringChildToFront(this); 6547 } 6548 } 6549 6550 /** 6551 * This is called in response to an internal scroll in this view (i.e., the 6552 * view scrolled its own contents). This is typically as a result of 6553 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 6554 * called. 6555 * 6556 * @param l Current horizontal scroll origin. 6557 * @param t Current vertical scroll origin. 6558 * @param oldl Previous horizontal scroll origin. 6559 * @param oldt Previous vertical scroll origin. 6560 */ 6561 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 6562 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 6563 postSendViewScrolledAccessibilityEventCallback(); 6564 } 6565 6566 mBackgroundSizeChanged = true; 6567 6568 final AttachInfo ai = mAttachInfo; 6569 if (ai != null) { 6570 ai.mViewScrollChanged = true; 6571 } 6572 } 6573 6574 /** 6575 * Interface definition for a callback to be invoked when the layout bounds of a view 6576 * changes due to layout processing. 6577 */ 6578 public interface OnLayoutChangeListener { 6579 /** 6580 * Called when the focus state of a view has changed. 6581 * 6582 * @param v The view whose state has changed. 6583 * @param left The new value of the view's left property. 6584 * @param top The new value of the view's top property. 6585 * @param right The new value of the view's right property. 6586 * @param bottom The new value of the view's bottom property. 6587 * @param oldLeft The previous value of the view's left property. 6588 * @param oldTop The previous value of the view's top property. 6589 * @param oldRight The previous value of the view's right property. 6590 * @param oldBottom The previous value of the view's bottom property. 6591 */ 6592 void onLayoutChange(View v, int left, int top, int right, int bottom, 6593 int oldLeft, int oldTop, int oldRight, int oldBottom); 6594 } 6595 6596 /** 6597 * This is called during layout when the size of this view has changed. If 6598 * you were just added to the view hierarchy, you're called with the old 6599 * values of 0. 6600 * 6601 * @param w Current width of this view. 6602 * @param h Current height of this view. 6603 * @param oldw Old width of this view. 6604 * @param oldh Old height of this view. 6605 */ 6606 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 6607 } 6608 6609 /** 6610 * Called by draw to draw the child views. This may be overridden 6611 * by derived classes to gain control just before its children are drawn 6612 * (but after its own view has been drawn). 6613 * @param canvas the canvas on which to draw the view 6614 */ 6615 protected void dispatchDraw(Canvas canvas) { 6616 } 6617 6618 /** 6619 * Gets the parent of this view. Note that the parent is a 6620 * ViewParent and not necessarily a View. 6621 * 6622 * @return Parent of this view. 6623 */ 6624 public final ViewParent getParent() { 6625 return mParent; 6626 } 6627 6628 /** 6629 * Set the horizontal scrolled position of your view. This will cause a call to 6630 * {@link #onScrollChanged(int, int, int, int)} and the view will be 6631 * invalidated. 6632 * @param value the x position to scroll to 6633 */ 6634 public void setScrollX(int value) { 6635 scrollTo(value, mScrollY); 6636 } 6637 6638 /** 6639 * Set the vertical scrolled position of your view. This will cause a call to 6640 * {@link #onScrollChanged(int, int, int, int)} and the view will be 6641 * invalidated. 6642 * @param value the y position to scroll to 6643 */ 6644 public void setScrollY(int value) { 6645 scrollTo(mScrollX, value); 6646 } 6647 6648 /** 6649 * Return the scrolled left position of this view. This is the left edge of 6650 * the displayed part of your view. You do not need to draw any pixels 6651 * farther left, since those are outside of the frame of your view on 6652 * screen. 6653 * 6654 * @return The left edge of the displayed part of your view, in pixels. 6655 */ 6656 public final int getScrollX() { 6657 return mScrollX; 6658 } 6659 6660 /** 6661 * Return the scrolled top position of this view. This is the top edge of 6662 * the displayed part of your view. You do not need to draw any pixels above 6663 * it, since those are outside of the frame of your view on screen. 6664 * 6665 * @return The top edge of the displayed part of your view, in pixels. 6666 */ 6667 public final int getScrollY() { 6668 return mScrollY; 6669 } 6670 6671 /** 6672 * Return the width of the your view. 6673 * 6674 * @return The width of your view, in pixels. 6675 */ 6676 @ViewDebug.ExportedProperty(category = "layout") 6677 public final int getWidth() { 6678 return mRight - mLeft; 6679 } 6680 6681 /** 6682 * Return the height of your view. 6683 * 6684 * @return The height of your view, in pixels. 6685 */ 6686 @ViewDebug.ExportedProperty(category = "layout") 6687 public final int getHeight() { 6688 return mBottom - mTop; 6689 } 6690 6691 /** 6692 * Return the visible drawing bounds of your view. Fills in the output 6693 * rectangle with the values from getScrollX(), getScrollY(), 6694 * getWidth(), and getHeight(). 6695 * 6696 * @param outRect The (scrolled) drawing bounds of the view. 6697 */ 6698 public void getDrawingRect(Rect outRect) { 6699 outRect.left = mScrollX; 6700 outRect.top = mScrollY; 6701 outRect.right = mScrollX + (mRight - mLeft); 6702 outRect.bottom = mScrollY + (mBottom - mTop); 6703 } 6704 6705 /** 6706 * Like {@link #getMeasuredWidthAndState()}, but only returns the 6707 * raw width component (that is the result is masked by 6708 * {@link #MEASURED_SIZE_MASK}). 6709 * 6710 * @return The raw measured width of this view. 6711 */ 6712 public final int getMeasuredWidth() { 6713 return mMeasuredWidth & MEASURED_SIZE_MASK; 6714 } 6715 6716 /** 6717 * Return the full width measurement information for this view as computed 6718 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 6719 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 6720 * This should be used during measurement and layout calculations only. Use 6721 * {@link #getWidth()} to see how wide a view is after layout. 6722 * 6723 * @return The measured width of this view as a bit mask. 6724 */ 6725 public final int getMeasuredWidthAndState() { 6726 return mMeasuredWidth; 6727 } 6728 6729 /** 6730 * Like {@link #getMeasuredHeightAndState()}, but only returns the 6731 * raw width component (that is the result is masked by 6732 * {@link #MEASURED_SIZE_MASK}). 6733 * 6734 * @return The raw measured height of this view. 6735 */ 6736 public final int getMeasuredHeight() { 6737 return mMeasuredHeight & MEASURED_SIZE_MASK; 6738 } 6739 6740 /** 6741 * Return the full height measurement information for this view as computed 6742 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 6743 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 6744 * This should be used during measurement and layout calculations only. Use 6745 * {@link #getHeight()} to see how wide a view is after layout. 6746 * 6747 * @return The measured width of this view as a bit mask. 6748 */ 6749 public final int getMeasuredHeightAndState() { 6750 return mMeasuredHeight; 6751 } 6752 6753 /** 6754 * Return only the state bits of {@link #getMeasuredWidthAndState()} 6755 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 6756 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 6757 * and the height component is at the shifted bits 6758 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 6759 */ 6760 public final int getMeasuredState() { 6761 return (mMeasuredWidth&MEASURED_STATE_MASK) 6762 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 6763 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 6764 } 6765 6766 /** 6767 * The transform matrix of this view, which is calculated based on the current 6768 * roation, scale, and pivot properties. 6769 * 6770 * @see #getRotation() 6771 * @see #getScaleX() 6772 * @see #getScaleY() 6773 * @see #getPivotX() 6774 * @see #getPivotY() 6775 * @return The current transform matrix for the view 6776 */ 6777 public Matrix getMatrix() { 6778 updateMatrix(); 6779 return mMatrix; 6780 } 6781 6782 /** 6783 * Utility function to determine if the value is far enough away from zero to be 6784 * considered non-zero. 6785 * @param value A floating point value to check for zero-ness 6786 * @return whether the passed-in value is far enough away from zero to be considered non-zero 6787 */ 6788 private static boolean nonzero(float value) { 6789 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON); 6790 } 6791 6792 /** 6793 * Returns true if the transform matrix is the identity matrix. 6794 * Recomputes the matrix if necessary. 6795 * 6796 * @return True if the transform matrix is the identity matrix, false otherwise. 6797 */ 6798 final boolean hasIdentityMatrix() { 6799 updateMatrix(); 6800 return mMatrixIsIdentity; 6801 } 6802 6803 /** 6804 * Recomputes the transform matrix if necessary. 6805 */ 6806 private void updateMatrix() { 6807 if (mMatrixDirty) { 6808 // transform-related properties have changed since the last time someone 6809 // asked for the matrix; recalculate it with the current values 6810 6811 // Figure out if we need to update the pivot point 6812 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 6813 if ((mRight - mLeft) != mPrevWidth || (mBottom - mTop) != mPrevHeight) { 6814 mPrevWidth = mRight - mLeft; 6815 mPrevHeight = mBottom - mTop; 6816 mPivotX = mPrevWidth / 2f; 6817 mPivotY = mPrevHeight / 2f; 6818 } 6819 } 6820 mMatrix.reset(); 6821 if (!nonzero(mRotationX) && !nonzero(mRotationY)) { 6822 mMatrix.setTranslate(mTranslationX, mTranslationY); 6823 mMatrix.preRotate(mRotation, mPivotX, mPivotY); 6824 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY); 6825 } else { 6826 if (mCamera == null) { 6827 mCamera = new Camera(); 6828 matrix3D = new Matrix(); 6829 } 6830 mCamera.save(); 6831 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY); 6832 mCamera.rotate(mRotationX, mRotationY, -mRotation); 6833 mCamera.getMatrix(matrix3D); 6834 matrix3D.preTranslate(-mPivotX, -mPivotY); 6835 matrix3D.postTranslate(mPivotX + mTranslationX, mPivotY + mTranslationY); 6836 mMatrix.postConcat(matrix3D); 6837 mCamera.restore(); 6838 } 6839 mMatrixDirty = false; 6840 mMatrixIsIdentity = mMatrix.isIdentity(); 6841 mInverseMatrixDirty = true; 6842 } 6843 } 6844 6845 /** 6846 * Utility method to retrieve the inverse of the current mMatrix property. 6847 * We cache the matrix to avoid recalculating it when transform properties 6848 * have not changed. 6849 * 6850 * @return The inverse of the current matrix of this view. 6851 */ 6852 final Matrix getInverseMatrix() { 6853 updateMatrix(); 6854 if (mInverseMatrixDirty) { 6855 if (mInverseMatrix == null) { 6856 mInverseMatrix = new Matrix(); 6857 } 6858 mMatrix.invert(mInverseMatrix); 6859 mInverseMatrixDirty = false; 6860 } 6861 return mInverseMatrix; 6862 } 6863 6864 /** 6865 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 6866 * views are drawn) from the camera to this view. The camera's distance 6867 * affects 3D transformations, for instance rotations around the X and Y 6868 * axis. If the rotationX or rotationY properties are changed and this view is 6869 * large (more than half the size of the screen), it is recommended to always 6870 * use a camera distance that's greater than the height (X axis rotation) or 6871 * the width (Y axis rotation) of this view.</p> 6872 * 6873 * <p>The distance of the camera from the view plane can have an affect on the 6874 * perspective distortion of the view when it is rotated around the x or y axis. 6875 * For example, a large distance will result in a large viewing angle, and there 6876 * will not be much perspective distortion of the view as it rotates. A short 6877 * distance may cause much more perspective distortion upon rotation, and can 6878 * also result in some drawing artifacts if the rotated view ends up partially 6879 * behind the camera (which is why the recommendation is to use a distance at 6880 * least as far as the size of the view, if the view is to be rotated.)</p> 6881 * 6882 * <p>The distance is expressed in "depth pixels." The default distance depends 6883 * on the screen density. For instance, on a medium density display, the 6884 * default distance is 1280. On a high density display, the default distance 6885 * is 1920.</p> 6886 * 6887 * <p>If you want to specify a distance that leads to visually consistent 6888 * results across various densities, use the following formula:</p> 6889 * <pre> 6890 * float scale = context.getResources().getDisplayMetrics().density; 6891 * view.setCameraDistance(distance * scale); 6892 * </pre> 6893 * 6894 * <p>The density scale factor of a high density display is 1.5, 6895 * and 1920 = 1280 * 1.5.</p> 6896 * 6897 * @param distance The distance in "depth pixels", if negative the opposite 6898 * value is used 6899 * 6900 * @see #setRotationX(float) 6901 * @see #setRotationY(float) 6902 */ 6903 public void setCameraDistance(float distance) { 6904 invalidateParentCaches(); 6905 invalidate(false); 6906 6907 final float dpi = mResources.getDisplayMetrics().densityDpi; 6908 if (mCamera == null) { 6909 mCamera = new Camera(); 6910 matrix3D = new Matrix(); 6911 } 6912 6913 mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi); 6914 mMatrixDirty = true; 6915 6916 invalidate(false); 6917 } 6918 6919 /** 6920 * The degrees that the view is rotated around the pivot point. 6921 * 6922 * @see #setRotation(float) 6923 * @see #getPivotX() 6924 * @see #getPivotY() 6925 * 6926 * @return The degrees of rotation. 6927 */ 6928 public float getRotation() { 6929 return mRotation; 6930 } 6931 6932 /** 6933 * Sets the degrees that the view is rotated around the pivot point. Increasing values 6934 * result in clockwise rotation. 6935 * 6936 * @param rotation The degrees of rotation. 6937 * 6938 * @see #getRotation() 6939 * @see #getPivotX() 6940 * @see #getPivotY() 6941 * @see #setRotationX(float) 6942 * @see #setRotationY(float) 6943 * 6944 * @attr ref android.R.styleable#View_rotation 6945 */ 6946 public void setRotation(float rotation) { 6947 if (mRotation != rotation) { 6948 invalidateParentCaches(); 6949 // Double-invalidation is necessary to capture view's old and new areas 6950 invalidate(false); 6951 mRotation = rotation; 6952 mMatrixDirty = true; 6953 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6954 invalidate(false); 6955 } 6956 } 6957 6958 /** 6959 * The degrees that the view is rotated around the vertical axis through the pivot point. 6960 * 6961 * @see #getPivotX() 6962 * @see #getPivotY() 6963 * @see #setRotationY(float) 6964 * 6965 * @return The degrees of Y rotation. 6966 */ 6967 public float getRotationY() { 6968 return mRotationY; 6969 } 6970 6971 /** 6972 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 6973 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 6974 * down the y axis. 6975 * 6976 * When rotating large views, it is recommended to adjust the camera distance 6977 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 6978 * 6979 * @param rotationY The degrees of Y rotation. 6980 * 6981 * @see #getRotationY() 6982 * @see #getPivotX() 6983 * @see #getPivotY() 6984 * @see #setRotation(float) 6985 * @see #setRotationX(float) 6986 * @see #setCameraDistance(float) 6987 * 6988 * @attr ref android.R.styleable#View_rotationY 6989 */ 6990 public void setRotationY(float rotationY) { 6991 if (mRotationY != rotationY) { 6992 invalidateParentCaches(); 6993 // Double-invalidation is necessary to capture view's old and new areas 6994 invalidate(false); 6995 mRotationY = rotationY; 6996 mMatrixDirty = true; 6997 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6998 invalidate(false); 6999 } 7000 } 7001 7002 /** 7003 * The degrees that the view is rotated around the horizontal axis through the pivot point. 7004 * 7005 * @see #getPivotX() 7006 * @see #getPivotY() 7007 * @see #setRotationX(float) 7008 * 7009 * @return The degrees of X rotation. 7010 */ 7011 public float getRotationX() { 7012 return mRotationX; 7013 } 7014 7015 /** 7016 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 7017 * Increasing values result in clockwise rotation from the viewpoint of looking down the 7018 * x axis. 7019 * 7020 * When rotating large views, it is recommended to adjust the camera distance 7021 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 7022 * 7023 * @param rotationX The degrees of X rotation. 7024 * 7025 * @see #getRotationX() 7026 * @see #getPivotX() 7027 * @see #getPivotY() 7028 * @see #setRotation(float) 7029 * @see #setRotationY(float) 7030 * @see #setCameraDistance(float) 7031 * 7032 * @attr ref android.R.styleable#View_rotationX 7033 */ 7034 public void setRotationX(float rotationX) { 7035 if (mRotationX != rotationX) { 7036 invalidateParentCaches(); 7037 // Double-invalidation is necessary to capture view's old and new areas 7038 invalidate(false); 7039 mRotationX = rotationX; 7040 mMatrixDirty = true; 7041 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7042 invalidate(false); 7043 } 7044 } 7045 7046 /** 7047 * The amount that the view is scaled in x around the pivot point, as a proportion of 7048 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 7049 * 7050 * <p>By default, this is 1.0f. 7051 * 7052 * @see #getPivotX() 7053 * @see #getPivotY() 7054 * @return The scaling factor. 7055 */ 7056 public float getScaleX() { 7057 return mScaleX; 7058 } 7059 7060 /** 7061 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 7062 * the view's unscaled width. A value of 1 means that no scaling is applied. 7063 * 7064 * @param scaleX The scaling factor. 7065 * @see #getPivotX() 7066 * @see #getPivotY() 7067 * 7068 * @attr ref android.R.styleable#View_scaleX 7069 */ 7070 public void setScaleX(float scaleX) { 7071 if (mScaleX != scaleX) { 7072 invalidateParentCaches(); 7073 // Double-invalidation is necessary to capture view's old and new areas 7074 invalidate(false); 7075 mScaleX = scaleX; 7076 mMatrixDirty = true; 7077 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7078 invalidate(false); 7079 } 7080 } 7081 7082 /** 7083 * The amount that the view is scaled in y around the pivot point, as a proportion of 7084 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 7085 * 7086 * <p>By default, this is 1.0f. 7087 * 7088 * @see #getPivotX() 7089 * @see #getPivotY() 7090 * @return The scaling factor. 7091 */ 7092 public float getScaleY() { 7093 return mScaleY; 7094 } 7095 7096 /** 7097 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 7098 * the view's unscaled width. A value of 1 means that no scaling is applied. 7099 * 7100 * @param scaleY The scaling factor. 7101 * @see #getPivotX() 7102 * @see #getPivotY() 7103 * 7104 * @attr ref android.R.styleable#View_scaleY 7105 */ 7106 public void setScaleY(float scaleY) { 7107 if (mScaleY != scaleY) { 7108 invalidateParentCaches(); 7109 // Double-invalidation is necessary to capture view's old and new areas 7110 invalidate(false); 7111 mScaleY = scaleY; 7112 mMatrixDirty = true; 7113 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7114 invalidate(false); 7115 } 7116 } 7117 7118 /** 7119 * The x location of the point around which the view is {@link #setRotation(float) rotated} 7120 * and {@link #setScaleX(float) scaled}. 7121 * 7122 * @see #getRotation() 7123 * @see #getScaleX() 7124 * @see #getScaleY() 7125 * @see #getPivotY() 7126 * @return The x location of the pivot point. 7127 */ 7128 public float getPivotX() { 7129 return mPivotX; 7130 } 7131 7132 /** 7133 * Sets the x location of the point around which the view is 7134 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 7135 * By default, the pivot point is centered on the object. 7136 * Setting this property disables this behavior and causes the view to use only the 7137 * explicitly set pivotX and pivotY values. 7138 * 7139 * @param pivotX The x location of the pivot point. 7140 * @see #getRotation() 7141 * @see #getScaleX() 7142 * @see #getScaleY() 7143 * @see #getPivotY() 7144 * 7145 * @attr ref android.R.styleable#View_transformPivotX 7146 */ 7147 public void setPivotX(float pivotX) { 7148 mPrivateFlags |= PIVOT_EXPLICITLY_SET; 7149 if (mPivotX != pivotX) { 7150 invalidateParentCaches(); 7151 // Double-invalidation is necessary to capture view's old and new areas 7152 invalidate(false); 7153 mPivotX = pivotX; 7154 mMatrixDirty = true; 7155 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7156 invalidate(false); 7157 } 7158 } 7159 7160 /** 7161 * The y location of the point around which the view is {@link #setRotation(float) rotated} 7162 * and {@link #setScaleY(float) scaled}. 7163 * 7164 * @see #getRotation() 7165 * @see #getScaleX() 7166 * @see #getScaleY() 7167 * @see #getPivotY() 7168 * @return The y location of the pivot point. 7169 */ 7170 public float getPivotY() { 7171 return mPivotY; 7172 } 7173 7174 /** 7175 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 7176 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 7177 * Setting this property disables this behavior and causes the view to use only the 7178 * explicitly set pivotX and pivotY values. 7179 * 7180 * @param pivotY The y location of the pivot point. 7181 * @see #getRotation() 7182 * @see #getScaleX() 7183 * @see #getScaleY() 7184 * @see #getPivotY() 7185 * 7186 * @attr ref android.R.styleable#View_transformPivotY 7187 */ 7188 public void setPivotY(float pivotY) { 7189 mPrivateFlags |= PIVOT_EXPLICITLY_SET; 7190 if (mPivotY != pivotY) { 7191 invalidateParentCaches(); 7192 // Double-invalidation is necessary to capture view's old and new areas 7193 invalidate(false); 7194 mPivotY = pivotY; 7195 mMatrixDirty = true; 7196 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7197 invalidate(false); 7198 } 7199 } 7200 7201 /** 7202 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 7203 * completely transparent and 1 means the view is completely opaque. 7204 * 7205 * <p>By default this is 1.0f. 7206 * @return The opacity of the view. 7207 */ 7208 public float getAlpha() { 7209 return mAlpha; 7210 } 7211 7212 /** 7213 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 7214 * completely transparent and 1 means the view is completely opaque.</p> 7215 * 7216 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 7217 * responsible for applying the opacity itself. Otherwise, calling this method is 7218 * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and 7219 * setting a hardware layer.</p> 7220 * 7221 * @param alpha The opacity of the view. 7222 * 7223 * @see #setLayerType(int, android.graphics.Paint) 7224 * 7225 * @attr ref android.R.styleable#View_alpha 7226 */ 7227 public void setAlpha(float alpha) { 7228 mAlpha = alpha; 7229 invalidateParentCaches(); 7230 if (onSetAlpha((int) (alpha * 255))) { 7231 mPrivateFlags |= ALPHA_SET; 7232 // subclass is handling alpha - don't optimize rendering cache invalidation 7233 invalidate(true); 7234 } else { 7235 mPrivateFlags &= ~ALPHA_SET; 7236 invalidate(false); 7237 } 7238 } 7239 7240 /** 7241 * Faster version of setAlpha() which performs the same steps except there are 7242 * no calls to invalidate(). The caller of this function should perform proper invalidation 7243 * on the parent and this object. The return value indicates whether the subclass handles 7244 * alpha (the return value for onSetAlpha()). 7245 * 7246 * @param alpha The new value for the alpha property 7247 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) 7248 */ 7249 boolean setAlphaNoInvalidation(float alpha) { 7250 mAlpha = alpha; 7251 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 7252 if (subclassHandlesAlpha) { 7253 mPrivateFlags |= ALPHA_SET; 7254 } else { 7255 mPrivateFlags &= ~ALPHA_SET; 7256 } 7257 return subclassHandlesAlpha; 7258 } 7259 7260 /** 7261 * Top position of this view relative to its parent. 7262 * 7263 * @return The top of this view, in pixels. 7264 */ 7265 @ViewDebug.CapturedViewProperty 7266 public final int getTop() { 7267 return mTop; 7268 } 7269 7270 /** 7271 * Sets the top position of this view relative to its parent. This method is meant to be called 7272 * by the layout system and should not generally be called otherwise, because the property 7273 * may be changed at any time by the layout. 7274 * 7275 * @param top The top of this view, in pixels. 7276 */ 7277 public final void setTop(int top) { 7278 if (top != mTop) { 7279 updateMatrix(); 7280 if (mMatrixIsIdentity) { 7281 if (mAttachInfo != null) { 7282 int minTop; 7283 int yLoc; 7284 if (top < mTop) { 7285 minTop = top; 7286 yLoc = top - mTop; 7287 } else { 7288 minTop = mTop; 7289 yLoc = 0; 7290 } 7291 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 7292 } 7293 } else { 7294 // Double-invalidation is necessary to capture view's old and new areas 7295 invalidate(true); 7296 } 7297 7298 int width = mRight - mLeft; 7299 int oldHeight = mBottom - mTop; 7300 7301 mTop = top; 7302 7303 onSizeChanged(width, mBottom - mTop, width, oldHeight); 7304 7305 if (!mMatrixIsIdentity) { 7306 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7307 // A change in dimension means an auto-centered pivot point changes, too 7308 mMatrixDirty = true; 7309 } 7310 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7311 invalidate(true); 7312 } 7313 mBackgroundSizeChanged = true; 7314 invalidateParentIfNeeded(); 7315 } 7316 } 7317 7318 /** 7319 * Bottom position of this view relative to its parent. 7320 * 7321 * @return The bottom of this view, in pixels. 7322 */ 7323 @ViewDebug.CapturedViewProperty 7324 public final int getBottom() { 7325 return mBottom; 7326 } 7327 7328 /** 7329 * True if this view has changed since the last time being drawn. 7330 * 7331 * @return The dirty state of this view. 7332 */ 7333 public boolean isDirty() { 7334 return (mPrivateFlags & DIRTY_MASK) != 0; 7335 } 7336 7337 /** 7338 * Sets the bottom position of this view relative to its parent. This method is meant to be 7339 * called by the layout system and should not generally be called otherwise, because the 7340 * property may be changed at any time by the layout. 7341 * 7342 * @param bottom The bottom of this view, in pixels. 7343 */ 7344 public final void setBottom(int bottom) { 7345 if (bottom != mBottom) { 7346 updateMatrix(); 7347 if (mMatrixIsIdentity) { 7348 if (mAttachInfo != null) { 7349 int maxBottom; 7350 if (bottom < mBottom) { 7351 maxBottom = mBottom; 7352 } else { 7353 maxBottom = bottom; 7354 } 7355 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 7356 } 7357 } else { 7358 // Double-invalidation is necessary to capture view's old and new areas 7359 invalidate(true); 7360 } 7361 7362 int width = mRight - mLeft; 7363 int oldHeight = mBottom - mTop; 7364 7365 mBottom = bottom; 7366 7367 onSizeChanged(width, mBottom - mTop, width, oldHeight); 7368 7369 if (!mMatrixIsIdentity) { 7370 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7371 // A change in dimension means an auto-centered pivot point changes, too 7372 mMatrixDirty = true; 7373 } 7374 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7375 invalidate(true); 7376 } 7377 mBackgroundSizeChanged = true; 7378 invalidateParentIfNeeded(); 7379 } 7380 } 7381 7382 /** 7383 * Left position of this view relative to its parent. 7384 * 7385 * @return The left edge of this view, in pixels. 7386 */ 7387 @ViewDebug.CapturedViewProperty 7388 public final int getLeft() { 7389 return mLeft; 7390 } 7391 7392 /** 7393 * Sets the left position of this view relative to its parent. This method is meant to be called 7394 * by the layout system and should not generally be called otherwise, because the property 7395 * may be changed at any time by the layout. 7396 * 7397 * @param left The bottom of this view, in pixels. 7398 */ 7399 public final void setLeft(int left) { 7400 if (left != mLeft) { 7401 updateMatrix(); 7402 if (mMatrixIsIdentity) { 7403 if (mAttachInfo != null) { 7404 int minLeft; 7405 int xLoc; 7406 if (left < mLeft) { 7407 minLeft = left; 7408 xLoc = left - mLeft; 7409 } else { 7410 minLeft = mLeft; 7411 xLoc = 0; 7412 } 7413 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 7414 } 7415 } else { 7416 // Double-invalidation is necessary to capture view's old and new areas 7417 invalidate(true); 7418 } 7419 7420 int oldWidth = mRight - mLeft; 7421 int height = mBottom - mTop; 7422 7423 mLeft = left; 7424 7425 onSizeChanged(mRight - mLeft, height, oldWidth, height); 7426 7427 if (!mMatrixIsIdentity) { 7428 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7429 // A change in dimension means an auto-centered pivot point changes, too 7430 mMatrixDirty = true; 7431 } 7432 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7433 invalidate(true); 7434 } 7435 mBackgroundSizeChanged = true; 7436 invalidateParentIfNeeded(); 7437 } 7438 } 7439 7440 /** 7441 * Right position of this view relative to its parent. 7442 * 7443 * @return The right edge of this view, in pixels. 7444 */ 7445 @ViewDebug.CapturedViewProperty 7446 public final int getRight() { 7447 return mRight; 7448 } 7449 7450 /** 7451 * Sets the right position of this view relative to its parent. This method is meant to be called 7452 * by the layout system and should not generally be called otherwise, because the property 7453 * may be changed at any time by the layout. 7454 * 7455 * @param right The bottom of this view, in pixels. 7456 */ 7457 public final void setRight(int right) { 7458 if (right != mRight) { 7459 updateMatrix(); 7460 if (mMatrixIsIdentity) { 7461 if (mAttachInfo != null) { 7462 int maxRight; 7463 if (right < mRight) { 7464 maxRight = mRight; 7465 } else { 7466 maxRight = right; 7467 } 7468 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 7469 } 7470 } else { 7471 // Double-invalidation is necessary to capture view's old and new areas 7472 invalidate(true); 7473 } 7474 7475 int oldWidth = mRight - mLeft; 7476 int height = mBottom - mTop; 7477 7478 mRight = right; 7479 7480 onSizeChanged(mRight - mLeft, height, oldWidth, height); 7481 7482 if (!mMatrixIsIdentity) { 7483 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 7484 // A change in dimension means an auto-centered pivot point changes, too 7485 mMatrixDirty = true; 7486 } 7487 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7488 invalidate(true); 7489 } 7490 mBackgroundSizeChanged = true; 7491 invalidateParentIfNeeded(); 7492 } 7493 } 7494 7495 /** 7496 * The visual x position of this view, in pixels. This is equivalent to the 7497 * {@link #setTranslationX(float) translationX} property plus the current 7498 * {@link #getLeft() left} property. 7499 * 7500 * @return The visual x position of this view, in pixels. 7501 */ 7502 public float getX() { 7503 return mLeft + mTranslationX; 7504 } 7505 7506 /** 7507 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 7508 * {@link #setTranslationX(float) translationX} property to be the difference between 7509 * the x value passed in and the current {@link #getLeft() left} property. 7510 * 7511 * @param x The visual x position of this view, in pixels. 7512 */ 7513 public void setX(float x) { 7514 setTranslationX(x - mLeft); 7515 } 7516 7517 /** 7518 * The visual y position of this view, in pixels. This is equivalent to the 7519 * {@link #setTranslationY(float) translationY} property plus the current 7520 * {@link #getTop() top} property. 7521 * 7522 * @return The visual y position of this view, in pixels. 7523 */ 7524 public float getY() { 7525 return mTop + mTranslationY; 7526 } 7527 7528 /** 7529 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 7530 * {@link #setTranslationY(float) translationY} property to be the difference between 7531 * the y value passed in and the current {@link #getTop() top} property. 7532 * 7533 * @param y The visual y position of this view, in pixels. 7534 */ 7535 public void setY(float y) { 7536 setTranslationY(y - mTop); 7537 } 7538 7539 7540 /** 7541 * The horizontal location of this view relative to its {@link #getLeft() left} position. 7542 * This position is post-layout, in addition to wherever the object's 7543 * layout placed it. 7544 * 7545 * @return The horizontal position of this view relative to its left position, in pixels. 7546 */ 7547 public float getTranslationX() { 7548 return mTranslationX; 7549 } 7550 7551 /** 7552 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 7553 * This effectively positions the object post-layout, in addition to wherever the object's 7554 * layout placed it. 7555 * 7556 * @param translationX The horizontal position of this view relative to its left position, 7557 * in pixels. 7558 * 7559 * @attr ref android.R.styleable#View_translationX 7560 */ 7561 public void setTranslationX(float translationX) { 7562 if (mTranslationX != translationX) { 7563 invalidateParentCaches(); 7564 // Double-invalidation is necessary to capture view's old and new areas 7565 invalidate(false); 7566 mTranslationX = translationX; 7567 mMatrixDirty = true; 7568 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7569 invalidate(false); 7570 } 7571 } 7572 7573 /** 7574 * The horizontal location of this view relative to its {@link #getTop() top} position. 7575 * This position is post-layout, in addition to wherever the object's 7576 * layout placed it. 7577 * 7578 * @return The vertical position of this view relative to its top position, 7579 * in pixels. 7580 */ 7581 public float getTranslationY() { 7582 return mTranslationY; 7583 } 7584 7585 /** 7586 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 7587 * This effectively positions the object post-layout, in addition to wherever the object's 7588 * layout placed it. 7589 * 7590 * @param translationY The vertical position of this view relative to its top position, 7591 * in pixels. 7592 * 7593 * @attr ref android.R.styleable#View_translationY 7594 */ 7595 public void setTranslationY(float translationY) { 7596 if (mTranslationY != translationY) { 7597 invalidateParentCaches(); 7598 // Double-invalidation is necessary to capture view's old and new areas 7599 invalidate(false); 7600 mTranslationY = translationY; 7601 mMatrixDirty = true; 7602 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7603 invalidate(false); 7604 } 7605 } 7606 7607 /** 7608 * @hide 7609 */ 7610 public void setFastTranslationX(float x) { 7611 mTranslationX = x; 7612 mMatrixDirty = true; 7613 } 7614 7615 /** 7616 * @hide 7617 */ 7618 public void setFastTranslationY(float y) { 7619 mTranslationY = y; 7620 mMatrixDirty = true; 7621 } 7622 7623 /** 7624 * @hide 7625 */ 7626 public void setFastX(float x) { 7627 mTranslationX = x - mLeft; 7628 mMatrixDirty = true; 7629 } 7630 7631 /** 7632 * @hide 7633 */ 7634 public void setFastY(float y) { 7635 mTranslationY = y - mTop; 7636 mMatrixDirty = true; 7637 } 7638 7639 /** 7640 * @hide 7641 */ 7642 public void setFastScaleX(float x) { 7643 mScaleX = x; 7644 mMatrixDirty = true; 7645 } 7646 7647 /** 7648 * @hide 7649 */ 7650 public void setFastScaleY(float y) { 7651 mScaleY = y; 7652 mMatrixDirty = true; 7653 } 7654 7655 /** 7656 * @hide 7657 */ 7658 public void setFastAlpha(float alpha) { 7659 mAlpha = alpha; 7660 } 7661 7662 /** 7663 * @hide 7664 */ 7665 public void setFastRotationY(float y) { 7666 mRotationY = y; 7667 mMatrixDirty = true; 7668 } 7669 7670 /** 7671 * Hit rectangle in parent's coordinates 7672 * 7673 * @param outRect The hit rectangle of the view. 7674 */ 7675 public void getHitRect(Rect outRect) { 7676 updateMatrix(); 7677 if (mMatrixIsIdentity || mAttachInfo == null) { 7678 outRect.set(mLeft, mTop, mRight, mBottom); 7679 } else { 7680 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 7681 tmpRect.set(-mPivotX, -mPivotY, getWidth() - mPivotX, getHeight() - mPivotY); 7682 mMatrix.mapRect(tmpRect); 7683 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 7684 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 7685 } 7686 } 7687 7688 /** 7689 * Determines whether the given point, in local coordinates is inside the view. 7690 */ 7691 /*package*/ final boolean pointInView(float localX, float localY) { 7692 return localX >= 0 && localX < (mRight - mLeft) 7693 && localY >= 0 && localY < (mBottom - mTop); 7694 } 7695 7696 /** 7697 * Utility method to determine whether the given point, in local coordinates, 7698 * is inside the view, where the area of the view is expanded by the slop factor. 7699 * This method is called while processing touch-move events to determine if the event 7700 * is still within the view. 7701 */ 7702 private boolean pointInView(float localX, float localY, float slop) { 7703 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 7704 localY < ((mBottom - mTop) + slop); 7705 } 7706 7707 /** 7708 * When a view has focus and the user navigates away from it, the next view is searched for 7709 * starting from the rectangle filled in by this method. 7710 * 7711 * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)}) 7712 * of the view. However, if your view maintains some idea of internal selection, 7713 * such as a cursor, or a selected row or column, you should override this method and 7714 * fill in a more specific rectangle. 7715 * 7716 * @param r The rectangle to fill in, in this view's coordinates. 7717 */ 7718 public void getFocusedRect(Rect r) { 7719 getDrawingRect(r); 7720 } 7721 7722 /** 7723 * If some part of this view is not clipped by any of its parents, then 7724 * return that area in r in global (root) coordinates. To convert r to local 7725 * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x, 7726 * -globalOffset.y)) If the view is completely clipped or translated out, 7727 * return false. 7728 * 7729 * @param r If true is returned, r holds the global coordinates of the 7730 * visible portion of this view. 7731 * @param globalOffset If true is returned, globalOffset holds the dx,dy 7732 * between this view and its root. globalOffet may be null. 7733 * @return true if r is non-empty (i.e. part of the view is visible at the 7734 * root level. 7735 */ 7736 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 7737 int width = mRight - mLeft; 7738 int height = mBottom - mTop; 7739 if (width > 0 && height > 0) { 7740 r.set(0, 0, width, height); 7741 if (globalOffset != null) { 7742 globalOffset.set(-mScrollX, -mScrollY); 7743 } 7744 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 7745 } 7746 return false; 7747 } 7748 7749 public final boolean getGlobalVisibleRect(Rect r) { 7750 return getGlobalVisibleRect(r, null); 7751 } 7752 7753 public final boolean getLocalVisibleRect(Rect r) { 7754 Point offset = new Point(); 7755 if (getGlobalVisibleRect(r, offset)) { 7756 r.offset(-offset.x, -offset.y); // make r local 7757 return true; 7758 } 7759 return false; 7760 } 7761 7762 /** 7763 * Offset this view's vertical location by the specified number of pixels. 7764 * 7765 * @param offset the number of pixels to offset the view by 7766 */ 7767 public void offsetTopAndBottom(int offset) { 7768 if (offset != 0) { 7769 updateMatrix(); 7770 if (mMatrixIsIdentity) { 7771 final ViewParent p = mParent; 7772 if (p != null && mAttachInfo != null) { 7773 final Rect r = mAttachInfo.mTmpInvalRect; 7774 int minTop; 7775 int maxBottom; 7776 int yLoc; 7777 if (offset < 0) { 7778 minTop = mTop + offset; 7779 maxBottom = mBottom; 7780 yLoc = offset; 7781 } else { 7782 minTop = mTop; 7783 maxBottom = mBottom + offset; 7784 yLoc = 0; 7785 } 7786 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 7787 p.invalidateChild(this, r); 7788 } 7789 } else { 7790 invalidate(false); 7791 } 7792 7793 mTop += offset; 7794 mBottom += offset; 7795 7796 if (!mMatrixIsIdentity) { 7797 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7798 invalidate(false); 7799 } 7800 invalidateParentIfNeeded(); 7801 } 7802 } 7803 7804 /** 7805 * Offset this view's horizontal location by the specified amount of pixels. 7806 * 7807 * @param offset the numer of pixels to offset the view by 7808 */ 7809 public void offsetLeftAndRight(int offset) { 7810 if (offset != 0) { 7811 updateMatrix(); 7812 if (mMatrixIsIdentity) { 7813 final ViewParent p = mParent; 7814 if (p != null && mAttachInfo != null) { 7815 final Rect r = mAttachInfo.mTmpInvalRect; 7816 int minLeft; 7817 int maxRight; 7818 if (offset < 0) { 7819 minLeft = mLeft + offset; 7820 maxRight = mRight; 7821 } else { 7822 minLeft = mLeft; 7823 maxRight = mRight + offset; 7824 } 7825 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 7826 p.invalidateChild(this, r); 7827 } 7828 } else { 7829 invalidate(false); 7830 } 7831 7832 mLeft += offset; 7833 mRight += offset; 7834 7835 if (!mMatrixIsIdentity) { 7836 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7837 invalidate(false); 7838 } 7839 invalidateParentIfNeeded(); 7840 } 7841 } 7842 7843 /** 7844 * Get the LayoutParams associated with this view. All views should have 7845 * layout parameters. These supply parameters to the <i>parent</i> of this 7846 * view specifying how it should be arranged. There are many subclasses of 7847 * ViewGroup.LayoutParams, and these correspond to the different subclasses 7848 * of ViewGroup that are responsible for arranging their children. 7849 * 7850 * This method may return null if this View is not attached to a parent 7851 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 7852 * was not invoked successfully. When a View is attached to a parent 7853 * ViewGroup, this method must not return null. 7854 * 7855 * @return The LayoutParams associated with this view, or null if no 7856 * parameters have been set yet 7857 */ 7858 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 7859 public ViewGroup.LayoutParams getLayoutParams() { 7860 return mLayoutParams; 7861 } 7862 7863 /** 7864 * Set the layout parameters associated with this view. These supply 7865 * parameters to the <i>parent</i> of this view specifying how it should be 7866 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 7867 * correspond to the different subclasses of ViewGroup that are responsible 7868 * for arranging their children. 7869 * 7870 * @param params The layout parameters for this view, cannot be null 7871 */ 7872 public void setLayoutParams(ViewGroup.LayoutParams params) { 7873 if (params == null) { 7874 throw new NullPointerException("Layout parameters cannot be null"); 7875 } 7876 mLayoutParams = params; 7877 requestLayout(); 7878 } 7879 7880 /** 7881 * Set the scrolled position of your view. This will cause a call to 7882 * {@link #onScrollChanged(int, int, int, int)} and the view will be 7883 * invalidated. 7884 * @param x the x position to scroll to 7885 * @param y the y position to scroll to 7886 */ 7887 public void scrollTo(int x, int y) { 7888 if (mScrollX != x || mScrollY != y) { 7889 int oldX = mScrollX; 7890 int oldY = mScrollY; 7891 mScrollX = x; 7892 mScrollY = y; 7893 invalidateParentCaches(); 7894 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 7895 if (!awakenScrollBars()) { 7896 invalidate(true); 7897 } 7898 } 7899 } 7900 7901 /** 7902 * Move the scrolled position of your view. This will cause a call to 7903 * {@link #onScrollChanged(int, int, int, int)} and the view will be 7904 * invalidated. 7905 * @param x the amount of pixels to scroll by horizontally 7906 * @param y the amount of pixels to scroll by vertically 7907 */ 7908 public void scrollBy(int x, int y) { 7909 scrollTo(mScrollX + x, mScrollY + y); 7910 } 7911 7912 /** 7913 * <p>Trigger the scrollbars to draw. When invoked this method starts an 7914 * animation to fade the scrollbars out after a default delay. If a subclass 7915 * provides animated scrolling, the start delay should equal the duration 7916 * of the scrolling animation.</p> 7917 * 7918 * <p>The animation starts only if at least one of the scrollbars is 7919 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 7920 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 7921 * this method returns true, and false otherwise. If the animation is 7922 * started, this method calls {@link #invalidate()}; in that case the 7923 * caller should not call {@link #invalidate()}.</p> 7924 * 7925 * <p>This method should be invoked every time a subclass directly updates 7926 * the scroll parameters.</p> 7927 * 7928 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 7929 * and {@link #scrollTo(int, int)}.</p> 7930 * 7931 * @return true if the animation is played, false otherwise 7932 * 7933 * @see #awakenScrollBars(int) 7934 * @see #scrollBy(int, int) 7935 * @see #scrollTo(int, int) 7936 * @see #isHorizontalScrollBarEnabled() 7937 * @see #isVerticalScrollBarEnabled() 7938 * @see #setHorizontalScrollBarEnabled(boolean) 7939 * @see #setVerticalScrollBarEnabled(boolean) 7940 */ 7941 protected boolean awakenScrollBars() { 7942 return mScrollCache != null && 7943 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 7944 } 7945 7946 /** 7947 * Trigger the scrollbars to draw. 7948 * This method differs from awakenScrollBars() only in its default duration. 7949 * initialAwakenScrollBars() will show the scroll bars for longer than 7950 * usual to give the user more of a chance to notice them. 7951 * 7952 * @return true if the animation is played, false otherwise. 7953 */ 7954 private boolean initialAwakenScrollBars() { 7955 return mScrollCache != null && 7956 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 7957 } 7958 7959 /** 7960 * <p> 7961 * Trigger the scrollbars to draw. When invoked this method starts an 7962 * animation to fade the scrollbars out after a fixed delay. If a subclass 7963 * provides animated scrolling, the start delay should equal the duration of 7964 * the scrolling animation. 7965 * </p> 7966 * 7967 * <p> 7968 * The animation starts only if at least one of the scrollbars is enabled, 7969 * as specified by {@link #isHorizontalScrollBarEnabled()} and 7970 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 7971 * this method returns true, and false otherwise. If the animation is 7972 * started, this method calls {@link #invalidate()}; in that case the caller 7973 * should not call {@link #invalidate()}. 7974 * </p> 7975 * 7976 * <p> 7977 * This method should be invoked everytime a subclass directly updates the 7978 * scroll parameters. 7979 * </p> 7980 * 7981 * @param startDelay the delay, in milliseconds, after which the animation 7982 * should start; when the delay is 0, the animation starts 7983 * immediately 7984 * @return true if the animation is played, false otherwise 7985 * 7986 * @see #scrollBy(int, int) 7987 * @see #scrollTo(int, int) 7988 * @see #isHorizontalScrollBarEnabled() 7989 * @see #isVerticalScrollBarEnabled() 7990 * @see #setHorizontalScrollBarEnabled(boolean) 7991 * @see #setVerticalScrollBarEnabled(boolean) 7992 */ 7993 protected boolean awakenScrollBars(int startDelay) { 7994 return awakenScrollBars(startDelay, true); 7995 } 7996 7997 /** 7998 * <p> 7999 * Trigger the scrollbars to draw. When invoked this method starts an 8000 * animation to fade the scrollbars out after a fixed delay. If a subclass 8001 * provides animated scrolling, the start delay should equal the duration of 8002 * the scrolling animation. 8003 * </p> 8004 * 8005 * <p> 8006 * The animation starts only if at least one of the scrollbars is enabled, 8007 * as specified by {@link #isHorizontalScrollBarEnabled()} and 8008 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 8009 * this method returns true, and false otherwise. If the animation is 8010 * started, this method calls {@link #invalidate()} if the invalidate parameter 8011 * is set to true; in that case the caller 8012 * should not call {@link #invalidate()}. 8013 * </p> 8014 * 8015 * <p> 8016 * This method should be invoked everytime a subclass directly updates the 8017 * scroll parameters. 8018 * </p> 8019 * 8020 * @param startDelay the delay, in milliseconds, after which the animation 8021 * should start; when the delay is 0, the animation starts 8022 * immediately 8023 * 8024 * @param invalidate Wheter this method should call invalidate 8025 * 8026 * @return true if the animation is played, false otherwise 8027 * 8028 * @see #scrollBy(int, int) 8029 * @see #scrollTo(int, int) 8030 * @see #isHorizontalScrollBarEnabled() 8031 * @see #isVerticalScrollBarEnabled() 8032 * @see #setHorizontalScrollBarEnabled(boolean) 8033 * @see #setVerticalScrollBarEnabled(boolean) 8034 */ 8035 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 8036 final ScrollabilityCache scrollCache = mScrollCache; 8037 8038 if (scrollCache == null || !scrollCache.fadeScrollBars) { 8039 return false; 8040 } 8041 8042 if (scrollCache.scrollBar == null) { 8043 scrollCache.scrollBar = new ScrollBarDrawable(); 8044 } 8045 8046 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 8047 8048 if (invalidate) { 8049 // Invalidate to show the scrollbars 8050 invalidate(true); 8051 } 8052 8053 if (scrollCache.state == ScrollabilityCache.OFF) { 8054 // FIXME: this is copied from WindowManagerService. 8055 // We should get this value from the system when it 8056 // is possible to do so. 8057 final int KEY_REPEAT_FIRST_DELAY = 750; 8058 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 8059 } 8060 8061 // Tell mScrollCache when we should start fading. This may 8062 // extend the fade start time if one was already scheduled 8063 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 8064 scrollCache.fadeStartTime = fadeStartTime; 8065 scrollCache.state = ScrollabilityCache.ON; 8066 8067 // Schedule our fader to run, unscheduling any old ones first 8068 if (mAttachInfo != null) { 8069 mAttachInfo.mHandler.removeCallbacks(scrollCache); 8070 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 8071 } 8072 8073 return true; 8074 } 8075 8076 return false; 8077 } 8078 8079 /** 8080 * Do not invalidate views which are not visible and which are not running an animation. They 8081 * will not get drawn and they should not set dirty flags as if they will be drawn 8082 */ 8083 private boolean skipInvalidate() { 8084 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 8085 (!(mParent instanceof ViewGroup) || 8086 !((ViewGroup) mParent).isViewTransitioning(this)); 8087 } 8088 /** 8089 * Mark the the area defined by dirty as needing to be drawn. If the view is 8090 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point 8091 * in the future. This must be called from a UI thread. To call from a non-UI 8092 * thread, call {@link #postInvalidate()}. 8093 * 8094 * WARNING: This method is destructive to dirty. 8095 * @param dirty the rectangle representing the bounds of the dirty region 8096 */ 8097 public void invalidate(Rect dirty) { 8098 if (ViewDebug.TRACE_HIERARCHY) { 8099 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 8100 } 8101 8102 if (skipInvalidate()) { 8103 return; 8104 } 8105 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 8106 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID || 8107 (mPrivateFlags & INVALIDATED) != INVALIDATED) { 8108 mPrivateFlags &= ~DRAWING_CACHE_VALID; 8109 mPrivateFlags |= INVALIDATED; 8110 final ViewParent p = mParent; 8111 final AttachInfo ai = mAttachInfo; 8112 //noinspection PointlessBooleanExpression,ConstantConditions 8113 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 8114 if (p != null && ai != null && ai.mHardwareAccelerated) { 8115 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 8116 // with a null dirty rect, which tells the ViewAncestor to redraw everything 8117 p.invalidateChild(this, null); 8118 return; 8119 } 8120 } 8121 if (p != null && ai != null) { 8122 final int scrollX = mScrollX; 8123 final int scrollY = mScrollY; 8124 final Rect r = ai.mTmpInvalRect; 8125 r.set(dirty.left - scrollX, dirty.top - scrollY, 8126 dirty.right - scrollX, dirty.bottom - scrollY); 8127 mParent.invalidateChild(this, r); 8128 } 8129 } 8130 } 8131 8132 /** 8133 * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn. 8134 * The coordinates of the dirty rect are relative to the view. 8135 * If the view is visible, {@link #onDraw(android.graphics.Canvas)} 8136 * will be called at some point in the future. This must be called from 8137 * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}. 8138 * @param l the left position of the dirty region 8139 * @param t the top position of the dirty region 8140 * @param r the right position of the dirty region 8141 * @param b the bottom position of the dirty region 8142 */ 8143 public void invalidate(int l, int t, int r, int b) { 8144 if (ViewDebug.TRACE_HIERARCHY) { 8145 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 8146 } 8147 8148 if (skipInvalidate()) { 8149 return; 8150 } 8151 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 8152 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID || 8153 (mPrivateFlags & INVALIDATED) != INVALIDATED) { 8154 mPrivateFlags &= ~DRAWING_CACHE_VALID; 8155 mPrivateFlags |= INVALIDATED; 8156 final ViewParent p = mParent; 8157 final AttachInfo ai = mAttachInfo; 8158 //noinspection PointlessBooleanExpression,ConstantConditions 8159 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 8160 if (p != null && ai != null && ai.mHardwareAccelerated) { 8161 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 8162 // with a null dirty rect, which tells the ViewAncestor to redraw everything 8163 p.invalidateChild(this, null); 8164 return; 8165 } 8166 } 8167 if (p != null && ai != null && l < r && t < b) { 8168 final int scrollX = mScrollX; 8169 final int scrollY = mScrollY; 8170 final Rect tmpr = ai.mTmpInvalRect; 8171 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY); 8172 p.invalidateChild(this, tmpr); 8173 } 8174 } 8175 } 8176 8177 /** 8178 * Invalidate the whole view. If the view is visible, 8179 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 8180 * the future. This must be called from a UI thread. To call from a non-UI thread, 8181 * call {@link #postInvalidate()}. 8182 */ 8183 public void invalidate() { 8184 invalidate(true); 8185 } 8186 8187 /** 8188 * This is where the invalidate() work actually happens. A full invalidate() 8189 * causes the drawing cache to be invalidated, but this function can be called with 8190 * invalidateCache set to false to skip that invalidation step for cases that do not 8191 * need it (for example, a component that remains at the same dimensions with the same 8192 * content). 8193 * 8194 * @param invalidateCache Whether the drawing cache for this view should be invalidated as 8195 * well. This is usually true for a full invalidate, but may be set to false if the 8196 * View's contents or dimensions have not changed. 8197 */ 8198 void invalidate(boolean invalidateCache) { 8199 if (ViewDebug.TRACE_HIERARCHY) { 8200 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 8201 } 8202 8203 if (skipInvalidate()) { 8204 return; 8205 } 8206 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 8207 (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) || 8208 (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) { 8209 mLastIsOpaque = isOpaque(); 8210 mPrivateFlags &= ~DRAWN; 8211 if (invalidateCache) { 8212 mPrivateFlags |= INVALIDATED; 8213 mPrivateFlags &= ~DRAWING_CACHE_VALID; 8214 } 8215 final AttachInfo ai = mAttachInfo; 8216 final ViewParent p = mParent; 8217 //noinspection PointlessBooleanExpression,ConstantConditions 8218 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 8219 if (p != null && ai != null && ai.mHardwareAccelerated) { 8220 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 8221 // with a null dirty rect, which tells the ViewAncestor to redraw everything 8222 p.invalidateChild(this, null); 8223 return; 8224 } 8225 } 8226 8227 if (p != null && ai != null) { 8228 final Rect r = ai.mTmpInvalRect; 8229 r.set(0, 0, mRight - mLeft, mBottom - mTop); 8230 // Don't call invalidate -- we don't want to internally scroll 8231 // our own bounds 8232 p.invalidateChild(this, r); 8233 } 8234 } 8235 } 8236 8237 /** 8238 * @hide 8239 */ 8240 public void fastInvalidate() { 8241 if (skipInvalidate()) { 8242 return; 8243 } 8244 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 8245 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID || 8246 (mPrivateFlags & INVALIDATED) != INVALIDATED) { 8247 if (mParent instanceof View) { 8248 ((View) mParent).mPrivateFlags |= INVALIDATED; 8249 } 8250 mPrivateFlags &= ~DRAWN; 8251 mPrivateFlags |= INVALIDATED; 8252 mPrivateFlags &= ~DRAWING_CACHE_VALID; 8253 if (mParent != null && mAttachInfo != null) { 8254 if (mAttachInfo.mHardwareAccelerated) { 8255 mParent.invalidateChild(this, null); 8256 } else { 8257 final Rect r = mAttachInfo.mTmpInvalRect; 8258 r.set(0, 0, mRight - mLeft, mBottom - mTop); 8259 // Don't call invalidate -- we don't want to internally scroll 8260 // our own bounds 8261 mParent.invalidateChild(this, r); 8262 } 8263 } 8264 } 8265 } 8266 8267 /** 8268 * Used to indicate that the parent of this view should clear its caches. This functionality 8269 * is used to force the parent to rebuild its display list (when hardware-accelerated), 8270 * which is necessary when various parent-managed properties of the view change, such as 8271 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 8272 * clears the parent caches and does not causes an invalidate event. 8273 * 8274 * @hide 8275 */ 8276 protected void invalidateParentCaches() { 8277 if (mParent instanceof View) { 8278 ((View) mParent).mPrivateFlags |= INVALIDATED; 8279 } 8280 } 8281 8282 /** 8283 * Used to indicate that the parent of this view should be invalidated. This functionality 8284 * is used to force the parent to rebuild its display list (when hardware-accelerated), 8285 * which is necessary when various parent-managed properties of the view change, such as 8286 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 8287 * an invalidation event to the parent. 8288 * 8289 * @hide 8290 */ 8291 protected void invalidateParentIfNeeded() { 8292 if (isHardwareAccelerated() && mParent instanceof View) { 8293 ((View) mParent).invalidate(true); 8294 } 8295 } 8296 8297 /** 8298 * Indicates whether this View is opaque. An opaque View guarantees that it will 8299 * draw all the pixels overlapping its bounds using a fully opaque color. 8300 * 8301 * Subclasses of View should override this method whenever possible to indicate 8302 * whether an instance is opaque. Opaque Views are treated in a special way by 8303 * the View hierarchy, possibly allowing it to perform optimizations during 8304 * invalidate/draw passes. 8305 * 8306 * @return True if this View is guaranteed to be fully opaque, false otherwise. 8307 */ 8308 @ViewDebug.ExportedProperty(category = "drawing") 8309 public boolean isOpaque() { 8310 return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK && 8311 (mAlpha >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD); 8312 } 8313 8314 /** 8315 * @hide 8316 */ 8317 protected void computeOpaqueFlags() { 8318 // Opaque if: 8319 // - Has a background 8320 // - Background is opaque 8321 // - Doesn't have scrollbars or scrollbars are inside overlay 8322 8323 if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) { 8324 mPrivateFlags |= OPAQUE_BACKGROUND; 8325 } else { 8326 mPrivateFlags &= ~OPAQUE_BACKGROUND; 8327 } 8328 8329 final int flags = mViewFlags; 8330 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 8331 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) { 8332 mPrivateFlags |= OPAQUE_SCROLLBARS; 8333 } else { 8334 mPrivateFlags &= ~OPAQUE_SCROLLBARS; 8335 } 8336 } 8337 8338 /** 8339 * @hide 8340 */ 8341 protected boolean hasOpaqueScrollbars() { 8342 return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS; 8343 } 8344 8345 /** 8346 * @return A handler associated with the thread running the View. This 8347 * handler can be used to pump events in the UI events queue. 8348 */ 8349 public Handler getHandler() { 8350 if (mAttachInfo != null) { 8351 return mAttachInfo.mHandler; 8352 } 8353 return null; 8354 } 8355 8356 /** 8357 * <p>Causes the Runnable to be added to the message queue. 8358 * The runnable will be run on the user interface thread.</p> 8359 * 8360 * <p>This method can be invoked from outside of the UI thread 8361 * only when this View is attached to a window.</p> 8362 * 8363 * @param action The Runnable that will be executed. 8364 * 8365 * @return Returns true if the Runnable was successfully placed in to the 8366 * message queue. Returns false on failure, usually because the 8367 * looper processing the message queue is exiting. 8368 */ 8369 public boolean post(Runnable action) { 8370 Handler handler; 8371 AttachInfo attachInfo = mAttachInfo; 8372 if (attachInfo != null) { 8373 handler = attachInfo.mHandler; 8374 } else { 8375 // Assume that post will succeed later 8376 ViewRootImpl.getRunQueue().post(action); 8377 return true; 8378 } 8379 8380 return handler.post(action); 8381 } 8382 8383 /** 8384 * <p>Causes the Runnable to be added to the message queue, to be run 8385 * after the specified amount of time elapses. 8386 * The runnable will be run on the user interface thread.</p> 8387 * 8388 * <p>This method can be invoked from outside of the UI thread 8389 * only when this View is attached to a window.</p> 8390 * 8391 * @param action The Runnable that will be executed. 8392 * @param delayMillis The delay (in milliseconds) until the Runnable 8393 * will be executed. 8394 * 8395 * @return true if the Runnable was successfully placed in to the 8396 * message queue. Returns false on failure, usually because the 8397 * looper processing the message queue is exiting. Note that a 8398 * result of true does not mean the Runnable will be processed -- 8399 * if the looper is quit before the delivery time of the message 8400 * occurs then the message will be dropped. 8401 */ 8402 public boolean postDelayed(Runnable action, long delayMillis) { 8403 Handler handler; 8404 AttachInfo attachInfo = mAttachInfo; 8405 if (attachInfo != null) { 8406 handler = attachInfo.mHandler; 8407 } else { 8408 // Assume that post will succeed later 8409 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 8410 return true; 8411 } 8412 8413 return handler.postDelayed(action, delayMillis); 8414 } 8415 8416 /** 8417 * <p>Removes the specified Runnable from the message queue.</p> 8418 * 8419 * <p>This method can be invoked from outside of the UI thread 8420 * only when this View is attached to a window.</p> 8421 * 8422 * @param action The Runnable to remove from the message handling queue 8423 * 8424 * @return true if this view could ask the Handler to remove the Runnable, 8425 * false otherwise. When the returned value is true, the Runnable 8426 * may or may not have been actually removed from the message queue 8427 * (for instance, if the Runnable was not in the queue already.) 8428 */ 8429 public boolean removeCallbacks(Runnable action) { 8430 Handler handler; 8431 AttachInfo attachInfo = mAttachInfo; 8432 if (attachInfo != null) { 8433 handler = attachInfo.mHandler; 8434 } else { 8435 // Assume that post will succeed later 8436 ViewRootImpl.getRunQueue().removeCallbacks(action); 8437 return true; 8438 } 8439 8440 handler.removeCallbacks(action); 8441 return true; 8442 } 8443 8444 /** 8445 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 8446 * Use this to invalidate the View from a non-UI thread.</p> 8447 * 8448 * <p>This method can be invoked from outside of the UI thread 8449 * only when this View is attached to a window.</p> 8450 * 8451 * @see #invalidate() 8452 */ 8453 public void postInvalidate() { 8454 postInvalidateDelayed(0); 8455 } 8456 8457 /** 8458 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 8459 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 8460 * 8461 * <p>This method can be invoked from outside of the UI thread 8462 * only when this View is attached to a window.</p> 8463 * 8464 * @param left The left coordinate of the rectangle to invalidate. 8465 * @param top The top coordinate of the rectangle to invalidate. 8466 * @param right The right coordinate of the rectangle to invalidate. 8467 * @param bottom The bottom coordinate of the rectangle to invalidate. 8468 * 8469 * @see #invalidate(int, int, int, int) 8470 * @see #invalidate(Rect) 8471 */ 8472 public void postInvalidate(int left, int top, int right, int bottom) { 8473 postInvalidateDelayed(0, left, top, right, bottom); 8474 } 8475 8476 /** 8477 * <p>Cause an invalidate to happen on a subsequent cycle through the event 8478 * loop. Waits for the specified amount of time.</p> 8479 * 8480 * <p>This method can be invoked from outside of the UI thread 8481 * only when this View is attached to a window.</p> 8482 * 8483 * @param delayMilliseconds the duration in milliseconds to delay the 8484 * invalidation by 8485 */ 8486 public void postInvalidateDelayed(long delayMilliseconds) { 8487 // We try only with the AttachInfo because there's no point in invalidating 8488 // if we are not attached to our window 8489 AttachInfo attachInfo = mAttachInfo; 8490 if (attachInfo != null) { 8491 Message msg = Message.obtain(); 8492 msg.what = AttachInfo.INVALIDATE_MSG; 8493 msg.obj = this; 8494 attachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds); 8495 } 8496 } 8497 8498 /** 8499 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 8500 * through the event loop. Waits for the specified amount of time.</p> 8501 * 8502 * <p>This method can be invoked from outside of the UI thread 8503 * only when this View is attached to a window.</p> 8504 * 8505 * @param delayMilliseconds the duration in milliseconds to delay the 8506 * invalidation by 8507 * @param left The left coordinate of the rectangle to invalidate. 8508 * @param top The top coordinate of the rectangle to invalidate. 8509 * @param right The right coordinate of the rectangle to invalidate. 8510 * @param bottom The bottom coordinate of the rectangle to invalidate. 8511 */ 8512 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 8513 int right, int bottom) { 8514 8515 // We try only with the AttachInfo because there's no point in invalidating 8516 // if we are not attached to our window 8517 AttachInfo attachInfo = mAttachInfo; 8518 if (attachInfo != null) { 8519 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire(); 8520 info.target = this; 8521 info.left = left; 8522 info.top = top; 8523 info.right = right; 8524 info.bottom = bottom; 8525 8526 final Message msg = Message.obtain(); 8527 msg.what = AttachInfo.INVALIDATE_RECT_MSG; 8528 msg.obj = info; 8529 attachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds); 8530 } 8531 } 8532 8533 /** 8534 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 8535 * This event is sent at most once every 8536 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 8537 */ 8538 private void postSendViewScrolledAccessibilityEventCallback() { 8539 if (mSendViewScrolledAccessibilityEvent == null) { 8540 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 8541 } 8542 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 8543 mSendViewScrolledAccessibilityEvent.mIsPending = true; 8544 postDelayed(mSendViewScrolledAccessibilityEvent, 8545 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 8546 } 8547 } 8548 8549 /** 8550 * Called by a parent to request that a child update its values for mScrollX 8551 * and mScrollY if necessary. This will typically be done if the child is 8552 * animating a scroll using a {@link android.widget.Scroller Scroller} 8553 * object. 8554 */ 8555 public void computeScroll() { 8556 } 8557 8558 /** 8559 * <p>Indicate whether the horizontal edges are faded when the view is 8560 * scrolled horizontally.</p> 8561 * 8562 * @return true if the horizontal edges should are faded on scroll, false 8563 * otherwise 8564 * 8565 * @see #setHorizontalFadingEdgeEnabled(boolean) 8566 * @attr ref android.R.styleable#View_fadingEdge 8567 */ 8568 public boolean isHorizontalFadingEdgeEnabled() { 8569 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 8570 } 8571 8572 /** 8573 * <p>Define whether the horizontal edges should be faded when this view 8574 * is scrolled horizontally.</p> 8575 * 8576 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 8577 * be faded when the view is scrolled 8578 * horizontally 8579 * 8580 * @see #isHorizontalFadingEdgeEnabled() 8581 * @attr ref android.R.styleable#View_fadingEdge 8582 */ 8583 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 8584 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 8585 if (horizontalFadingEdgeEnabled) { 8586 initScrollCache(); 8587 } 8588 8589 mViewFlags ^= FADING_EDGE_HORIZONTAL; 8590 } 8591 } 8592 8593 /** 8594 * <p>Indicate whether the vertical edges are faded when the view is 8595 * scrolled horizontally.</p> 8596 * 8597 * @return true if the vertical edges should are faded on scroll, false 8598 * otherwise 8599 * 8600 * @see #setVerticalFadingEdgeEnabled(boolean) 8601 * @attr ref android.R.styleable#View_fadingEdge 8602 */ 8603 public boolean isVerticalFadingEdgeEnabled() { 8604 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 8605 } 8606 8607 /** 8608 * <p>Define whether the vertical edges should be faded when this view 8609 * is scrolled vertically.</p> 8610 * 8611 * @param verticalFadingEdgeEnabled true if the vertical edges should 8612 * be faded when the view is scrolled 8613 * vertically 8614 * 8615 * @see #isVerticalFadingEdgeEnabled() 8616 * @attr ref android.R.styleable#View_fadingEdge 8617 */ 8618 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 8619 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 8620 if (verticalFadingEdgeEnabled) { 8621 initScrollCache(); 8622 } 8623 8624 mViewFlags ^= FADING_EDGE_VERTICAL; 8625 } 8626 } 8627 8628 /** 8629 * Returns the strength, or intensity, of the top faded edge. The strength is 8630 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 8631 * returns 0.0 or 1.0 but no value in between. 8632 * 8633 * Subclasses should override this method to provide a smoother fade transition 8634 * when scrolling occurs. 8635 * 8636 * @return the intensity of the top fade as a float between 0.0f and 1.0f 8637 */ 8638 protected float getTopFadingEdgeStrength() { 8639 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 8640 } 8641 8642 /** 8643 * Returns the strength, or intensity, of the bottom faded edge. The strength is 8644 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 8645 * returns 0.0 or 1.0 but no value in between. 8646 * 8647 * Subclasses should override this method to provide a smoother fade transition 8648 * when scrolling occurs. 8649 * 8650 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 8651 */ 8652 protected float getBottomFadingEdgeStrength() { 8653 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 8654 computeVerticalScrollRange() ? 1.0f : 0.0f; 8655 } 8656 8657 /** 8658 * Returns the strength, or intensity, of the left faded edge. The strength is 8659 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 8660 * returns 0.0 or 1.0 but no value in between. 8661 * 8662 * Subclasses should override this method to provide a smoother fade transition 8663 * when scrolling occurs. 8664 * 8665 * @return the intensity of the left fade as a float between 0.0f and 1.0f 8666 */ 8667 protected float getLeftFadingEdgeStrength() { 8668 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 8669 } 8670 8671 /** 8672 * Returns the strength, or intensity, of the right faded edge. The strength is 8673 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 8674 * returns 0.0 or 1.0 but no value in between. 8675 * 8676 * Subclasses should override this method to provide a smoother fade transition 8677 * when scrolling occurs. 8678 * 8679 * @return the intensity of the right fade as a float between 0.0f and 1.0f 8680 */ 8681 protected float getRightFadingEdgeStrength() { 8682 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 8683 computeHorizontalScrollRange() ? 1.0f : 0.0f; 8684 } 8685 8686 /** 8687 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 8688 * scrollbar is not drawn by default.</p> 8689 * 8690 * @return true if the horizontal scrollbar should be painted, false 8691 * otherwise 8692 * 8693 * @see #setHorizontalScrollBarEnabled(boolean) 8694 */ 8695 public boolean isHorizontalScrollBarEnabled() { 8696 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 8697 } 8698 8699 /** 8700 * <p>Define whether the horizontal scrollbar should be drawn or not. The 8701 * scrollbar is not drawn by default.</p> 8702 * 8703 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 8704 * be painted 8705 * 8706 * @see #isHorizontalScrollBarEnabled() 8707 */ 8708 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 8709 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 8710 mViewFlags ^= SCROLLBARS_HORIZONTAL; 8711 computeOpaqueFlags(); 8712 resolvePadding(); 8713 } 8714 } 8715 8716 /** 8717 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 8718 * scrollbar is not drawn by default.</p> 8719 * 8720 * @return true if the vertical scrollbar should be painted, false 8721 * otherwise 8722 * 8723 * @see #setVerticalScrollBarEnabled(boolean) 8724 */ 8725 public boolean isVerticalScrollBarEnabled() { 8726 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 8727 } 8728 8729 /** 8730 * <p>Define whether the vertical scrollbar should be drawn or not. The 8731 * scrollbar is not drawn by default.</p> 8732 * 8733 * @param verticalScrollBarEnabled true if the vertical scrollbar should 8734 * be painted 8735 * 8736 * @see #isVerticalScrollBarEnabled() 8737 */ 8738 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 8739 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 8740 mViewFlags ^= SCROLLBARS_VERTICAL; 8741 computeOpaqueFlags(); 8742 resolvePadding(); 8743 } 8744 } 8745 8746 /** 8747 * @hide 8748 */ 8749 protected void recomputePadding() { 8750 setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 8751 } 8752 8753 /** 8754 * Define whether scrollbars will fade when the view is not scrolling. 8755 * 8756 * @param fadeScrollbars wheter to enable fading 8757 * 8758 */ 8759 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 8760 initScrollCache(); 8761 final ScrollabilityCache scrollabilityCache = mScrollCache; 8762 scrollabilityCache.fadeScrollBars = fadeScrollbars; 8763 if (fadeScrollbars) { 8764 scrollabilityCache.state = ScrollabilityCache.OFF; 8765 } else { 8766 scrollabilityCache.state = ScrollabilityCache.ON; 8767 } 8768 } 8769 8770 /** 8771 * 8772 * Returns true if scrollbars will fade when this view is not scrolling 8773 * 8774 * @return true if scrollbar fading is enabled 8775 */ 8776 public boolean isScrollbarFadingEnabled() { 8777 return mScrollCache != null && mScrollCache.fadeScrollBars; 8778 } 8779 8780 /** 8781 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 8782 * inset. When inset, they add to the padding of the view. And the scrollbars 8783 * can be drawn inside the padding area or on the edge of the view. For example, 8784 * if a view has a background drawable and you want to draw the scrollbars 8785 * inside the padding specified by the drawable, you can use 8786 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 8787 * appear at the edge of the view, ignoring the padding, then you can use 8788 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 8789 * @param style the style of the scrollbars. Should be one of 8790 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 8791 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 8792 * @see #SCROLLBARS_INSIDE_OVERLAY 8793 * @see #SCROLLBARS_INSIDE_INSET 8794 * @see #SCROLLBARS_OUTSIDE_OVERLAY 8795 * @see #SCROLLBARS_OUTSIDE_INSET 8796 */ 8797 public void setScrollBarStyle(int style) { 8798 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 8799 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 8800 computeOpaqueFlags(); 8801 resolvePadding(); 8802 } 8803 } 8804 8805 /** 8806 * <p>Returns the current scrollbar style.</p> 8807 * @return the current scrollbar style 8808 * @see #SCROLLBARS_INSIDE_OVERLAY 8809 * @see #SCROLLBARS_INSIDE_INSET 8810 * @see #SCROLLBARS_OUTSIDE_OVERLAY 8811 * @see #SCROLLBARS_OUTSIDE_INSET 8812 */ 8813 @ViewDebug.ExportedProperty(mapping = { 8814 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 8815 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 8816 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 8817 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 8818 }) 8819 public int getScrollBarStyle() { 8820 return mViewFlags & SCROLLBARS_STYLE_MASK; 8821 } 8822 8823 /** 8824 * <p>Compute the horizontal range that the horizontal scrollbar 8825 * represents.</p> 8826 * 8827 * <p>The range is expressed in arbitrary units that must be the same as the 8828 * units used by {@link #computeHorizontalScrollExtent()} and 8829 * {@link #computeHorizontalScrollOffset()}.</p> 8830 * 8831 * <p>The default range is the drawing width of this view.</p> 8832 * 8833 * @return the total horizontal range represented by the horizontal 8834 * scrollbar 8835 * 8836 * @see #computeHorizontalScrollExtent() 8837 * @see #computeHorizontalScrollOffset() 8838 * @see android.widget.ScrollBarDrawable 8839 */ 8840 protected int computeHorizontalScrollRange() { 8841 return getWidth(); 8842 } 8843 8844 /** 8845 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 8846 * within the horizontal range. This value is used to compute the position 8847 * of the thumb within the scrollbar's track.</p> 8848 * 8849 * <p>The range is expressed in arbitrary units that must be the same as the 8850 * units used by {@link #computeHorizontalScrollRange()} and 8851 * {@link #computeHorizontalScrollExtent()}.</p> 8852 * 8853 * <p>The default offset is the scroll offset of this view.</p> 8854 * 8855 * @return the horizontal offset of the scrollbar's thumb 8856 * 8857 * @see #computeHorizontalScrollRange() 8858 * @see #computeHorizontalScrollExtent() 8859 * @see android.widget.ScrollBarDrawable 8860 */ 8861 protected int computeHorizontalScrollOffset() { 8862 return mScrollX; 8863 } 8864 8865 /** 8866 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 8867 * within the horizontal range. This value is used to compute the length 8868 * of the thumb within the scrollbar's track.</p> 8869 * 8870 * <p>The range is expressed in arbitrary units that must be the same as the 8871 * units used by {@link #computeHorizontalScrollRange()} and 8872 * {@link #computeHorizontalScrollOffset()}.</p> 8873 * 8874 * <p>The default extent is the drawing width of this view.</p> 8875 * 8876 * @return the horizontal extent of the scrollbar's thumb 8877 * 8878 * @see #computeHorizontalScrollRange() 8879 * @see #computeHorizontalScrollOffset() 8880 * @see android.widget.ScrollBarDrawable 8881 */ 8882 protected int computeHorizontalScrollExtent() { 8883 return getWidth(); 8884 } 8885 8886 /** 8887 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 8888 * 8889 * <p>The range is expressed in arbitrary units that must be the same as the 8890 * units used by {@link #computeVerticalScrollExtent()} and 8891 * {@link #computeVerticalScrollOffset()}.</p> 8892 * 8893 * @return the total vertical range represented by the vertical scrollbar 8894 * 8895 * <p>The default range is the drawing height of this view.</p> 8896 * 8897 * @see #computeVerticalScrollExtent() 8898 * @see #computeVerticalScrollOffset() 8899 * @see android.widget.ScrollBarDrawable 8900 */ 8901 protected int computeVerticalScrollRange() { 8902 return getHeight(); 8903 } 8904 8905 /** 8906 * <p>Compute the vertical offset of the vertical scrollbar's thumb 8907 * within the horizontal range. This value is used to compute the position 8908 * of the thumb within the scrollbar's track.</p> 8909 * 8910 * <p>The range is expressed in arbitrary units that must be the same as the 8911 * units used by {@link #computeVerticalScrollRange()} and 8912 * {@link #computeVerticalScrollExtent()}.</p> 8913 * 8914 * <p>The default offset is the scroll offset of this view.</p> 8915 * 8916 * @return the vertical offset of the scrollbar's thumb 8917 * 8918 * @see #computeVerticalScrollRange() 8919 * @see #computeVerticalScrollExtent() 8920 * @see android.widget.ScrollBarDrawable 8921 */ 8922 protected int computeVerticalScrollOffset() { 8923 return mScrollY; 8924 } 8925 8926 /** 8927 * <p>Compute the vertical extent of the horizontal scrollbar's thumb 8928 * within the vertical range. This value is used to compute the length 8929 * of the thumb within the scrollbar's track.</p> 8930 * 8931 * <p>The range is expressed in arbitrary units that must be the same as the 8932 * units used by {@link #computeVerticalScrollRange()} and 8933 * {@link #computeVerticalScrollOffset()}.</p> 8934 * 8935 * <p>The default extent is the drawing height of this view.</p> 8936 * 8937 * @return the vertical extent of the scrollbar's thumb 8938 * 8939 * @see #computeVerticalScrollRange() 8940 * @see #computeVerticalScrollOffset() 8941 * @see android.widget.ScrollBarDrawable 8942 */ 8943 protected int computeVerticalScrollExtent() { 8944 return getHeight(); 8945 } 8946 8947 /** 8948 * Check if this view can be scrolled horizontally in a certain direction. 8949 * 8950 * @param direction Negative to check scrolling left, positive to check scrolling right. 8951 * @return true if this view can be scrolled in the specified direction, false otherwise. 8952 */ 8953 public boolean canScrollHorizontally(int direction) { 8954 final int offset = computeHorizontalScrollOffset(); 8955 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 8956 if (range == 0) return false; 8957 if (direction < 0) { 8958 return offset > 0; 8959 } else { 8960 return offset < range - 1; 8961 } 8962 } 8963 8964 /** 8965 * Check if this view can be scrolled vertically in a certain direction. 8966 * 8967 * @param direction Negative to check scrolling up, positive to check scrolling down. 8968 * @return true if this view can be scrolled in the specified direction, false otherwise. 8969 */ 8970 public boolean canScrollVertically(int direction) { 8971 final int offset = computeVerticalScrollOffset(); 8972 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 8973 if (range == 0) return false; 8974 if (direction < 0) { 8975 return offset > 0; 8976 } else { 8977 return offset < range - 1; 8978 } 8979 } 8980 8981 /** 8982 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 8983 * scrollbars are painted only if they have been awakened first.</p> 8984 * 8985 * @param canvas the canvas on which to draw the scrollbars 8986 * 8987 * @see #awakenScrollBars(int) 8988 */ 8989 protected final void onDrawScrollBars(Canvas canvas) { 8990 // scrollbars are drawn only when the animation is running 8991 final ScrollabilityCache cache = mScrollCache; 8992 if (cache != null) { 8993 8994 int state = cache.state; 8995 8996 if (state == ScrollabilityCache.OFF) { 8997 return; 8998 } 8999 9000 boolean invalidate = false; 9001 9002 if (state == ScrollabilityCache.FADING) { 9003 // We're fading -- get our fade interpolation 9004 if (cache.interpolatorValues == null) { 9005 cache.interpolatorValues = new float[1]; 9006 } 9007 9008 float[] values = cache.interpolatorValues; 9009 9010 // Stops the animation if we're done 9011 if (cache.scrollBarInterpolator.timeToValues(values) == 9012 Interpolator.Result.FREEZE_END) { 9013 cache.state = ScrollabilityCache.OFF; 9014 } else { 9015 cache.scrollBar.setAlpha(Math.round(values[0])); 9016 } 9017 9018 // This will make the scroll bars inval themselves after 9019 // drawing. We only want this when we're fading so that 9020 // we prevent excessive redraws 9021 invalidate = true; 9022 } else { 9023 // We're just on -- but we may have been fading before so 9024 // reset alpha 9025 cache.scrollBar.setAlpha(255); 9026 } 9027 9028 9029 final int viewFlags = mViewFlags; 9030 9031 final boolean drawHorizontalScrollBar = 9032 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 9033 final boolean drawVerticalScrollBar = 9034 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 9035 && !isVerticalScrollBarHidden(); 9036 9037 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 9038 final int width = mRight - mLeft; 9039 final int height = mBottom - mTop; 9040 9041 final ScrollBarDrawable scrollBar = cache.scrollBar; 9042 9043 final int scrollX = mScrollX; 9044 final int scrollY = mScrollY; 9045 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 9046 9047 int left, top, right, bottom; 9048 9049 if (drawHorizontalScrollBar) { 9050 int size = scrollBar.getSize(false); 9051 if (size <= 0) { 9052 size = cache.scrollBarSize; 9053 } 9054 9055 scrollBar.setParameters(computeHorizontalScrollRange(), 9056 computeHorizontalScrollOffset(), 9057 computeHorizontalScrollExtent(), false); 9058 final int verticalScrollBarGap = drawVerticalScrollBar ? 9059 getVerticalScrollbarWidth() : 0; 9060 top = scrollY + height - size - (mUserPaddingBottom & inside); 9061 left = scrollX + (mPaddingLeft & inside); 9062 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 9063 bottom = top + size; 9064 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 9065 if (invalidate) { 9066 invalidate(left, top, right, bottom); 9067 } 9068 } 9069 9070 if (drawVerticalScrollBar) { 9071 int size = scrollBar.getSize(true); 9072 if (size <= 0) { 9073 size = cache.scrollBarSize; 9074 } 9075 9076 scrollBar.setParameters(computeVerticalScrollRange(), 9077 computeVerticalScrollOffset(), 9078 computeVerticalScrollExtent(), true); 9079 switch (mVerticalScrollbarPosition) { 9080 default: 9081 case SCROLLBAR_POSITION_DEFAULT: 9082 case SCROLLBAR_POSITION_RIGHT: 9083 left = scrollX + width - size - (mUserPaddingRight & inside); 9084 break; 9085 case SCROLLBAR_POSITION_LEFT: 9086 left = scrollX + (mUserPaddingLeft & inside); 9087 break; 9088 } 9089 top = scrollY + (mPaddingTop & inside); 9090 right = left + size; 9091 bottom = scrollY + height - (mUserPaddingBottom & inside); 9092 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 9093 if (invalidate) { 9094 invalidate(left, top, right, bottom); 9095 } 9096 } 9097 } 9098 } 9099 } 9100 9101 /** 9102 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 9103 * FastScroller is visible. 9104 * @return whether to temporarily hide the vertical scrollbar 9105 * @hide 9106 */ 9107 protected boolean isVerticalScrollBarHidden() { 9108 return false; 9109 } 9110 9111 /** 9112 * <p>Draw the horizontal scrollbar if 9113 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 9114 * 9115 * @param canvas the canvas on which to draw the scrollbar 9116 * @param scrollBar the scrollbar's drawable 9117 * 9118 * @see #isHorizontalScrollBarEnabled() 9119 * @see #computeHorizontalScrollRange() 9120 * @see #computeHorizontalScrollExtent() 9121 * @see #computeHorizontalScrollOffset() 9122 * @see android.widget.ScrollBarDrawable 9123 * @hide 9124 */ 9125 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 9126 int l, int t, int r, int b) { 9127 scrollBar.setBounds(l, t, r, b); 9128 scrollBar.draw(canvas); 9129 } 9130 9131 /** 9132 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 9133 * returns true.</p> 9134 * 9135 * @param canvas the canvas on which to draw the scrollbar 9136 * @param scrollBar the scrollbar's drawable 9137 * 9138 * @see #isVerticalScrollBarEnabled() 9139 * @see #computeVerticalScrollRange() 9140 * @see #computeVerticalScrollExtent() 9141 * @see #computeVerticalScrollOffset() 9142 * @see android.widget.ScrollBarDrawable 9143 * @hide 9144 */ 9145 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 9146 int l, int t, int r, int b) { 9147 scrollBar.setBounds(l, t, r, b); 9148 scrollBar.draw(canvas); 9149 } 9150 9151 /** 9152 * Implement this to do your drawing. 9153 * 9154 * @param canvas the canvas on which the background will be drawn 9155 */ 9156 protected void onDraw(Canvas canvas) { 9157 } 9158 9159 /* 9160 * Caller is responsible for calling requestLayout if necessary. 9161 * (This allows addViewInLayout to not request a new layout.) 9162 */ 9163 void assignParent(ViewParent parent) { 9164 if (mParent == null) { 9165 mParent = parent; 9166 } else if (parent == null) { 9167 mParent = null; 9168 } else { 9169 throw new RuntimeException("view " + this + " being added, but" 9170 + " it already has a parent"); 9171 } 9172 } 9173 9174 /** 9175 * This is called when the view is attached to a window. At this point it 9176 * has a Surface and will start drawing. Note that this function is 9177 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 9178 * however it may be called any time before the first onDraw -- including 9179 * before or after {@link #onMeasure(int, int)}. 9180 * 9181 * @see #onDetachedFromWindow() 9182 */ 9183 protected void onAttachedToWindow() { 9184 if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) { 9185 mParent.requestTransparentRegion(this); 9186 } 9187 if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 9188 initialAwakenScrollBars(); 9189 mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH; 9190 } 9191 jumpDrawablesToCurrentState(); 9192 // Order is important here: LayoutDirection MUST be resolved before Padding 9193 // and TextDirection 9194 resolveLayoutDirectionIfNeeded(); 9195 resolvePadding(); 9196 resolveTextDirection(); 9197 if (isFocused()) { 9198 InputMethodManager imm = InputMethodManager.peekInstance(); 9199 imm.focusIn(this); 9200 } 9201 } 9202 9203 /** 9204 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 9205 * that the parent directionality can and will be resolved before its children. 9206 */ 9207 private void resolveLayoutDirectionIfNeeded() { 9208 // Do not resolve if it is not needed 9209 if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) == LAYOUT_DIRECTION_RESOLVED) return; 9210 9211 // Clear any previous layout direction resolution 9212 mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_RTL; 9213 9214 // Reset also TextDirection as a change into LayoutDirection may impact the selected 9215 // TextDirectionHeuristic 9216 resetResolvedTextDirection(); 9217 9218 // Set resolved depending on layout direction 9219 switch (getLayoutDirection()) { 9220 case LAYOUT_DIRECTION_INHERIT: 9221 // We cannot do the resolution if there is no parent 9222 if (mParent == null) return; 9223 9224 // If this is root view, no need to look at parent's layout dir. 9225 if (mParent instanceof ViewGroup) { 9226 ViewGroup viewGroup = ((ViewGroup) mParent); 9227 9228 // Check if the parent view group can resolve 9229 if (! viewGroup.canResolveLayoutDirection()) { 9230 return; 9231 } 9232 if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) { 9233 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL; 9234 } 9235 } 9236 break; 9237 case LAYOUT_DIRECTION_RTL: 9238 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL; 9239 break; 9240 case LAYOUT_DIRECTION_LOCALE: 9241 if(isLayoutDirectionRtl(Locale.getDefault())) { 9242 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL; 9243 } 9244 break; 9245 default: 9246 // Nothing to do, LTR by default 9247 } 9248 9249 // Set to resolved 9250 mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED; 9251 } 9252 9253 /** 9254 * @hide 9255 */ 9256 protected void resolvePadding() { 9257 // If the user specified the absolute padding (either with android:padding or 9258 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise 9259 // use the default padding or the padding from the background drawable 9260 // (stored at this point in mPadding*) 9261 switch (getResolvedLayoutDirection()) { 9262 case LAYOUT_DIRECTION_RTL: 9263 // Start user padding override Right user padding. Otherwise, if Right user 9264 // padding is not defined, use the default Right padding. If Right user padding 9265 // is defined, just use it. 9266 if (mUserPaddingStart >= 0) { 9267 mUserPaddingRight = mUserPaddingStart; 9268 } else if (mUserPaddingRight < 0) { 9269 mUserPaddingRight = mPaddingRight; 9270 } 9271 if (mUserPaddingEnd >= 0) { 9272 mUserPaddingLeft = mUserPaddingEnd; 9273 } else if (mUserPaddingLeft < 0) { 9274 mUserPaddingLeft = mPaddingLeft; 9275 } 9276 break; 9277 case LAYOUT_DIRECTION_LTR: 9278 default: 9279 // Start user padding override Left user padding. Otherwise, if Left user 9280 // padding is not defined, use the default left padding. If Left user padding 9281 // is defined, just use it. 9282 if (mUserPaddingStart >= 0) { 9283 mUserPaddingLeft = mUserPaddingStart; 9284 } else if (mUserPaddingLeft < 0) { 9285 mUserPaddingLeft = mPaddingLeft; 9286 } 9287 if (mUserPaddingEnd >= 0) { 9288 mUserPaddingRight = mUserPaddingEnd; 9289 } else if (mUserPaddingRight < 0) { 9290 mUserPaddingRight = mPaddingRight; 9291 } 9292 } 9293 9294 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 9295 9296 recomputePadding(); 9297 } 9298 9299 /** 9300 * Return true if layout direction resolution can be done 9301 * 9302 * @hide 9303 */ 9304 protected boolean canResolveLayoutDirection() { 9305 switch (getLayoutDirection()) { 9306 case LAYOUT_DIRECTION_INHERIT: 9307 return (mParent != null); 9308 default: 9309 return true; 9310 } 9311 } 9312 9313 /** 9314 * Reset the resolved layout direction. 9315 * 9316 * Subclasses need to override this method to clear cached information that depends on the 9317 * resolved layout direction, or to inform child views that inherit their layout direction. 9318 * Overrides must also call the superclass implementation at the start of their implementation. 9319 * 9320 * @hide 9321 */ 9322 protected void resetResolvedLayoutDirection() { 9323 // Reset the current View resolution 9324 mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED; 9325 } 9326 9327 /** 9328 * Check if a Locale is corresponding to a RTL script. 9329 * 9330 * @param locale Locale to check 9331 * @return true if a Locale is corresponding to a RTL script. 9332 * 9333 * @hide 9334 */ 9335 protected static boolean isLayoutDirectionRtl(Locale locale) { 9336 return (LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE == 9337 LocaleUtil.getLayoutDirectionFromLocale(locale)); 9338 } 9339 9340 /** 9341 * This is called when the view is detached from a window. At this point it 9342 * no longer has a surface for drawing. 9343 * 9344 * @see #onAttachedToWindow() 9345 */ 9346 protected void onDetachedFromWindow() { 9347 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT; 9348 9349 removeUnsetPressCallback(); 9350 removeLongPressCallback(); 9351 removePerformClickCallback(); 9352 removeSendViewScrolledAccessibilityEventCallback(); 9353 9354 destroyDrawingCache(); 9355 9356 destroyLayer(); 9357 9358 if (mDisplayList != null) { 9359 mDisplayList.invalidate(); 9360 } 9361 9362 if (mAttachInfo != null) { 9363 mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_MSG, this); 9364 } 9365 9366 mCurrentAnimation = null; 9367 9368 resetResolvedLayoutDirection(); 9369 resetResolvedTextDirection(); 9370 } 9371 9372 /** 9373 * @return The number of times this view has been attached to a window 9374 */ 9375 protected int getWindowAttachCount() { 9376 return mWindowAttachCount; 9377 } 9378 9379 /** 9380 * Retrieve a unique token identifying the window this view is attached to. 9381 * @return Return the window's token for use in 9382 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 9383 */ 9384 public IBinder getWindowToken() { 9385 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 9386 } 9387 9388 /** 9389 * Retrieve a unique token identifying the top-level "real" window of 9390 * the window that this view is attached to. That is, this is like 9391 * {@link #getWindowToken}, except if the window this view in is a panel 9392 * window (attached to another containing window), then the token of 9393 * the containing window is returned instead. 9394 * 9395 * @return Returns the associated window token, either 9396 * {@link #getWindowToken()} or the containing window's token. 9397 */ 9398 public IBinder getApplicationWindowToken() { 9399 AttachInfo ai = mAttachInfo; 9400 if (ai != null) { 9401 IBinder appWindowToken = ai.mPanelParentWindowToken; 9402 if (appWindowToken == null) { 9403 appWindowToken = ai.mWindowToken; 9404 } 9405 return appWindowToken; 9406 } 9407 return null; 9408 } 9409 9410 /** 9411 * Retrieve private session object this view hierarchy is using to 9412 * communicate with the window manager. 9413 * @return the session object to communicate with the window manager 9414 */ 9415 /*package*/ IWindowSession getWindowSession() { 9416 return mAttachInfo != null ? mAttachInfo.mSession : null; 9417 } 9418 9419 /** 9420 * @param info the {@link android.view.View.AttachInfo} to associated with 9421 * this view 9422 */ 9423 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 9424 //System.out.println("Attached! " + this); 9425 mAttachInfo = info; 9426 mWindowAttachCount++; 9427 // We will need to evaluate the drawable state at least once. 9428 mPrivateFlags |= DRAWABLE_STATE_DIRTY; 9429 if (mFloatingTreeObserver != null) { 9430 info.mTreeObserver.merge(mFloatingTreeObserver); 9431 mFloatingTreeObserver = null; 9432 } 9433 if ((mPrivateFlags&SCROLL_CONTAINER) != 0) { 9434 mAttachInfo.mScrollContainers.add(this); 9435 mPrivateFlags |= SCROLL_CONTAINER_ADDED; 9436 } 9437 performCollectViewAttributes(visibility); 9438 onAttachedToWindow(); 9439 9440 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 9441 mOnAttachStateChangeListeners; 9442 if (listeners != null && listeners.size() > 0) { 9443 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 9444 // perform the dispatching. The iterator is a safe guard against listeners that 9445 // could mutate the list by calling the various add/remove methods. This prevents 9446 // the array from being modified while we iterate it. 9447 for (OnAttachStateChangeListener listener : listeners) { 9448 listener.onViewAttachedToWindow(this); 9449 } 9450 } 9451 9452 int vis = info.mWindowVisibility; 9453 if (vis != GONE) { 9454 onWindowVisibilityChanged(vis); 9455 } 9456 if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) { 9457 // If nobody has evaluated the drawable state yet, then do it now. 9458 refreshDrawableState(); 9459 } 9460 } 9461 9462 void dispatchDetachedFromWindow() { 9463 AttachInfo info = mAttachInfo; 9464 if (info != null) { 9465 int vis = info.mWindowVisibility; 9466 if (vis != GONE) { 9467 onWindowVisibilityChanged(GONE); 9468 } 9469 } 9470 9471 onDetachedFromWindow(); 9472 9473 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 9474 mOnAttachStateChangeListeners; 9475 if (listeners != null && listeners.size() > 0) { 9476 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 9477 // perform the dispatching. The iterator is a safe guard against listeners that 9478 // could mutate the list by calling the various add/remove methods. This prevents 9479 // the array from being modified while we iterate it. 9480 for (OnAttachStateChangeListener listener : listeners) { 9481 listener.onViewDetachedFromWindow(this); 9482 } 9483 } 9484 9485 if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) { 9486 mAttachInfo.mScrollContainers.remove(this); 9487 mPrivateFlags &= ~SCROLL_CONTAINER_ADDED; 9488 } 9489 9490 mAttachInfo = null; 9491 } 9492 9493 /** 9494 * Store this view hierarchy's frozen state into the given container. 9495 * 9496 * @param container The SparseArray in which to save the view's state. 9497 * 9498 * @see #restoreHierarchyState(android.util.SparseArray) 9499 * @see #dispatchSaveInstanceState(android.util.SparseArray) 9500 * @see #onSaveInstanceState() 9501 */ 9502 public void saveHierarchyState(SparseArray<Parcelable> container) { 9503 dispatchSaveInstanceState(container); 9504 } 9505 9506 /** 9507 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 9508 * this view and its children. May be overridden to modify how freezing happens to a 9509 * view's children; for example, some views may want to not store state for their children. 9510 * 9511 * @param container The SparseArray in which to save the view's state. 9512 * 9513 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 9514 * @see #saveHierarchyState(android.util.SparseArray) 9515 * @see #onSaveInstanceState() 9516 */ 9517 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 9518 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 9519 mPrivateFlags &= ~SAVE_STATE_CALLED; 9520 Parcelable state = onSaveInstanceState(); 9521 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) { 9522 throw new IllegalStateException( 9523 "Derived class did not call super.onSaveInstanceState()"); 9524 } 9525 if (state != null) { 9526 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 9527 // + ": " + state); 9528 container.put(mID, state); 9529 } 9530 } 9531 } 9532 9533 /** 9534 * Hook allowing a view to generate a representation of its internal state 9535 * that can later be used to create a new instance with that same state. 9536 * This state should only contain information that is not persistent or can 9537 * not be reconstructed later. For example, you will never store your 9538 * current position on screen because that will be computed again when a 9539 * new instance of the view is placed in its view hierarchy. 9540 * <p> 9541 * Some examples of things you may store here: the current cursor position 9542 * in a text view (but usually not the text itself since that is stored in a 9543 * content provider or other persistent storage), the currently selected 9544 * item in a list view. 9545 * 9546 * @return Returns a Parcelable object containing the view's current dynamic 9547 * state, or null if there is nothing interesting to save. The 9548 * default implementation returns null. 9549 * @see #onRestoreInstanceState(android.os.Parcelable) 9550 * @see #saveHierarchyState(android.util.SparseArray) 9551 * @see #dispatchSaveInstanceState(android.util.SparseArray) 9552 * @see #setSaveEnabled(boolean) 9553 */ 9554 protected Parcelable onSaveInstanceState() { 9555 mPrivateFlags |= SAVE_STATE_CALLED; 9556 return BaseSavedState.EMPTY_STATE; 9557 } 9558 9559 /** 9560 * Restore this view hierarchy's frozen state from the given container. 9561 * 9562 * @param container The SparseArray which holds previously frozen states. 9563 * 9564 * @see #saveHierarchyState(android.util.SparseArray) 9565 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 9566 * @see #onRestoreInstanceState(android.os.Parcelable) 9567 */ 9568 public void restoreHierarchyState(SparseArray<Parcelable> container) { 9569 dispatchRestoreInstanceState(container); 9570 } 9571 9572 /** 9573 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 9574 * state for this view and its children. May be overridden to modify how restoring 9575 * happens to a view's children; for example, some views may want to not store state 9576 * for their children. 9577 * 9578 * @param container The SparseArray which holds previously saved state. 9579 * 9580 * @see #dispatchSaveInstanceState(android.util.SparseArray) 9581 * @see #restoreHierarchyState(android.util.SparseArray) 9582 * @see #onRestoreInstanceState(android.os.Parcelable) 9583 */ 9584 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 9585 if (mID != NO_ID) { 9586 Parcelable state = container.get(mID); 9587 if (state != null) { 9588 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 9589 // + ": " + state); 9590 mPrivateFlags &= ~SAVE_STATE_CALLED; 9591 onRestoreInstanceState(state); 9592 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) { 9593 throw new IllegalStateException( 9594 "Derived class did not call super.onRestoreInstanceState()"); 9595 } 9596 } 9597 } 9598 } 9599 9600 /** 9601 * Hook allowing a view to re-apply a representation of its internal state that had previously 9602 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 9603 * null state. 9604 * 9605 * @param state The frozen state that had previously been returned by 9606 * {@link #onSaveInstanceState}. 9607 * 9608 * @see #onSaveInstanceState() 9609 * @see #restoreHierarchyState(android.util.SparseArray) 9610 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 9611 */ 9612 protected void onRestoreInstanceState(Parcelable state) { 9613 mPrivateFlags |= SAVE_STATE_CALLED; 9614 if (state != BaseSavedState.EMPTY_STATE && state != null) { 9615 throw new IllegalArgumentException("Wrong state class, expecting View State but " 9616 + "received " + state.getClass().toString() + " instead. This usually happens " 9617 + "when two views of different type have the same id in the same hierarchy. " 9618 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 9619 + "other views do not use the same id."); 9620 } 9621 } 9622 9623 /** 9624 * <p>Return the time at which the drawing of the view hierarchy started.</p> 9625 * 9626 * @return the drawing start time in milliseconds 9627 */ 9628 public long getDrawingTime() { 9629 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 9630 } 9631 9632 /** 9633 * <p>Enables or disables the duplication of the parent's state into this view. When 9634 * duplication is enabled, this view gets its drawable state from its parent rather 9635 * than from its own internal properties.</p> 9636 * 9637 * <p>Note: in the current implementation, setting this property to true after the 9638 * view was added to a ViewGroup might have no effect at all. This property should 9639 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 9640 * 9641 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 9642 * property is enabled, an exception will be thrown.</p> 9643 * 9644 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 9645 * parent, these states should not be affected by this method.</p> 9646 * 9647 * @param enabled True to enable duplication of the parent's drawable state, false 9648 * to disable it. 9649 * 9650 * @see #getDrawableState() 9651 * @see #isDuplicateParentStateEnabled() 9652 */ 9653 public void setDuplicateParentStateEnabled(boolean enabled) { 9654 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 9655 } 9656 9657 /** 9658 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 9659 * 9660 * @return True if this view's drawable state is duplicated from the parent, 9661 * false otherwise 9662 * 9663 * @see #getDrawableState() 9664 * @see #setDuplicateParentStateEnabled(boolean) 9665 */ 9666 public boolean isDuplicateParentStateEnabled() { 9667 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 9668 } 9669 9670 /** 9671 * <p>Specifies the type of layer backing this view. The layer can be 9672 * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or 9673 * {@link #LAYER_TYPE_HARDWARE hardware}.</p> 9674 * 9675 * <p>A layer is associated with an optional {@link android.graphics.Paint} 9676 * instance that controls how the layer is composed on screen. The following 9677 * properties of the paint are taken into account when composing the layer:</p> 9678 * <ul> 9679 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 9680 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 9681 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 9682 * </ul> 9683 * 9684 * <p>If this view has an alpha value set to < 1.0 by calling 9685 * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by 9686 * this view's alpha value. Calling {@link #setAlpha(float)} is therefore 9687 * equivalent to setting a hardware layer on this view and providing a paint with 9688 * the desired alpha value.<p> 9689 * 9690 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled}, 9691 * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware} 9692 * for more information on when and how to use layers.</p> 9693 * 9694 * @param layerType The ype of layer to use with this view, must be one of 9695 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 9696 * {@link #LAYER_TYPE_HARDWARE} 9697 * @param paint The paint used to compose the layer. This argument is optional 9698 * and can be null. It is ignored when the layer type is 9699 * {@link #LAYER_TYPE_NONE} 9700 * 9701 * @see #getLayerType() 9702 * @see #LAYER_TYPE_NONE 9703 * @see #LAYER_TYPE_SOFTWARE 9704 * @see #LAYER_TYPE_HARDWARE 9705 * @see #setAlpha(float) 9706 * 9707 * @attr ref android.R.styleable#View_layerType 9708 */ 9709 public void setLayerType(int layerType, Paint paint) { 9710 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 9711 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 9712 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 9713 } 9714 9715 if (layerType == mLayerType) { 9716 if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) { 9717 mLayerPaint = paint == null ? new Paint() : paint; 9718 invalidateParentCaches(); 9719 invalidate(true); 9720 } 9721 return; 9722 } 9723 9724 // Destroy any previous software drawing cache if needed 9725 switch (mLayerType) { 9726 case LAYER_TYPE_HARDWARE: 9727 destroyLayer(); 9728 // fall through - unaccelerated views may use software layer mechanism instead 9729 case LAYER_TYPE_SOFTWARE: 9730 destroyDrawingCache(); 9731 break; 9732 default: 9733 break; 9734 } 9735 9736 mLayerType = layerType; 9737 final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE; 9738 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 9739 mLocalDirtyRect = layerDisabled ? null : new Rect(); 9740 9741 invalidateParentCaches(); 9742 invalidate(true); 9743 } 9744 9745 /** 9746 * Indicates what type of layer is currently associated with this view. By default 9747 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 9748 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 9749 * for more information on the different types of layers. 9750 * 9751 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 9752 * {@link #LAYER_TYPE_HARDWARE} 9753 * 9754 * @see #setLayerType(int, android.graphics.Paint) 9755 * @see #buildLayer() 9756 * @see #LAYER_TYPE_NONE 9757 * @see #LAYER_TYPE_SOFTWARE 9758 * @see #LAYER_TYPE_HARDWARE 9759 */ 9760 public int getLayerType() { 9761 return mLayerType; 9762 } 9763 9764 /** 9765 * Forces this view's layer to be created and this view to be rendered 9766 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 9767 * invoking this method will have no effect. 9768 * 9769 * This method can for instance be used to render a view into its layer before 9770 * starting an animation. If this view is complex, rendering into the layer 9771 * before starting the animation will avoid skipping frames. 9772 * 9773 * @throws IllegalStateException If this view is not attached to a window 9774 * 9775 * @see #setLayerType(int, android.graphics.Paint) 9776 */ 9777 public void buildLayer() { 9778 if (mLayerType == LAYER_TYPE_NONE) return; 9779 9780 if (mAttachInfo == null) { 9781 throw new IllegalStateException("This view must be attached to a window first"); 9782 } 9783 9784 switch (mLayerType) { 9785 case LAYER_TYPE_HARDWARE: 9786 getHardwareLayer(); 9787 break; 9788 case LAYER_TYPE_SOFTWARE: 9789 buildDrawingCache(true); 9790 break; 9791 } 9792 } 9793 9794 /** 9795 * <p>Returns a hardware layer that can be used to draw this view again 9796 * without executing its draw method.</p> 9797 * 9798 * @return A HardwareLayer ready to render, or null if an error occurred. 9799 */ 9800 HardwareLayer getHardwareLayer() { 9801 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null || 9802 !mAttachInfo.mHardwareRenderer.isEnabled()) { 9803 return null; 9804 } 9805 9806 final int width = mRight - mLeft; 9807 final int height = mBottom - mTop; 9808 9809 if (width == 0 || height == 0) { 9810 return null; 9811 } 9812 9813 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) { 9814 if (mHardwareLayer == null) { 9815 mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer( 9816 width, height, isOpaque()); 9817 mLocalDirtyRect.setEmpty(); 9818 } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) { 9819 mHardwareLayer.resize(width, height); 9820 mLocalDirtyRect.setEmpty(); 9821 } 9822 9823 HardwareCanvas currentCanvas = mAttachInfo.mHardwareCanvas; 9824 final HardwareCanvas canvas = mHardwareLayer.start(currentCanvas); 9825 mAttachInfo.mHardwareCanvas = canvas; 9826 try { 9827 canvas.setViewport(width, height); 9828 canvas.onPreDraw(mLocalDirtyRect); 9829 mLocalDirtyRect.setEmpty(); 9830 9831 final int restoreCount = canvas.save(); 9832 9833 computeScroll(); 9834 canvas.translate(-mScrollX, -mScrollY); 9835 9836 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 9837 9838 // Fast path for layouts with no backgrounds 9839 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 9840 mPrivateFlags &= ~DIRTY_MASK; 9841 dispatchDraw(canvas); 9842 } else { 9843 draw(canvas); 9844 } 9845 9846 canvas.restoreToCount(restoreCount); 9847 } finally { 9848 canvas.onPostDraw(); 9849 mHardwareLayer.end(currentCanvas); 9850 mAttachInfo.mHardwareCanvas = currentCanvas; 9851 } 9852 } 9853 9854 return mHardwareLayer; 9855 } 9856 9857 boolean destroyLayer() { 9858 if (mHardwareLayer != null) { 9859 mHardwareLayer.destroy(); 9860 mHardwareLayer = null; 9861 return true; 9862 } 9863 return false; 9864 } 9865 9866 /** 9867 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 9868 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 9869 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 9870 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 9871 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 9872 * null.</p> 9873 * 9874 * <p>Enabling the drawing cache is similar to 9875 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 9876 * acceleration is turned off. When hardware acceleration is turned on, enabling the 9877 * drawing cache has no effect on rendering because the system uses a different mechanism 9878 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 9879 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 9880 * for information on how to enable software and hardware layers.</p> 9881 * 9882 * <p>This API can be used to manually generate 9883 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 9884 * {@link #getDrawingCache()}.</p> 9885 * 9886 * @param enabled true to enable the drawing cache, false otherwise 9887 * 9888 * @see #isDrawingCacheEnabled() 9889 * @see #getDrawingCache() 9890 * @see #buildDrawingCache() 9891 * @see #setLayerType(int, android.graphics.Paint) 9892 */ 9893 public void setDrawingCacheEnabled(boolean enabled) { 9894 mCachingFailed = false; 9895 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 9896 } 9897 9898 /** 9899 * <p>Indicates whether the drawing cache is enabled for this view.</p> 9900 * 9901 * @return true if the drawing cache is enabled 9902 * 9903 * @see #setDrawingCacheEnabled(boolean) 9904 * @see #getDrawingCache() 9905 */ 9906 @ViewDebug.ExportedProperty(category = "drawing") 9907 public boolean isDrawingCacheEnabled() { 9908 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 9909 } 9910 9911 /** 9912 * Debugging utility which recursively outputs the dirty state of a view and its 9913 * descendants. 9914 * 9915 * @hide 9916 */ 9917 @SuppressWarnings({"UnusedDeclaration"}) 9918 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 9919 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) + 9920 ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" + 9921 (mPrivateFlags & View.DRAWING_CACHE_VALID) + 9922 ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")"); 9923 if (clear) { 9924 mPrivateFlags &= clearMask; 9925 } 9926 if (this instanceof ViewGroup) { 9927 ViewGroup parent = (ViewGroup) this; 9928 final int count = parent.getChildCount(); 9929 for (int i = 0; i < count; i++) { 9930 final View child = parent.getChildAt(i); 9931 child.outputDirtyFlags(indent + " ", clear, clearMask); 9932 } 9933 } 9934 } 9935 9936 /** 9937 * This method is used by ViewGroup to cause its children to restore or recreate their 9938 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 9939 * to recreate its own display list, which would happen if it went through the normal 9940 * draw/dispatchDraw mechanisms. 9941 * 9942 * @hide 9943 */ 9944 protected void dispatchGetDisplayList() {} 9945 9946 /** 9947 * A view that is not attached or hardware accelerated cannot create a display list. 9948 * This method checks these conditions and returns the appropriate result. 9949 * 9950 * @return true if view has the ability to create a display list, false otherwise. 9951 * 9952 * @hide 9953 */ 9954 public boolean canHaveDisplayList() { 9955 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 9956 } 9957 9958 /** 9959 * <p>Returns a display list that can be used to draw this view again 9960 * without executing its draw method.</p> 9961 * 9962 * @return A DisplayList ready to replay, or null if caching is not enabled. 9963 * 9964 * @hide 9965 */ 9966 public DisplayList getDisplayList() { 9967 if (!canHaveDisplayList()) { 9968 return null; 9969 } 9970 9971 if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || 9972 mDisplayList == null || !mDisplayList.isValid() || 9973 mRecreateDisplayList)) { 9974 // Don't need to recreate the display list, just need to tell our 9975 // children to restore/recreate theirs 9976 if (mDisplayList != null && mDisplayList.isValid() && 9977 !mRecreateDisplayList) { 9978 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 9979 mPrivateFlags &= ~DIRTY_MASK; 9980 dispatchGetDisplayList(); 9981 9982 return mDisplayList; 9983 } 9984 9985 // If we got here, we're recreating it. Mark it as such to ensure that 9986 // we copy in child display lists into ours in drawChild() 9987 mRecreateDisplayList = true; 9988 if (mDisplayList == null) { 9989 mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList(); 9990 // If we're creating a new display list, make sure our parent gets invalidated 9991 // since they will need to recreate their display list to account for this 9992 // new child display list. 9993 invalidateParentCaches(); 9994 } 9995 9996 final HardwareCanvas canvas = mDisplayList.start(); 9997 try { 9998 int width = mRight - mLeft; 9999 int height = mBottom - mTop; 10000 10001 canvas.setViewport(width, height); 10002 // The dirty rect should always be null for a display list 10003 canvas.onPreDraw(null); 10004 10005 computeScroll(); 10006 canvas.translate(-mScrollX, -mScrollY); 10007 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 10008 mPrivateFlags &= ~DIRTY_MASK; 10009 10010 // Fast path for layouts with no backgrounds 10011 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 10012 dispatchDraw(canvas); 10013 } else { 10014 draw(canvas); 10015 } 10016 } finally { 10017 canvas.onPostDraw(); 10018 10019 mDisplayList.end(); 10020 } 10021 } else { 10022 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 10023 mPrivateFlags &= ~DIRTY_MASK; 10024 } 10025 10026 return mDisplayList; 10027 } 10028 10029 /** 10030 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 10031 * 10032 * @return A non-scaled bitmap representing this view or null if cache is disabled. 10033 * 10034 * @see #getDrawingCache(boolean) 10035 */ 10036 public Bitmap getDrawingCache() { 10037 return getDrawingCache(false); 10038 } 10039 10040 /** 10041 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 10042 * is null when caching is disabled. If caching is enabled and the cache is not ready, 10043 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 10044 * draw from the cache when the cache is enabled. To benefit from the cache, you must 10045 * request the drawing cache by calling this method and draw it on screen if the 10046 * returned bitmap is not null.</p> 10047 * 10048 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 10049 * this method will create a bitmap of the same size as this view. Because this bitmap 10050 * will be drawn scaled by the parent ViewGroup, the result on screen might show 10051 * scaling artifacts. To avoid such artifacts, you should call this method by setting 10052 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 10053 * size than the view. This implies that your application must be able to handle this 10054 * size.</p> 10055 * 10056 * @param autoScale Indicates whether the generated bitmap should be scaled based on 10057 * the current density of the screen when the application is in compatibility 10058 * mode. 10059 * 10060 * @return A bitmap representing this view or null if cache is disabled. 10061 * 10062 * @see #setDrawingCacheEnabled(boolean) 10063 * @see #isDrawingCacheEnabled() 10064 * @see #buildDrawingCache(boolean) 10065 * @see #destroyDrawingCache() 10066 */ 10067 public Bitmap getDrawingCache(boolean autoScale) { 10068 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 10069 return null; 10070 } 10071 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 10072 buildDrawingCache(autoScale); 10073 } 10074 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 10075 } 10076 10077 /** 10078 * <p>Frees the resources used by the drawing cache. If you call 10079 * {@link #buildDrawingCache()} manually without calling 10080 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 10081 * should cleanup the cache with this method afterwards.</p> 10082 * 10083 * @see #setDrawingCacheEnabled(boolean) 10084 * @see #buildDrawingCache() 10085 * @see #getDrawingCache() 10086 */ 10087 public void destroyDrawingCache() { 10088 if (mDrawingCache != null) { 10089 mDrawingCache.recycle(); 10090 mDrawingCache = null; 10091 } 10092 if (mUnscaledDrawingCache != null) { 10093 mUnscaledDrawingCache.recycle(); 10094 mUnscaledDrawingCache = null; 10095 } 10096 } 10097 10098 /** 10099 * Setting a solid background color for the drawing cache's bitmaps will improve 10100 * perfromance and memory usage. Note, though that this should only be used if this 10101 * view will always be drawn on top of a solid color. 10102 * 10103 * @param color The background color to use for the drawing cache's bitmap 10104 * 10105 * @see #setDrawingCacheEnabled(boolean) 10106 * @see #buildDrawingCache() 10107 * @see #getDrawingCache() 10108 */ 10109 public void setDrawingCacheBackgroundColor(int color) { 10110 if (color != mDrawingCacheBackgroundColor) { 10111 mDrawingCacheBackgroundColor = color; 10112 mPrivateFlags &= ~DRAWING_CACHE_VALID; 10113 } 10114 } 10115 10116 /** 10117 * @see #setDrawingCacheBackgroundColor(int) 10118 * 10119 * @return The background color to used for the drawing cache's bitmap 10120 */ 10121 public int getDrawingCacheBackgroundColor() { 10122 return mDrawingCacheBackgroundColor; 10123 } 10124 10125 /** 10126 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 10127 * 10128 * @see #buildDrawingCache(boolean) 10129 */ 10130 public void buildDrawingCache() { 10131 buildDrawingCache(false); 10132 } 10133 10134 /** 10135 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 10136 * 10137 * <p>If you call {@link #buildDrawingCache()} manually without calling 10138 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 10139 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 10140 * 10141 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 10142 * this method will create a bitmap of the same size as this view. Because this bitmap 10143 * will be drawn scaled by the parent ViewGroup, the result on screen might show 10144 * scaling artifacts. To avoid such artifacts, you should call this method by setting 10145 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 10146 * size than the view. This implies that your application must be able to handle this 10147 * size.</p> 10148 * 10149 * <p>You should avoid calling this method when hardware acceleration is enabled. If 10150 * you do not need the drawing cache bitmap, calling this method will increase memory 10151 * usage and cause the view to be rendered in software once, thus negatively impacting 10152 * performance.</p> 10153 * 10154 * @see #getDrawingCache() 10155 * @see #destroyDrawingCache() 10156 */ 10157 public void buildDrawingCache(boolean autoScale) { 10158 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ? 10159 mDrawingCache == null : mUnscaledDrawingCache == null)) { 10160 mCachingFailed = false; 10161 10162 if (ViewDebug.TRACE_HIERARCHY) { 10163 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE); 10164 } 10165 10166 int width = mRight - mLeft; 10167 int height = mBottom - mTop; 10168 10169 final AttachInfo attachInfo = mAttachInfo; 10170 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 10171 10172 if (autoScale && scalingRequired) { 10173 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 10174 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 10175 } 10176 10177 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 10178 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 10179 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 10180 10181 if (width <= 0 || height <= 0 || 10182 // Projected bitmap size in bytes 10183 (width * height * (opaque && !use32BitCache ? 2 : 4) > 10184 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) { 10185 destroyDrawingCache(); 10186 mCachingFailed = true; 10187 return; 10188 } 10189 10190 boolean clear = true; 10191 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 10192 10193 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 10194 Bitmap.Config quality; 10195 if (!opaque) { 10196 // Never pick ARGB_4444 because it looks awful 10197 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 10198 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 10199 case DRAWING_CACHE_QUALITY_AUTO: 10200 quality = Bitmap.Config.ARGB_8888; 10201 break; 10202 case DRAWING_CACHE_QUALITY_LOW: 10203 quality = Bitmap.Config.ARGB_8888; 10204 break; 10205 case DRAWING_CACHE_QUALITY_HIGH: 10206 quality = Bitmap.Config.ARGB_8888; 10207 break; 10208 default: 10209 quality = Bitmap.Config.ARGB_8888; 10210 break; 10211 } 10212 } else { 10213 // Optimization for translucent windows 10214 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 10215 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 10216 } 10217 10218 // Try to cleanup memory 10219 if (bitmap != null) bitmap.recycle(); 10220 10221 try { 10222 bitmap = Bitmap.createBitmap(width, height, quality); 10223 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 10224 if (autoScale) { 10225 mDrawingCache = bitmap; 10226 } else { 10227 mUnscaledDrawingCache = bitmap; 10228 } 10229 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 10230 } catch (OutOfMemoryError e) { 10231 // If there is not enough memory to create the bitmap cache, just 10232 // ignore the issue as bitmap caches are not required to draw the 10233 // view hierarchy 10234 if (autoScale) { 10235 mDrawingCache = null; 10236 } else { 10237 mUnscaledDrawingCache = null; 10238 } 10239 mCachingFailed = true; 10240 return; 10241 } 10242 10243 clear = drawingCacheBackgroundColor != 0; 10244 } 10245 10246 Canvas canvas; 10247 if (attachInfo != null) { 10248 canvas = attachInfo.mCanvas; 10249 if (canvas == null) { 10250 canvas = new Canvas(); 10251 } 10252 canvas.setBitmap(bitmap); 10253 // Temporarily clobber the cached Canvas in case one of our children 10254 // is also using a drawing cache. Without this, the children would 10255 // steal the canvas by attaching their own bitmap to it and bad, bad 10256 // thing would happen (invisible views, corrupted drawings, etc.) 10257 attachInfo.mCanvas = null; 10258 } else { 10259 // This case should hopefully never or seldom happen 10260 canvas = new Canvas(bitmap); 10261 } 10262 10263 if (clear) { 10264 bitmap.eraseColor(drawingCacheBackgroundColor); 10265 } 10266 10267 computeScroll(); 10268 final int restoreCount = canvas.save(); 10269 10270 if (autoScale && scalingRequired) { 10271 final float scale = attachInfo.mApplicationScale; 10272 canvas.scale(scale, scale); 10273 } 10274 10275 canvas.translate(-mScrollX, -mScrollY); 10276 10277 mPrivateFlags |= DRAWN; 10278 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 10279 mLayerType != LAYER_TYPE_NONE) { 10280 mPrivateFlags |= DRAWING_CACHE_VALID; 10281 } 10282 10283 // Fast path for layouts with no backgrounds 10284 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 10285 if (ViewDebug.TRACE_HIERARCHY) { 10286 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); 10287 } 10288 mPrivateFlags &= ~DIRTY_MASK; 10289 dispatchDraw(canvas); 10290 } else { 10291 draw(canvas); 10292 } 10293 10294 canvas.restoreToCount(restoreCount); 10295 canvas.setBitmap(null); 10296 10297 if (attachInfo != null) { 10298 // Restore the cached Canvas for our siblings 10299 attachInfo.mCanvas = canvas; 10300 } 10301 } 10302 } 10303 10304 /** 10305 * Create a snapshot of the view into a bitmap. We should probably make 10306 * some form of this public, but should think about the API. 10307 */ 10308 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 10309 int width = mRight - mLeft; 10310 int height = mBottom - mTop; 10311 10312 final AttachInfo attachInfo = mAttachInfo; 10313 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 10314 width = (int) ((width * scale) + 0.5f); 10315 height = (int) ((height * scale) + 0.5f); 10316 10317 Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality); 10318 if (bitmap == null) { 10319 throw new OutOfMemoryError(); 10320 } 10321 10322 Resources resources = getResources(); 10323 if (resources != null) { 10324 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 10325 } 10326 10327 Canvas canvas; 10328 if (attachInfo != null) { 10329 canvas = attachInfo.mCanvas; 10330 if (canvas == null) { 10331 canvas = new Canvas(); 10332 } 10333 canvas.setBitmap(bitmap); 10334 // Temporarily clobber the cached Canvas in case one of our children 10335 // is also using a drawing cache. Without this, the children would 10336 // steal the canvas by attaching their own bitmap to it and bad, bad 10337 // things would happen (invisible views, corrupted drawings, etc.) 10338 attachInfo.mCanvas = null; 10339 } else { 10340 // This case should hopefully never or seldom happen 10341 canvas = new Canvas(bitmap); 10342 } 10343 10344 if ((backgroundColor & 0xff000000) != 0) { 10345 bitmap.eraseColor(backgroundColor); 10346 } 10347 10348 computeScroll(); 10349 final int restoreCount = canvas.save(); 10350 canvas.scale(scale, scale); 10351 canvas.translate(-mScrollX, -mScrollY); 10352 10353 // Temporarily remove the dirty mask 10354 int flags = mPrivateFlags; 10355 mPrivateFlags &= ~DIRTY_MASK; 10356 10357 // Fast path for layouts with no backgrounds 10358 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 10359 dispatchDraw(canvas); 10360 } else { 10361 draw(canvas); 10362 } 10363 10364 mPrivateFlags = flags; 10365 10366 canvas.restoreToCount(restoreCount); 10367 canvas.setBitmap(null); 10368 10369 if (attachInfo != null) { 10370 // Restore the cached Canvas for our siblings 10371 attachInfo.mCanvas = canvas; 10372 } 10373 10374 return bitmap; 10375 } 10376 10377 /** 10378 * Indicates whether this View is currently in edit mode. A View is usually 10379 * in edit mode when displayed within a developer tool. For instance, if 10380 * this View is being drawn by a visual user interface builder, this method 10381 * should return true. 10382 * 10383 * Subclasses should check the return value of this method to provide 10384 * different behaviors if their normal behavior might interfere with the 10385 * host environment. For instance: the class spawns a thread in its 10386 * constructor, the drawing code relies on device-specific features, etc. 10387 * 10388 * This method is usually checked in the drawing code of custom widgets. 10389 * 10390 * @return True if this View is in edit mode, false otherwise. 10391 */ 10392 public boolean isInEditMode() { 10393 return false; 10394 } 10395 10396 /** 10397 * If the View draws content inside its padding and enables fading edges, 10398 * it needs to support padding offsets. Padding offsets are added to the 10399 * fading edges to extend the length of the fade so that it covers pixels 10400 * drawn inside the padding. 10401 * 10402 * Subclasses of this class should override this method if they need 10403 * to draw content inside the padding. 10404 * 10405 * @return True if padding offset must be applied, false otherwise. 10406 * 10407 * @see #getLeftPaddingOffset() 10408 * @see #getRightPaddingOffset() 10409 * @see #getTopPaddingOffset() 10410 * @see #getBottomPaddingOffset() 10411 * 10412 * @since CURRENT 10413 */ 10414 protected boolean isPaddingOffsetRequired() { 10415 return false; 10416 } 10417 10418 /** 10419 * Amount by which to extend the left fading region. Called only when 10420 * {@link #isPaddingOffsetRequired()} returns true. 10421 * 10422 * @return The left padding offset in pixels. 10423 * 10424 * @see #isPaddingOffsetRequired() 10425 * 10426 * @since CURRENT 10427 */ 10428 protected int getLeftPaddingOffset() { 10429 return 0; 10430 } 10431 10432 /** 10433 * Amount by which to extend the right fading region. Called only when 10434 * {@link #isPaddingOffsetRequired()} returns true. 10435 * 10436 * @return The right padding offset in pixels. 10437 * 10438 * @see #isPaddingOffsetRequired() 10439 * 10440 * @since CURRENT 10441 */ 10442 protected int getRightPaddingOffset() { 10443 return 0; 10444 } 10445 10446 /** 10447 * Amount by which to extend the top fading region. Called only when 10448 * {@link #isPaddingOffsetRequired()} returns true. 10449 * 10450 * @return The top padding offset in pixels. 10451 * 10452 * @see #isPaddingOffsetRequired() 10453 * 10454 * @since CURRENT 10455 */ 10456 protected int getTopPaddingOffset() { 10457 return 0; 10458 } 10459 10460 /** 10461 * Amount by which to extend the bottom fading region. Called only when 10462 * {@link #isPaddingOffsetRequired()} returns true. 10463 * 10464 * @return The bottom padding offset in pixels. 10465 * 10466 * @see #isPaddingOffsetRequired() 10467 * 10468 * @since CURRENT 10469 */ 10470 protected int getBottomPaddingOffset() { 10471 return 0; 10472 } 10473 10474 /** 10475 * @hide 10476 * @param offsetRequired 10477 */ 10478 protected int getFadeTop(boolean offsetRequired) { 10479 int top = mPaddingTop; 10480 if (offsetRequired) top += getTopPaddingOffset(); 10481 return top; 10482 } 10483 10484 /** 10485 * @hide 10486 * @param offsetRequired 10487 */ 10488 protected int getFadeHeight(boolean offsetRequired) { 10489 int padding = mPaddingTop; 10490 if (offsetRequired) padding += getTopPaddingOffset(); 10491 return mBottom - mTop - mPaddingBottom - padding; 10492 } 10493 10494 /** 10495 * <p>Indicates whether this view is attached to an hardware accelerated 10496 * window or not.</p> 10497 * 10498 * <p>Even if this method returns true, it does not mean that every call 10499 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 10500 * accelerated {@link android.graphics.Canvas}. For instance, if this view 10501 * is drawn onto an offscren {@link android.graphics.Bitmap} and its 10502 * window is hardware accelerated, 10503 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 10504 * return false, and this method will return true.</p> 10505 * 10506 * @return True if the view is attached to a window and the window is 10507 * hardware accelerated; false in any other case. 10508 */ 10509 public boolean isHardwareAccelerated() { 10510 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 10511 } 10512 10513 /** 10514 * Manually render this view (and all of its children) to the given Canvas. 10515 * The view must have already done a full layout before this function is 10516 * called. When implementing a view, implement 10517 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 10518 * If you do need to override this method, call the superclass version. 10519 * 10520 * @param canvas The Canvas to which the View is rendered. 10521 */ 10522 public void draw(Canvas canvas) { 10523 if (ViewDebug.TRACE_HIERARCHY) { 10524 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); 10525 } 10526 10527 final int privateFlags = mPrivateFlags; 10528 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE && 10529 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 10530 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN; 10531 10532 /* 10533 * Draw traversal performs several drawing steps which must be executed 10534 * in the appropriate order: 10535 * 10536 * 1. Draw the background 10537 * 2. If necessary, save the canvas' layers to prepare for fading 10538 * 3. Draw view's content 10539 * 4. Draw children 10540 * 5. If necessary, draw the fading edges and restore layers 10541 * 6. Draw decorations (scrollbars for instance) 10542 */ 10543 10544 // Step 1, draw the background, if needed 10545 int saveCount; 10546 10547 if (!dirtyOpaque) { 10548 final Drawable background = mBGDrawable; 10549 if (background != null) { 10550 final int scrollX = mScrollX; 10551 final int scrollY = mScrollY; 10552 10553 if (mBackgroundSizeChanged) { 10554 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 10555 mBackgroundSizeChanged = false; 10556 } 10557 10558 if ((scrollX | scrollY) == 0) { 10559 background.draw(canvas); 10560 } else { 10561 canvas.translate(scrollX, scrollY); 10562 background.draw(canvas); 10563 canvas.translate(-scrollX, -scrollY); 10564 } 10565 } 10566 } 10567 10568 // skip step 2 & 5 if possible (common case) 10569 final int viewFlags = mViewFlags; 10570 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 10571 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 10572 if (!verticalEdges && !horizontalEdges) { 10573 // Step 3, draw the content 10574 if (!dirtyOpaque) onDraw(canvas); 10575 10576 // Step 4, draw the children 10577 dispatchDraw(canvas); 10578 10579 // Step 6, draw decorations (scrollbars) 10580 onDrawScrollBars(canvas); 10581 10582 // we're done... 10583 return; 10584 } 10585 10586 /* 10587 * Here we do the full fledged routine... 10588 * (this is an uncommon case where speed matters less, 10589 * this is why we repeat some of the tests that have been 10590 * done above) 10591 */ 10592 10593 boolean drawTop = false; 10594 boolean drawBottom = false; 10595 boolean drawLeft = false; 10596 boolean drawRight = false; 10597 10598 float topFadeStrength = 0.0f; 10599 float bottomFadeStrength = 0.0f; 10600 float leftFadeStrength = 0.0f; 10601 float rightFadeStrength = 0.0f; 10602 10603 // Step 2, save the canvas' layers 10604 int paddingLeft = mPaddingLeft; 10605 10606 final boolean offsetRequired = isPaddingOffsetRequired(); 10607 if (offsetRequired) { 10608 paddingLeft += getLeftPaddingOffset(); 10609 } 10610 10611 int left = mScrollX + paddingLeft; 10612 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 10613 int top = mScrollY + getFadeTop(offsetRequired); 10614 int bottom = top + getFadeHeight(offsetRequired); 10615 10616 if (offsetRequired) { 10617 right += getRightPaddingOffset(); 10618 bottom += getBottomPaddingOffset(); 10619 } 10620 10621 final ScrollabilityCache scrollabilityCache = mScrollCache; 10622 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 10623 int length = (int) fadeHeight; 10624 10625 // clip the fade length if top and bottom fades overlap 10626 // overlapping fades produce odd-looking artifacts 10627 if (verticalEdges && (top + length > bottom - length)) { 10628 length = (bottom - top) / 2; 10629 } 10630 10631 // also clip horizontal fades if necessary 10632 if (horizontalEdges && (left + length > right - length)) { 10633 length = (right - left) / 2; 10634 } 10635 10636 if (verticalEdges) { 10637 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 10638 drawTop = topFadeStrength * fadeHeight > 1.0f; 10639 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 10640 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 10641 } 10642 10643 if (horizontalEdges) { 10644 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 10645 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 10646 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 10647 drawRight = rightFadeStrength * fadeHeight > 1.0f; 10648 } 10649 10650 saveCount = canvas.getSaveCount(); 10651 10652 int solidColor = getSolidColor(); 10653 if (solidColor == 0) { 10654 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 10655 10656 if (drawTop) { 10657 canvas.saveLayer(left, top, right, top + length, null, flags); 10658 } 10659 10660 if (drawBottom) { 10661 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 10662 } 10663 10664 if (drawLeft) { 10665 canvas.saveLayer(left, top, left + length, bottom, null, flags); 10666 } 10667 10668 if (drawRight) { 10669 canvas.saveLayer(right - length, top, right, bottom, null, flags); 10670 } 10671 } else { 10672 scrollabilityCache.setFadeColor(solidColor); 10673 } 10674 10675 // Step 3, draw the content 10676 if (!dirtyOpaque) onDraw(canvas); 10677 10678 // Step 4, draw the children 10679 dispatchDraw(canvas); 10680 10681 // Step 5, draw the fade effect and restore layers 10682 final Paint p = scrollabilityCache.paint; 10683 final Matrix matrix = scrollabilityCache.matrix; 10684 final Shader fade = scrollabilityCache.shader; 10685 10686 if (drawTop) { 10687 matrix.setScale(1, fadeHeight * topFadeStrength); 10688 matrix.postTranslate(left, top); 10689 fade.setLocalMatrix(matrix); 10690 canvas.drawRect(left, top, right, top + length, p); 10691 } 10692 10693 if (drawBottom) { 10694 matrix.setScale(1, fadeHeight * bottomFadeStrength); 10695 matrix.postRotate(180); 10696 matrix.postTranslate(left, bottom); 10697 fade.setLocalMatrix(matrix); 10698 canvas.drawRect(left, bottom - length, right, bottom, p); 10699 } 10700 10701 if (drawLeft) { 10702 matrix.setScale(1, fadeHeight * leftFadeStrength); 10703 matrix.postRotate(-90); 10704 matrix.postTranslate(left, top); 10705 fade.setLocalMatrix(matrix); 10706 canvas.drawRect(left, top, left + length, bottom, p); 10707 } 10708 10709 if (drawRight) { 10710 matrix.setScale(1, fadeHeight * rightFadeStrength); 10711 matrix.postRotate(90); 10712 matrix.postTranslate(right, top); 10713 fade.setLocalMatrix(matrix); 10714 canvas.drawRect(right - length, top, right, bottom, p); 10715 } 10716 10717 canvas.restoreToCount(saveCount); 10718 10719 // Step 6, draw decorations (scrollbars) 10720 onDrawScrollBars(canvas); 10721 } 10722 10723 /** 10724 * Override this if your view is known to always be drawn on top of a solid color background, 10725 * and needs to draw fading edges. Returning a non-zero color enables the view system to 10726 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 10727 * should be set to 0xFF. 10728 * 10729 * @see #setVerticalFadingEdgeEnabled(boolean) 10730 * @see #setHorizontalFadingEdgeEnabled(boolean) 10731 * 10732 * @return The known solid color background for this view, or 0 if the color may vary 10733 */ 10734 @ViewDebug.ExportedProperty(category = "drawing") 10735 public int getSolidColor() { 10736 return 0; 10737 } 10738 10739 /** 10740 * Build a human readable string representation of the specified view flags. 10741 * 10742 * @param flags the view flags to convert to a string 10743 * @return a String representing the supplied flags 10744 */ 10745 private static String printFlags(int flags) { 10746 String output = ""; 10747 int numFlags = 0; 10748 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 10749 output += "TAKES_FOCUS"; 10750 numFlags++; 10751 } 10752 10753 switch (flags & VISIBILITY_MASK) { 10754 case INVISIBLE: 10755 if (numFlags > 0) { 10756 output += " "; 10757 } 10758 output += "INVISIBLE"; 10759 // USELESS HERE numFlags++; 10760 break; 10761 case GONE: 10762 if (numFlags > 0) { 10763 output += " "; 10764 } 10765 output += "GONE"; 10766 // USELESS HERE numFlags++; 10767 break; 10768 default: 10769 break; 10770 } 10771 return output; 10772 } 10773 10774 /** 10775 * Build a human readable string representation of the specified private 10776 * view flags. 10777 * 10778 * @param privateFlags the private view flags to convert to a string 10779 * @return a String representing the supplied flags 10780 */ 10781 private static String printPrivateFlags(int privateFlags) { 10782 String output = ""; 10783 int numFlags = 0; 10784 10785 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) { 10786 output += "WANTS_FOCUS"; 10787 numFlags++; 10788 } 10789 10790 if ((privateFlags & FOCUSED) == FOCUSED) { 10791 if (numFlags > 0) { 10792 output += " "; 10793 } 10794 output += "FOCUSED"; 10795 numFlags++; 10796 } 10797 10798 if ((privateFlags & SELECTED) == SELECTED) { 10799 if (numFlags > 0) { 10800 output += " "; 10801 } 10802 output += "SELECTED"; 10803 numFlags++; 10804 } 10805 10806 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) { 10807 if (numFlags > 0) { 10808 output += " "; 10809 } 10810 output += "IS_ROOT_NAMESPACE"; 10811 numFlags++; 10812 } 10813 10814 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) { 10815 if (numFlags > 0) { 10816 output += " "; 10817 } 10818 output += "HAS_BOUNDS"; 10819 numFlags++; 10820 } 10821 10822 if ((privateFlags & DRAWN) == DRAWN) { 10823 if (numFlags > 0) { 10824 output += " "; 10825 } 10826 output += "DRAWN"; 10827 // USELESS HERE numFlags++; 10828 } 10829 return output; 10830 } 10831 10832 /** 10833 * <p>Indicates whether or not this view's layout will be requested during 10834 * the next hierarchy layout pass.</p> 10835 * 10836 * @return true if the layout will be forced during next layout pass 10837 */ 10838 public boolean isLayoutRequested() { 10839 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT; 10840 } 10841 10842 /** 10843 * Assign a size and position to a view and all of its 10844 * descendants 10845 * 10846 * <p>This is the second phase of the layout mechanism. 10847 * (The first is measuring). In this phase, each parent calls 10848 * layout on all of its children to position them. 10849 * This is typically done using the child measurements 10850 * that were stored in the measure pass().</p> 10851 * 10852 * <p>Derived classes should not override this method. 10853 * Derived classes with children should override 10854 * onLayout. In that method, they should 10855 * call layout on each of their children.</p> 10856 * 10857 * @param l Left position, relative to parent 10858 * @param t Top position, relative to parent 10859 * @param r Right position, relative to parent 10860 * @param b Bottom position, relative to parent 10861 */ 10862 @SuppressWarnings({"unchecked"}) 10863 public void layout(int l, int t, int r, int b) { 10864 int oldL = mLeft; 10865 int oldT = mTop; 10866 int oldB = mBottom; 10867 int oldR = mRight; 10868 boolean changed = setFrame(l, t, r, b); 10869 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) { 10870 if (ViewDebug.TRACE_HIERARCHY) { 10871 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT); 10872 } 10873 10874 onLayout(changed, l, t, r, b); 10875 mPrivateFlags &= ~LAYOUT_REQUIRED; 10876 10877 if (mOnLayoutChangeListeners != null) { 10878 ArrayList<OnLayoutChangeListener> listenersCopy = 10879 (ArrayList<OnLayoutChangeListener>) mOnLayoutChangeListeners.clone(); 10880 int numListeners = listenersCopy.size(); 10881 for (int i = 0; i < numListeners; ++i) { 10882 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 10883 } 10884 } 10885 } 10886 mPrivateFlags &= ~FORCE_LAYOUT; 10887 } 10888 10889 /** 10890 * Called from layout when this view should 10891 * assign a size and position to each of its children. 10892 * 10893 * Derived classes with children should override 10894 * this method and call layout on each of 10895 * their children. 10896 * @param changed This is a new size or position for this view 10897 * @param left Left position, relative to parent 10898 * @param top Top position, relative to parent 10899 * @param right Right position, relative to parent 10900 * @param bottom Bottom position, relative to parent 10901 */ 10902 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 10903 } 10904 10905 /** 10906 * Assign a size and position to this view. 10907 * 10908 * This is called from layout. 10909 * 10910 * @param left Left position, relative to parent 10911 * @param top Top position, relative to parent 10912 * @param right Right position, relative to parent 10913 * @param bottom Bottom position, relative to parent 10914 * @return true if the new size and position are different than the 10915 * previous ones 10916 * {@hide} 10917 */ 10918 protected boolean setFrame(int left, int top, int right, int bottom) { 10919 boolean changed = false; 10920 10921 if (DBG) { 10922 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 10923 + right + "," + bottom + ")"); 10924 } 10925 10926 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 10927 changed = true; 10928 10929 // Remember our drawn bit 10930 int drawn = mPrivateFlags & DRAWN; 10931 10932 int oldWidth = mRight - mLeft; 10933 int oldHeight = mBottom - mTop; 10934 int newWidth = right - left; 10935 int newHeight = bottom - top; 10936 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 10937 10938 // Invalidate our old position 10939 invalidate(sizeChanged); 10940 10941 mLeft = left; 10942 mTop = top; 10943 mRight = right; 10944 mBottom = bottom; 10945 10946 mPrivateFlags |= HAS_BOUNDS; 10947 10948 10949 if (sizeChanged) { 10950 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 10951 // A change in dimension means an auto-centered pivot point changes, too 10952 mMatrixDirty = true; 10953 } 10954 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 10955 } 10956 10957 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 10958 // If we are visible, force the DRAWN bit to on so that 10959 // this invalidate will go through (at least to our parent). 10960 // This is because someone may have invalidated this view 10961 // before this call to setFrame came in, thereby clearing 10962 // the DRAWN bit. 10963 mPrivateFlags |= DRAWN; 10964 invalidate(sizeChanged); 10965 // parent display list may need to be recreated based on a change in the bounds 10966 // of any child 10967 invalidateParentCaches(); 10968 } 10969 10970 // Reset drawn bit to original value (invalidate turns it off) 10971 mPrivateFlags |= drawn; 10972 10973 mBackgroundSizeChanged = true; 10974 } 10975 return changed; 10976 } 10977 10978 /** 10979 * Finalize inflating a view from XML. This is called as the last phase 10980 * of inflation, after all child views have been added. 10981 * 10982 * <p>Even if the subclass overrides onFinishInflate, they should always be 10983 * sure to call the super method, so that we get called. 10984 */ 10985 protected void onFinishInflate() { 10986 } 10987 10988 /** 10989 * Returns the resources associated with this view. 10990 * 10991 * @return Resources object. 10992 */ 10993 public Resources getResources() { 10994 return mResources; 10995 } 10996 10997 /** 10998 * Invalidates the specified Drawable. 10999 * 11000 * @param drawable the drawable to invalidate 11001 */ 11002 public void invalidateDrawable(Drawable drawable) { 11003 if (verifyDrawable(drawable)) { 11004 final Rect dirty = drawable.getBounds(); 11005 final int scrollX = mScrollX; 11006 final int scrollY = mScrollY; 11007 11008 invalidate(dirty.left + scrollX, dirty.top + scrollY, 11009 dirty.right + scrollX, dirty.bottom + scrollY); 11010 } 11011 } 11012 11013 /** 11014 * Schedules an action on a drawable to occur at a specified time. 11015 * 11016 * @param who the recipient of the action 11017 * @param what the action to run on the drawable 11018 * @param when the time at which the action must occur. Uses the 11019 * {@link SystemClock#uptimeMillis} timebase. 11020 */ 11021 public void scheduleDrawable(Drawable who, Runnable what, long when) { 11022 if (verifyDrawable(who) && what != null && mAttachInfo != null) { 11023 mAttachInfo.mHandler.postAtTime(what, who, when); 11024 } 11025 } 11026 11027 /** 11028 * Cancels a scheduled action on a drawable. 11029 * 11030 * @param who the recipient of the action 11031 * @param what the action to cancel 11032 */ 11033 public void unscheduleDrawable(Drawable who, Runnable what) { 11034 if (verifyDrawable(who) && what != null && mAttachInfo != null) { 11035 mAttachInfo.mHandler.removeCallbacks(what, who); 11036 } 11037 } 11038 11039 /** 11040 * Unschedule any events associated with the given Drawable. This can be 11041 * used when selecting a new Drawable into a view, so that the previous 11042 * one is completely unscheduled. 11043 * 11044 * @param who The Drawable to unschedule. 11045 * 11046 * @see #drawableStateChanged 11047 */ 11048 public void unscheduleDrawable(Drawable who) { 11049 if (mAttachInfo != null) { 11050 mAttachInfo.mHandler.removeCallbacksAndMessages(who); 11051 } 11052 } 11053 11054 /** 11055 * Return the layout direction of a given Drawable. 11056 * 11057 * @param who the Drawable to query 11058 * 11059 * @hide 11060 */ 11061 public int getResolvedLayoutDirection(Drawable who) { 11062 return (who == mBGDrawable) ? getResolvedLayoutDirection() : LAYOUT_DIRECTION_DEFAULT; 11063 } 11064 11065 /** 11066 * If your view subclass is displaying its own Drawable objects, it should 11067 * override this function and return true for any Drawable it is 11068 * displaying. This allows animations for those drawables to be 11069 * scheduled. 11070 * 11071 * <p>Be sure to call through to the super class when overriding this 11072 * function. 11073 * 11074 * @param who The Drawable to verify. Return true if it is one you are 11075 * displaying, else return the result of calling through to the 11076 * super class. 11077 * 11078 * @return boolean If true than the Drawable is being displayed in the 11079 * view; else false and it is not allowed to animate. 11080 * 11081 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 11082 * @see #drawableStateChanged() 11083 */ 11084 protected boolean verifyDrawable(Drawable who) { 11085 return who == mBGDrawable; 11086 } 11087 11088 /** 11089 * This function is called whenever the state of the view changes in such 11090 * a way that it impacts the state of drawables being shown. 11091 * 11092 * <p>Be sure to call through to the superclass when overriding this 11093 * function. 11094 * 11095 * @see Drawable#setState(int[]) 11096 */ 11097 protected void drawableStateChanged() { 11098 Drawable d = mBGDrawable; 11099 if (d != null && d.isStateful()) { 11100 d.setState(getDrawableState()); 11101 } 11102 } 11103 11104 /** 11105 * Call this to force a view to update its drawable state. This will cause 11106 * drawableStateChanged to be called on this view. Views that are interested 11107 * in the new state should call getDrawableState. 11108 * 11109 * @see #drawableStateChanged 11110 * @see #getDrawableState 11111 */ 11112 public void refreshDrawableState() { 11113 mPrivateFlags |= DRAWABLE_STATE_DIRTY; 11114 drawableStateChanged(); 11115 11116 ViewParent parent = mParent; 11117 if (parent != null) { 11118 parent.childDrawableStateChanged(this); 11119 } 11120 } 11121 11122 /** 11123 * Return an array of resource IDs of the drawable states representing the 11124 * current state of the view. 11125 * 11126 * @return The current drawable state 11127 * 11128 * @see Drawable#setState(int[]) 11129 * @see #drawableStateChanged() 11130 * @see #onCreateDrawableState(int) 11131 */ 11132 public final int[] getDrawableState() { 11133 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) { 11134 return mDrawableState; 11135 } else { 11136 mDrawableState = onCreateDrawableState(0); 11137 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY; 11138 return mDrawableState; 11139 } 11140 } 11141 11142 /** 11143 * Generate the new {@link android.graphics.drawable.Drawable} state for 11144 * this view. This is called by the view 11145 * system when the cached Drawable state is determined to be invalid. To 11146 * retrieve the current state, you should use {@link #getDrawableState}. 11147 * 11148 * @param extraSpace if non-zero, this is the number of extra entries you 11149 * would like in the returned array in which you can place your own 11150 * states. 11151 * 11152 * @return Returns an array holding the current {@link Drawable} state of 11153 * the view. 11154 * 11155 * @see #mergeDrawableStates(int[], int[]) 11156 */ 11157 protected int[] onCreateDrawableState(int extraSpace) { 11158 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 11159 mParent instanceof View) { 11160 return ((View) mParent).onCreateDrawableState(extraSpace); 11161 } 11162 11163 int[] drawableState; 11164 11165 int privateFlags = mPrivateFlags; 11166 11167 int viewStateIndex = 0; 11168 if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 11169 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 11170 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 11171 if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 11172 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 11173 if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 11174 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 11175 HardwareRenderer.isAvailable()) { 11176 // This is set if HW acceleration is requested, even if the current 11177 // process doesn't allow it. This is just to allow app preview 11178 // windows to better match their app. 11179 viewStateIndex |= VIEW_STATE_ACCELERATED; 11180 } 11181 if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 11182 11183 final int privateFlags2 = mPrivateFlags2; 11184 if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 11185 if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 11186 11187 drawableState = VIEW_STATE_SETS[viewStateIndex]; 11188 11189 //noinspection ConstantIfStatement 11190 if (false) { 11191 Log.i("View", "drawableStateIndex=" + viewStateIndex); 11192 Log.i("View", toString() 11193 + " pressed=" + ((privateFlags & PRESSED) != 0) 11194 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 11195 + " fo=" + hasFocus() 11196 + " sl=" + ((privateFlags & SELECTED) != 0) 11197 + " wf=" + hasWindowFocus() 11198 + ": " + Arrays.toString(drawableState)); 11199 } 11200 11201 if (extraSpace == 0) { 11202 return drawableState; 11203 } 11204 11205 final int[] fullState; 11206 if (drawableState != null) { 11207 fullState = new int[drawableState.length + extraSpace]; 11208 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 11209 } else { 11210 fullState = new int[extraSpace]; 11211 } 11212 11213 return fullState; 11214 } 11215 11216 /** 11217 * Merge your own state values in <var>additionalState</var> into the base 11218 * state values <var>baseState</var> that were returned by 11219 * {@link #onCreateDrawableState(int)}. 11220 * 11221 * @param baseState The base state values returned by 11222 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 11223 * own additional state values. 11224 * 11225 * @param additionalState The additional state values you would like 11226 * added to <var>baseState</var>; this array is not modified. 11227 * 11228 * @return As a convenience, the <var>baseState</var> array you originally 11229 * passed into the function is returned. 11230 * 11231 * @see #onCreateDrawableState(int) 11232 */ 11233 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 11234 final int N = baseState.length; 11235 int i = N - 1; 11236 while (i >= 0 && baseState[i] == 0) { 11237 i--; 11238 } 11239 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 11240 return baseState; 11241 } 11242 11243 /** 11244 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 11245 * on all Drawable objects associated with this view. 11246 */ 11247 public void jumpDrawablesToCurrentState() { 11248 if (mBGDrawable != null) { 11249 mBGDrawable.jumpToCurrentState(); 11250 } 11251 } 11252 11253 /** 11254 * Sets the background color for this view. 11255 * @param color the color of the background 11256 */ 11257 @RemotableViewMethod 11258 public void setBackgroundColor(int color) { 11259 if (mBGDrawable instanceof ColorDrawable) { 11260 ((ColorDrawable) mBGDrawable).setColor(color); 11261 } else { 11262 setBackgroundDrawable(new ColorDrawable(color)); 11263 } 11264 } 11265 11266 /** 11267 * Set the background to a given resource. The resource should refer to 11268 * a Drawable object or 0 to remove the background. 11269 * @param resid The identifier of the resource. 11270 * @attr ref android.R.styleable#View_background 11271 */ 11272 @RemotableViewMethod 11273 public void setBackgroundResource(int resid) { 11274 if (resid != 0 && resid == mBackgroundResource) { 11275 return; 11276 } 11277 11278 Drawable d= null; 11279 if (resid != 0) { 11280 d = mResources.getDrawable(resid); 11281 } 11282 setBackgroundDrawable(d); 11283 11284 mBackgroundResource = resid; 11285 } 11286 11287 /** 11288 * Set the background to a given Drawable, or remove the background. If the 11289 * background has padding, this View's padding is set to the background's 11290 * padding. However, when a background is removed, this View's padding isn't 11291 * touched. If setting the padding is desired, please use 11292 * {@link #setPadding(int, int, int, int)}. 11293 * 11294 * @param d The Drawable to use as the background, or null to remove the 11295 * background 11296 */ 11297 public void setBackgroundDrawable(Drawable d) { 11298 if (d == mBGDrawable) { 11299 return; 11300 } 11301 11302 boolean requestLayout = false; 11303 11304 mBackgroundResource = 0; 11305 11306 /* 11307 * Regardless of whether we're setting a new background or not, we want 11308 * to clear the previous drawable. 11309 */ 11310 if (mBGDrawable != null) { 11311 mBGDrawable.setCallback(null); 11312 unscheduleDrawable(mBGDrawable); 11313 } 11314 11315 if (d != null) { 11316 Rect padding = sThreadLocal.get(); 11317 if (padding == null) { 11318 padding = new Rect(); 11319 sThreadLocal.set(padding); 11320 } 11321 if (d.getPadding(padding)) { 11322 switch (d.getResolvedLayoutDirectionSelf()) { 11323 case LAYOUT_DIRECTION_RTL: 11324 setPadding(padding.right, padding.top, padding.left, padding.bottom); 11325 break; 11326 case LAYOUT_DIRECTION_LTR: 11327 default: 11328 setPadding(padding.left, padding.top, padding.right, padding.bottom); 11329 } 11330 } 11331 11332 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 11333 // if it has a different minimum size, we should layout again 11334 if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() || 11335 mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) { 11336 requestLayout = true; 11337 } 11338 11339 d.setCallback(this); 11340 if (d.isStateful()) { 11341 d.setState(getDrawableState()); 11342 } 11343 d.setVisible(getVisibility() == VISIBLE, false); 11344 mBGDrawable = d; 11345 11346 if ((mPrivateFlags & SKIP_DRAW) != 0) { 11347 mPrivateFlags &= ~SKIP_DRAW; 11348 mPrivateFlags |= ONLY_DRAWS_BACKGROUND; 11349 requestLayout = true; 11350 } 11351 } else { 11352 /* Remove the background */ 11353 mBGDrawable = null; 11354 11355 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) { 11356 /* 11357 * This view ONLY drew the background before and we're removing 11358 * the background, so now it won't draw anything 11359 * (hence we SKIP_DRAW) 11360 */ 11361 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND; 11362 mPrivateFlags |= SKIP_DRAW; 11363 } 11364 11365 /* 11366 * When the background is set, we try to apply its padding to this 11367 * View. When the background is removed, we don't touch this View's 11368 * padding. This is noted in the Javadocs. Hence, we don't need to 11369 * requestLayout(), the invalidate() below is sufficient. 11370 */ 11371 11372 // The old background's minimum size could have affected this 11373 // View's layout, so let's requestLayout 11374 requestLayout = true; 11375 } 11376 11377 computeOpaqueFlags(); 11378 11379 if (requestLayout) { 11380 requestLayout(); 11381 } 11382 11383 mBackgroundSizeChanged = true; 11384 invalidate(true); 11385 } 11386 11387 /** 11388 * Gets the background drawable 11389 * @return The drawable used as the background for this view, if any. 11390 */ 11391 public Drawable getBackground() { 11392 return mBGDrawable; 11393 } 11394 11395 /** 11396 * Sets the padding. The view may add on the space required to display 11397 * the scrollbars, depending on the style and visibility of the scrollbars. 11398 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 11399 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 11400 * from the values set in this call. 11401 * 11402 * @attr ref android.R.styleable#View_padding 11403 * @attr ref android.R.styleable#View_paddingBottom 11404 * @attr ref android.R.styleable#View_paddingLeft 11405 * @attr ref android.R.styleable#View_paddingRight 11406 * @attr ref android.R.styleable#View_paddingTop 11407 * @param left the left padding in pixels 11408 * @param top the top padding in pixels 11409 * @param right the right padding in pixels 11410 * @param bottom the bottom padding in pixels 11411 */ 11412 public void setPadding(int left, int top, int right, int bottom) { 11413 boolean changed = false; 11414 11415 mUserPaddingRelative = false; 11416 11417 mUserPaddingLeft = left; 11418 mUserPaddingRight = right; 11419 mUserPaddingBottom = bottom; 11420 11421 final int viewFlags = mViewFlags; 11422 11423 // Common case is there are no scroll bars. 11424 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 11425 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 11426 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 11427 ? 0 : getVerticalScrollbarWidth(); 11428 switch (mVerticalScrollbarPosition) { 11429 case SCROLLBAR_POSITION_DEFAULT: 11430 if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) { 11431 left += offset; 11432 } else { 11433 right += offset; 11434 } 11435 break; 11436 case SCROLLBAR_POSITION_RIGHT: 11437 right += offset; 11438 break; 11439 case SCROLLBAR_POSITION_LEFT: 11440 left += offset; 11441 break; 11442 } 11443 } 11444 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 11445 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 11446 ? 0 : getHorizontalScrollbarHeight(); 11447 } 11448 } 11449 11450 if (mPaddingLeft != left) { 11451 changed = true; 11452 mPaddingLeft = left; 11453 } 11454 if (mPaddingTop != top) { 11455 changed = true; 11456 mPaddingTop = top; 11457 } 11458 if (mPaddingRight != right) { 11459 changed = true; 11460 mPaddingRight = right; 11461 } 11462 if (mPaddingBottom != bottom) { 11463 changed = true; 11464 mPaddingBottom = bottom; 11465 } 11466 11467 if (changed) { 11468 requestLayout(); 11469 } 11470 } 11471 11472 /** 11473 * Sets the relative padding. The view may add on the space required to display 11474 * the scrollbars, depending on the style and visibility of the scrollbars. 11475 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 11476 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 11477 * from the values set in this call. 11478 * 11479 * @attr ref android.R.styleable#View_padding 11480 * @attr ref android.R.styleable#View_paddingBottom 11481 * @attr ref android.R.styleable#View_paddingStart 11482 * @attr ref android.R.styleable#View_paddingEnd 11483 * @attr ref android.R.styleable#View_paddingTop 11484 * @param start the start padding in pixels 11485 * @param top the top padding in pixels 11486 * @param end the end padding in pixels 11487 * @param bottom the bottom padding in pixels 11488 * 11489 * @hide 11490 */ 11491 public void setPaddingRelative(int start, int top, int end, int bottom) { 11492 mUserPaddingRelative = true; 11493 11494 mUserPaddingStart = start; 11495 mUserPaddingEnd = end; 11496 11497 switch(getResolvedLayoutDirection()) { 11498 case LAYOUT_DIRECTION_RTL: 11499 setPadding(end, top, start, bottom); 11500 break; 11501 case LAYOUT_DIRECTION_LTR: 11502 default: 11503 setPadding(start, top, end, bottom); 11504 } 11505 } 11506 11507 /** 11508 * Returns the top padding of this view. 11509 * 11510 * @return the top padding in pixels 11511 */ 11512 public int getPaddingTop() { 11513 return mPaddingTop; 11514 } 11515 11516 /** 11517 * Returns the bottom padding of this view. If there are inset and enabled 11518 * scrollbars, this value may include the space required to display the 11519 * scrollbars as well. 11520 * 11521 * @return the bottom padding in pixels 11522 */ 11523 public int getPaddingBottom() { 11524 return mPaddingBottom; 11525 } 11526 11527 /** 11528 * Returns the left padding of this view. If there are inset and enabled 11529 * scrollbars, this value may include the space required to display the 11530 * scrollbars as well. 11531 * 11532 * @return the left padding in pixels 11533 */ 11534 public int getPaddingLeft() { 11535 return mPaddingLeft; 11536 } 11537 11538 /** 11539 * Returns the start padding of this view. If there are inset and enabled 11540 * scrollbars, this value may include the space required to display the 11541 * scrollbars as well. 11542 * 11543 * @return the start padding in pixels 11544 * 11545 * @hide 11546 */ 11547 public int getPaddingStart() { 11548 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 11549 mPaddingRight : mPaddingLeft; 11550 } 11551 11552 /** 11553 * Returns the right padding of this view. If there are inset and enabled 11554 * scrollbars, this value may include the space required to display the 11555 * scrollbars as well. 11556 * 11557 * @return the right padding in pixels 11558 */ 11559 public int getPaddingRight() { 11560 return mPaddingRight; 11561 } 11562 11563 /** 11564 * Returns the end padding of this view. If there are inset and enabled 11565 * scrollbars, this value may include the space required to display the 11566 * scrollbars as well. 11567 * 11568 * @return the end padding in pixels 11569 * 11570 * @hide 11571 */ 11572 public int getPaddingEnd() { 11573 return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 11574 mPaddingLeft : mPaddingRight; 11575 } 11576 11577 /** 11578 * Return if the padding as been set thru relative values 11579 * {@link #setPaddingRelative(int, int, int, int)} or thru 11580 * @attr ref android.R.styleable#View_paddingStart or 11581 * @attr ref android.R.styleable#View_paddingEnd 11582 * 11583 * @return true if the padding is relative or false if it is not. 11584 * 11585 * @hide 11586 */ 11587 public boolean isPaddingRelative() { 11588 return mUserPaddingRelative; 11589 } 11590 11591 /** 11592 * Changes the selection state of this view. A view can be selected or not. 11593 * Note that selection is not the same as focus. Views are typically 11594 * selected in the context of an AdapterView like ListView or GridView; 11595 * the selected view is the view that is highlighted. 11596 * 11597 * @param selected true if the view must be selected, false otherwise 11598 */ 11599 public void setSelected(boolean selected) { 11600 if (((mPrivateFlags & SELECTED) != 0) != selected) { 11601 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0); 11602 if (!selected) resetPressedState(); 11603 invalidate(true); 11604 refreshDrawableState(); 11605 dispatchSetSelected(selected); 11606 } 11607 } 11608 11609 /** 11610 * Dispatch setSelected to all of this View's children. 11611 * 11612 * @see #setSelected(boolean) 11613 * 11614 * @param selected The new selected state 11615 */ 11616 protected void dispatchSetSelected(boolean selected) { 11617 } 11618 11619 /** 11620 * Indicates the selection state of this view. 11621 * 11622 * @return true if the view is selected, false otherwise 11623 */ 11624 @ViewDebug.ExportedProperty 11625 public boolean isSelected() { 11626 return (mPrivateFlags & SELECTED) != 0; 11627 } 11628 11629 /** 11630 * Changes the activated state of this view. A view can be activated or not. 11631 * Note that activation is not the same as selection. Selection is 11632 * a transient property, representing the view (hierarchy) the user is 11633 * currently interacting with. Activation is a longer-term state that the 11634 * user can move views in and out of. For example, in a list view with 11635 * single or multiple selection enabled, the views in the current selection 11636 * set are activated. (Um, yeah, we are deeply sorry about the terminology 11637 * here.) The activated state is propagated down to children of the view it 11638 * is set on. 11639 * 11640 * @param activated true if the view must be activated, false otherwise 11641 */ 11642 public void setActivated(boolean activated) { 11643 if (((mPrivateFlags & ACTIVATED) != 0) != activated) { 11644 mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0); 11645 invalidate(true); 11646 refreshDrawableState(); 11647 dispatchSetActivated(activated); 11648 } 11649 } 11650 11651 /** 11652 * Dispatch setActivated to all of this View's children. 11653 * 11654 * @see #setActivated(boolean) 11655 * 11656 * @param activated The new activated state 11657 */ 11658 protected void dispatchSetActivated(boolean activated) { 11659 } 11660 11661 /** 11662 * Indicates the activation state of this view. 11663 * 11664 * @return true if the view is activated, false otherwise 11665 */ 11666 @ViewDebug.ExportedProperty 11667 public boolean isActivated() { 11668 return (mPrivateFlags & ACTIVATED) != 0; 11669 } 11670 11671 /** 11672 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 11673 * observer can be used to get notifications when global events, like 11674 * layout, happen. 11675 * 11676 * The returned ViewTreeObserver observer is not guaranteed to remain 11677 * valid for the lifetime of this View. If the caller of this method keeps 11678 * a long-lived reference to ViewTreeObserver, it should always check for 11679 * the return value of {@link ViewTreeObserver#isAlive()}. 11680 * 11681 * @return The ViewTreeObserver for this view's hierarchy. 11682 */ 11683 public ViewTreeObserver getViewTreeObserver() { 11684 if (mAttachInfo != null) { 11685 return mAttachInfo.mTreeObserver; 11686 } 11687 if (mFloatingTreeObserver == null) { 11688 mFloatingTreeObserver = new ViewTreeObserver(); 11689 } 11690 return mFloatingTreeObserver; 11691 } 11692 11693 /** 11694 * <p>Finds the topmost view in the current view hierarchy.</p> 11695 * 11696 * @return the topmost view containing this view 11697 */ 11698 public View getRootView() { 11699 if (mAttachInfo != null) { 11700 final View v = mAttachInfo.mRootView; 11701 if (v != null) { 11702 return v; 11703 } 11704 } 11705 11706 View parent = this; 11707 11708 while (parent.mParent != null && parent.mParent instanceof View) { 11709 parent = (View) parent.mParent; 11710 } 11711 11712 return parent; 11713 } 11714 11715 /** 11716 * <p>Computes the coordinates of this view on the screen. The argument 11717 * must be an array of two integers. After the method returns, the array 11718 * contains the x and y location in that order.</p> 11719 * 11720 * @param location an array of two integers in which to hold the coordinates 11721 */ 11722 public void getLocationOnScreen(int[] location) { 11723 getLocationInWindow(location); 11724 11725 final AttachInfo info = mAttachInfo; 11726 if (info != null) { 11727 location[0] += info.mWindowLeft; 11728 location[1] += info.mWindowTop; 11729 } 11730 } 11731 11732 /** 11733 * <p>Computes the coordinates of this view in its window. The argument 11734 * must be an array of two integers. After the method returns, the array 11735 * contains the x and y location in that order.</p> 11736 * 11737 * @param location an array of two integers in which to hold the coordinates 11738 */ 11739 public void getLocationInWindow(int[] location) { 11740 if (location == null || location.length < 2) { 11741 throw new IllegalArgumentException("location must be an array of " 11742 + "two integers"); 11743 } 11744 11745 location[0] = mLeft + (int) (mTranslationX + 0.5f); 11746 location[1] = mTop + (int) (mTranslationY + 0.5f); 11747 11748 ViewParent viewParent = mParent; 11749 while (viewParent instanceof View) { 11750 final View view = (View)viewParent; 11751 location[0] += view.mLeft + (int) (view.mTranslationX + 0.5f) - view.mScrollX; 11752 location[1] += view.mTop + (int) (view.mTranslationY + 0.5f) - view.mScrollY; 11753 viewParent = view.mParent; 11754 } 11755 11756 if (viewParent instanceof ViewRootImpl) { 11757 // *cough* 11758 final ViewRootImpl vr = (ViewRootImpl)viewParent; 11759 location[1] -= vr.mCurScrollY; 11760 } 11761 } 11762 11763 /** 11764 * {@hide} 11765 * @param id the id of the view to be found 11766 * @return the view of the specified id, null if cannot be found 11767 */ 11768 protected View findViewTraversal(int id) { 11769 if (id == mID) { 11770 return this; 11771 } 11772 return null; 11773 } 11774 11775 /** 11776 * {@hide} 11777 * @param tag the tag of the view to be found 11778 * @return the view of specified tag, null if cannot be found 11779 */ 11780 protected View findViewWithTagTraversal(Object tag) { 11781 if (tag != null && tag.equals(mTag)) { 11782 return this; 11783 } 11784 return null; 11785 } 11786 11787 /** 11788 * {@hide} 11789 * @param predicate The predicate to evaluate. 11790 * @param childToSkip If not null, ignores this child during the recursive traversal. 11791 * @return The first view that matches the predicate or null. 11792 */ 11793 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 11794 if (predicate.apply(this)) { 11795 return this; 11796 } 11797 return null; 11798 } 11799 11800 /** 11801 * Look for a child view with the given id. If this view has the given 11802 * id, return this view. 11803 * 11804 * @param id The id to search for. 11805 * @return The view that has the given id in the hierarchy or null 11806 */ 11807 public final View findViewById(int id) { 11808 if (id < 0) { 11809 return null; 11810 } 11811 return findViewTraversal(id); 11812 } 11813 11814 /** 11815 * Look for a child view with the given tag. If this view has the given 11816 * tag, return this view. 11817 * 11818 * @param tag The tag to search for, using "tag.equals(getTag())". 11819 * @return The View that has the given tag in the hierarchy or null 11820 */ 11821 public final View findViewWithTag(Object tag) { 11822 if (tag == null) { 11823 return null; 11824 } 11825 return findViewWithTagTraversal(tag); 11826 } 11827 11828 /** 11829 * {@hide} 11830 * Look for a child view that matches the specified predicate. 11831 * If this view matches the predicate, return this view. 11832 * 11833 * @param predicate The predicate to evaluate. 11834 * @return The first view that matches the predicate or null. 11835 */ 11836 public final View findViewByPredicate(Predicate<View> predicate) { 11837 return findViewByPredicateTraversal(predicate, null); 11838 } 11839 11840 /** 11841 * {@hide} 11842 * Look for a child view that matches the specified predicate, 11843 * starting with the specified view and its descendents and then 11844 * recusively searching the ancestors and siblings of that view 11845 * until this view is reached. 11846 * 11847 * This method is useful in cases where the predicate does not match 11848 * a single unique view (perhaps multiple views use the same id) 11849 * and we are trying to find the view that is "closest" in scope to the 11850 * starting view. 11851 * 11852 * @param start The view to start from. 11853 * @param predicate The predicate to evaluate. 11854 * @return The first view that matches the predicate or null. 11855 */ 11856 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 11857 View childToSkip = null; 11858 for (;;) { 11859 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 11860 if (view != null || start == this) { 11861 return view; 11862 } 11863 11864 ViewParent parent = start.getParent(); 11865 if (parent == null || !(parent instanceof View)) { 11866 return null; 11867 } 11868 11869 childToSkip = start; 11870 start = (View) parent; 11871 } 11872 } 11873 11874 /** 11875 * Sets the identifier for this view. The identifier does not have to be 11876 * unique in this view's hierarchy. The identifier should be a positive 11877 * number. 11878 * 11879 * @see #NO_ID 11880 * @see #getId() 11881 * @see #findViewById(int) 11882 * 11883 * @param id a number used to identify the view 11884 * 11885 * @attr ref android.R.styleable#View_id 11886 */ 11887 public void setId(int id) { 11888 mID = id; 11889 } 11890 11891 /** 11892 * {@hide} 11893 * 11894 * @param isRoot true if the view belongs to the root namespace, false 11895 * otherwise 11896 */ 11897 public void setIsRootNamespace(boolean isRoot) { 11898 if (isRoot) { 11899 mPrivateFlags |= IS_ROOT_NAMESPACE; 11900 } else { 11901 mPrivateFlags &= ~IS_ROOT_NAMESPACE; 11902 } 11903 } 11904 11905 /** 11906 * {@hide} 11907 * 11908 * @return true if the view belongs to the root namespace, false otherwise 11909 */ 11910 public boolean isRootNamespace() { 11911 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0; 11912 } 11913 11914 /** 11915 * Returns this view's identifier. 11916 * 11917 * @return a positive integer used to identify the view or {@link #NO_ID} 11918 * if the view has no ID 11919 * 11920 * @see #setId(int) 11921 * @see #findViewById(int) 11922 * @attr ref android.R.styleable#View_id 11923 */ 11924 @ViewDebug.CapturedViewProperty 11925 public int getId() { 11926 return mID; 11927 } 11928 11929 /** 11930 * Returns this view's tag. 11931 * 11932 * @return the Object stored in this view as a tag 11933 * 11934 * @see #setTag(Object) 11935 * @see #getTag(int) 11936 */ 11937 @ViewDebug.ExportedProperty 11938 public Object getTag() { 11939 return mTag; 11940 } 11941 11942 /** 11943 * Sets the tag associated with this view. A tag can be used to mark 11944 * a view in its hierarchy and does not have to be unique within the 11945 * hierarchy. Tags can also be used to store data within a view without 11946 * resorting to another data structure. 11947 * 11948 * @param tag an Object to tag the view with 11949 * 11950 * @see #getTag() 11951 * @see #setTag(int, Object) 11952 */ 11953 public void setTag(final Object tag) { 11954 mTag = tag; 11955 } 11956 11957 /** 11958 * Returns the tag associated with this view and the specified key. 11959 * 11960 * @param key The key identifying the tag 11961 * 11962 * @return the Object stored in this view as a tag 11963 * 11964 * @see #setTag(int, Object) 11965 * @see #getTag() 11966 */ 11967 public Object getTag(int key) { 11968 SparseArray<Object> tags = null; 11969 synchronized (sTagsLock) { 11970 if (sTags != null) { 11971 tags = sTags.get(this); 11972 } 11973 } 11974 11975 if (tags != null) return tags.get(key); 11976 return null; 11977 } 11978 11979 /** 11980 * Sets a tag associated with this view and a key. A tag can be used 11981 * to mark a view in its hierarchy and does not have to be unique within 11982 * the hierarchy. Tags can also be used to store data within a view 11983 * without resorting to another data structure. 11984 * 11985 * The specified key should be an id declared in the resources of the 11986 * application to ensure it is unique (see the <a 11987 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 11988 * Keys identified as belonging to 11989 * the Android framework or not associated with any package will cause 11990 * an {@link IllegalArgumentException} to be thrown. 11991 * 11992 * @param key The key identifying the tag 11993 * @param tag An Object to tag the view with 11994 * 11995 * @throws IllegalArgumentException If they specified key is not valid 11996 * 11997 * @see #setTag(Object) 11998 * @see #getTag(int) 11999 */ 12000 public void setTag(int key, final Object tag) { 12001 // If the package id is 0x00 or 0x01, it's either an undefined package 12002 // or a framework id 12003 if ((key >>> 24) < 2) { 12004 throw new IllegalArgumentException("The key must be an application-specific " 12005 + "resource id."); 12006 } 12007 12008 setTagInternal(this, key, tag); 12009 } 12010 12011 /** 12012 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 12013 * framework id. 12014 * 12015 * @hide 12016 */ 12017 public void setTagInternal(int key, Object tag) { 12018 if ((key >>> 24) != 0x1) { 12019 throw new IllegalArgumentException("The key must be a framework-specific " 12020 + "resource id."); 12021 } 12022 12023 setTagInternal(this, key, tag); 12024 } 12025 12026 private static void setTagInternal(View view, int key, Object tag) { 12027 SparseArray<Object> tags = null; 12028 synchronized (sTagsLock) { 12029 if (sTags == null) { 12030 sTags = new WeakHashMap<View, SparseArray<Object>>(); 12031 } else { 12032 tags = sTags.get(view); 12033 } 12034 } 12035 12036 if (tags == null) { 12037 tags = new SparseArray<Object>(2); 12038 synchronized (sTagsLock) { 12039 sTags.put(view, tags); 12040 } 12041 } 12042 12043 tags.put(key, tag); 12044 } 12045 12046 /** 12047 * @param consistency The type of consistency. See ViewDebug for more information. 12048 * 12049 * @hide 12050 */ 12051 protected boolean dispatchConsistencyCheck(int consistency) { 12052 return onConsistencyCheck(consistency); 12053 } 12054 12055 /** 12056 * Method that subclasses should implement to check their consistency. The type of 12057 * consistency check is indicated by the bit field passed as a parameter. 12058 * 12059 * @param consistency The type of consistency. See ViewDebug for more information. 12060 * 12061 * @throws IllegalStateException if the view is in an inconsistent state. 12062 * 12063 * @hide 12064 */ 12065 protected boolean onConsistencyCheck(int consistency) { 12066 boolean result = true; 12067 12068 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0; 12069 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0; 12070 12071 if (checkLayout) { 12072 if (getParent() == null) { 12073 result = false; 12074 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 12075 "View " + this + " does not have a parent."); 12076 } 12077 12078 if (mAttachInfo == null) { 12079 result = false; 12080 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 12081 "View " + this + " is not attached to a window."); 12082 } 12083 } 12084 12085 if (checkDrawing) { 12086 // Do not check the DIRTY/DRAWN flags because views can call invalidate() 12087 // from their draw() method 12088 12089 if ((mPrivateFlags & DRAWN) != DRAWN && 12090 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) { 12091 result = false; 12092 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 12093 "View " + this + " was invalidated but its drawing cache is valid."); 12094 } 12095 } 12096 12097 return result; 12098 } 12099 12100 /** 12101 * Prints information about this view in the log output, with the tag 12102 * {@link #VIEW_LOG_TAG}. 12103 * 12104 * @hide 12105 */ 12106 public void debug() { 12107 debug(0); 12108 } 12109 12110 /** 12111 * Prints information about this view in the log output, with the tag 12112 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 12113 * indentation defined by the <code>depth</code>. 12114 * 12115 * @param depth the indentation level 12116 * 12117 * @hide 12118 */ 12119 protected void debug(int depth) { 12120 String output = debugIndent(depth - 1); 12121 12122 output += "+ " + this; 12123 int id = getId(); 12124 if (id != -1) { 12125 output += " (id=" + id + ")"; 12126 } 12127 Object tag = getTag(); 12128 if (tag != null) { 12129 output += " (tag=" + tag + ")"; 12130 } 12131 Log.d(VIEW_LOG_TAG, output); 12132 12133 if ((mPrivateFlags & FOCUSED) != 0) { 12134 output = debugIndent(depth) + " FOCUSED"; 12135 Log.d(VIEW_LOG_TAG, output); 12136 } 12137 12138 output = debugIndent(depth); 12139 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 12140 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 12141 + "} "; 12142 Log.d(VIEW_LOG_TAG, output); 12143 12144 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 12145 || mPaddingBottom != 0) { 12146 output = debugIndent(depth); 12147 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 12148 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 12149 Log.d(VIEW_LOG_TAG, output); 12150 } 12151 12152 output = debugIndent(depth); 12153 output += "mMeasureWidth=" + mMeasuredWidth + 12154 " mMeasureHeight=" + mMeasuredHeight; 12155 Log.d(VIEW_LOG_TAG, output); 12156 12157 output = debugIndent(depth); 12158 if (mLayoutParams == null) { 12159 output += "BAD! no layout params"; 12160 } else { 12161 output = mLayoutParams.debug(output); 12162 } 12163 Log.d(VIEW_LOG_TAG, output); 12164 12165 output = debugIndent(depth); 12166 output += "flags={"; 12167 output += View.printFlags(mViewFlags); 12168 output += "}"; 12169 Log.d(VIEW_LOG_TAG, output); 12170 12171 output = debugIndent(depth); 12172 output += "privateFlags={"; 12173 output += View.printPrivateFlags(mPrivateFlags); 12174 output += "}"; 12175 Log.d(VIEW_LOG_TAG, output); 12176 } 12177 12178 /** 12179 * Creates an string of whitespaces used for indentation. 12180 * 12181 * @param depth the indentation level 12182 * @return a String containing (depth * 2 + 3) * 2 white spaces 12183 * 12184 * @hide 12185 */ 12186 protected static String debugIndent(int depth) { 12187 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 12188 for (int i = 0; i < (depth * 2) + 3; i++) { 12189 spaces.append(' ').append(' '); 12190 } 12191 return spaces.toString(); 12192 } 12193 12194 /** 12195 * <p>Return the offset of the widget's text baseline from the widget's top 12196 * boundary. If this widget does not support baseline alignment, this 12197 * method returns -1. </p> 12198 * 12199 * @return the offset of the baseline within the widget's bounds or -1 12200 * if baseline alignment is not supported 12201 */ 12202 @ViewDebug.ExportedProperty(category = "layout") 12203 public int getBaseline() { 12204 return -1; 12205 } 12206 12207 /** 12208 * Call this when something has changed which has invalidated the 12209 * layout of this view. This will schedule a layout pass of the view 12210 * tree. 12211 */ 12212 public void requestLayout() { 12213 if (ViewDebug.TRACE_HIERARCHY) { 12214 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT); 12215 } 12216 12217 mPrivateFlags |= FORCE_LAYOUT; 12218 mPrivateFlags |= INVALIDATED; 12219 12220 if (mParent != null) { 12221 if (mLayoutParams != null) { 12222 mLayoutParams.resolveWithDirection(getResolvedLayoutDirection()); 12223 } 12224 if (!mParent.isLayoutRequested()) { 12225 mParent.requestLayout(); 12226 } 12227 } 12228 } 12229 12230 /** 12231 * Forces this view to be laid out during the next layout pass. 12232 * This method does not call requestLayout() or forceLayout() 12233 * on the parent. 12234 */ 12235 public void forceLayout() { 12236 mPrivateFlags |= FORCE_LAYOUT; 12237 mPrivateFlags |= INVALIDATED; 12238 } 12239 12240 /** 12241 * <p> 12242 * This is called to find out how big a view should be. The parent 12243 * supplies constraint information in the width and height parameters. 12244 * </p> 12245 * 12246 * <p> 12247 * The actual mesurement work of a view is performed in 12248 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 12249 * {@link #onMeasure(int, int)} can and must be overriden by subclasses. 12250 * </p> 12251 * 12252 * 12253 * @param widthMeasureSpec Horizontal space requirements as imposed by the 12254 * parent 12255 * @param heightMeasureSpec Vertical space requirements as imposed by the 12256 * parent 12257 * 12258 * @see #onMeasure(int, int) 12259 */ 12260 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 12261 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT || 12262 widthMeasureSpec != mOldWidthMeasureSpec || 12263 heightMeasureSpec != mOldHeightMeasureSpec) { 12264 12265 // first clears the measured dimension flag 12266 mPrivateFlags &= ~MEASURED_DIMENSION_SET; 12267 12268 if (ViewDebug.TRACE_HIERARCHY) { 12269 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE); 12270 } 12271 12272 // measure ourselves, this should set the measured dimension flag back 12273 onMeasure(widthMeasureSpec, heightMeasureSpec); 12274 12275 // flag not set, setMeasuredDimension() was not invoked, we raise 12276 // an exception to warn the developer 12277 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) { 12278 throw new IllegalStateException("onMeasure() did not set the" 12279 + " measured dimension by calling" 12280 + " setMeasuredDimension()"); 12281 } 12282 12283 mPrivateFlags |= LAYOUT_REQUIRED; 12284 } 12285 12286 mOldWidthMeasureSpec = widthMeasureSpec; 12287 mOldHeightMeasureSpec = heightMeasureSpec; 12288 } 12289 12290 /** 12291 * <p> 12292 * Measure the view and its content to determine the measured width and the 12293 * measured height. This method is invoked by {@link #measure(int, int)} and 12294 * should be overriden by subclasses to provide accurate and efficient 12295 * measurement of their contents. 12296 * </p> 12297 * 12298 * <p> 12299 * <strong>CONTRACT:</strong> When overriding this method, you 12300 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 12301 * measured width and height of this view. Failure to do so will trigger an 12302 * <code>IllegalStateException</code>, thrown by 12303 * {@link #measure(int, int)}. Calling the superclass' 12304 * {@link #onMeasure(int, int)} is a valid use. 12305 * </p> 12306 * 12307 * <p> 12308 * The base class implementation of measure defaults to the background size, 12309 * unless a larger size is allowed by the MeasureSpec. Subclasses should 12310 * override {@link #onMeasure(int, int)} to provide better measurements of 12311 * their content. 12312 * </p> 12313 * 12314 * <p> 12315 * If this method is overridden, it is the subclass's responsibility to make 12316 * sure the measured height and width are at least the view's minimum height 12317 * and width ({@link #getSuggestedMinimumHeight()} and 12318 * {@link #getSuggestedMinimumWidth()}). 12319 * </p> 12320 * 12321 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 12322 * The requirements are encoded with 12323 * {@link android.view.View.MeasureSpec}. 12324 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 12325 * The requirements are encoded with 12326 * {@link android.view.View.MeasureSpec}. 12327 * 12328 * @see #getMeasuredWidth() 12329 * @see #getMeasuredHeight() 12330 * @see #setMeasuredDimension(int, int) 12331 * @see #getSuggestedMinimumHeight() 12332 * @see #getSuggestedMinimumWidth() 12333 * @see android.view.View.MeasureSpec#getMode(int) 12334 * @see android.view.View.MeasureSpec#getSize(int) 12335 */ 12336 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 12337 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 12338 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 12339 } 12340 12341 /** 12342 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the 12343 * measured width and measured height. Failing to do so will trigger an 12344 * exception at measurement time.</p> 12345 * 12346 * @param measuredWidth The measured width of this view. May be a complex 12347 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 12348 * {@link #MEASURED_STATE_TOO_SMALL}. 12349 * @param measuredHeight The measured height of this view. May be a complex 12350 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 12351 * {@link #MEASURED_STATE_TOO_SMALL}. 12352 */ 12353 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 12354 mMeasuredWidth = measuredWidth; 12355 mMeasuredHeight = measuredHeight; 12356 12357 mPrivateFlags |= MEASURED_DIMENSION_SET; 12358 } 12359 12360 /** 12361 * Merge two states as returned by {@link #getMeasuredState()}. 12362 * @param curState The current state as returned from a view or the result 12363 * of combining multiple views. 12364 * @param newState The new view state to combine. 12365 * @return Returns a new integer reflecting the combination of the two 12366 * states. 12367 */ 12368 public static int combineMeasuredStates(int curState, int newState) { 12369 return curState | newState; 12370 } 12371 12372 /** 12373 * Version of {@link #resolveSizeAndState(int, int, int)} 12374 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 12375 */ 12376 public static int resolveSize(int size, int measureSpec) { 12377 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 12378 } 12379 12380 /** 12381 * Utility to reconcile a desired size and state, with constraints imposed 12382 * by a MeasureSpec. Will take the desired size, unless a different size 12383 * is imposed by the constraints. The returned value is a compound integer, 12384 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 12385 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 12386 * size is smaller than the size the view wants to be. 12387 * 12388 * @param size How big the view wants to be 12389 * @param measureSpec Constraints imposed by the parent 12390 * @return Size information bit mask as defined by 12391 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 12392 */ 12393 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 12394 int result = size; 12395 int specMode = MeasureSpec.getMode(measureSpec); 12396 int specSize = MeasureSpec.getSize(measureSpec); 12397 switch (specMode) { 12398 case MeasureSpec.UNSPECIFIED: 12399 result = size; 12400 break; 12401 case MeasureSpec.AT_MOST: 12402 if (specSize < size) { 12403 result = specSize | MEASURED_STATE_TOO_SMALL; 12404 } else { 12405 result = size; 12406 } 12407 break; 12408 case MeasureSpec.EXACTLY: 12409 result = specSize; 12410 break; 12411 } 12412 return result | (childMeasuredState&MEASURED_STATE_MASK); 12413 } 12414 12415 /** 12416 * Utility to return a default size. Uses the supplied size if the 12417 * MeasureSpec imposed no constraints. Will get larger if allowed 12418 * by the MeasureSpec. 12419 * 12420 * @param size Default size for this view 12421 * @param measureSpec Constraints imposed by the parent 12422 * @return The size this view should be. 12423 */ 12424 public static int getDefaultSize(int size, int measureSpec) { 12425 int result = size; 12426 int specMode = MeasureSpec.getMode(measureSpec); 12427 int specSize = MeasureSpec.getSize(measureSpec); 12428 12429 switch (specMode) { 12430 case MeasureSpec.UNSPECIFIED: 12431 result = size; 12432 break; 12433 case MeasureSpec.AT_MOST: 12434 case MeasureSpec.EXACTLY: 12435 result = specSize; 12436 break; 12437 } 12438 return result; 12439 } 12440 12441 /** 12442 * Returns the suggested minimum height that the view should use. This 12443 * returns the maximum of the view's minimum height 12444 * and the background's minimum height 12445 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 12446 * <p> 12447 * When being used in {@link #onMeasure(int, int)}, the caller should still 12448 * ensure the returned height is within the requirements of the parent. 12449 * 12450 * @return The suggested minimum height of the view. 12451 */ 12452 protected int getSuggestedMinimumHeight() { 12453 int suggestedMinHeight = mMinHeight; 12454 12455 if (mBGDrawable != null) { 12456 final int bgMinHeight = mBGDrawable.getMinimumHeight(); 12457 if (suggestedMinHeight < bgMinHeight) { 12458 suggestedMinHeight = bgMinHeight; 12459 } 12460 } 12461 12462 return suggestedMinHeight; 12463 } 12464 12465 /** 12466 * Returns the suggested minimum width that the view should use. This 12467 * returns the maximum of the view's minimum width) 12468 * and the background's minimum width 12469 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 12470 * <p> 12471 * When being used in {@link #onMeasure(int, int)}, the caller should still 12472 * ensure the returned width is within the requirements of the parent. 12473 * 12474 * @return The suggested minimum width of the view. 12475 */ 12476 protected int getSuggestedMinimumWidth() { 12477 int suggestedMinWidth = mMinWidth; 12478 12479 if (mBGDrawable != null) { 12480 final int bgMinWidth = mBGDrawable.getMinimumWidth(); 12481 if (suggestedMinWidth < bgMinWidth) { 12482 suggestedMinWidth = bgMinWidth; 12483 } 12484 } 12485 12486 return suggestedMinWidth; 12487 } 12488 12489 /** 12490 * Sets the minimum height of the view. It is not guaranteed the view will 12491 * be able to achieve this minimum height (for example, if its parent layout 12492 * constrains it with less available height). 12493 * 12494 * @param minHeight The minimum height the view will try to be. 12495 */ 12496 public void setMinimumHeight(int minHeight) { 12497 mMinHeight = minHeight; 12498 } 12499 12500 /** 12501 * Sets the minimum width of the view. It is not guaranteed the view will 12502 * be able to achieve this minimum width (for example, if its parent layout 12503 * constrains it with less available width). 12504 * 12505 * @param minWidth The minimum width the view will try to be. 12506 */ 12507 public void setMinimumWidth(int minWidth) { 12508 mMinWidth = minWidth; 12509 } 12510 12511 /** 12512 * Get the animation currently associated with this view. 12513 * 12514 * @return The animation that is currently playing or 12515 * scheduled to play for this view. 12516 */ 12517 public Animation getAnimation() { 12518 return mCurrentAnimation; 12519 } 12520 12521 /** 12522 * Start the specified animation now. 12523 * 12524 * @param animation the animation to start now 12525 */ 12526 public void startAnimation(Animation animation) { 12527 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 12528 setAnimation(animation); 12529 invalidateParentCaches(); 12530 invalidate(true); 12531 } 12532 12533 /** 12534 * Cancels any animations for this view. 12535 */ 12536 public void clearAnimation() { 12537 if (mCurrentAnimation != null) { 12538 mCurrentAnimation.detach(); 12539 } 12540 mCurrentAnimation = null; 12541 invalidateParentIfNeeded(); 12542 } 12543 12544 /** 12545 * Sets the next animation to play for this view. 12546 * If you want the animation to play immediately, use 12547 * startAnimation. This method provides allows fine-grained 12548 * control over the start time and invalidation, but you 12549 * must make sure that 1) the animation has a start time set, and 12550 * 2) the view will be invalidated when the animation is supposed to 12551 * start. 12552 * 12553 * @param animation The next animation, or null. 12554 */ 12555 public void setAnimation(Animation animation) { 12556 mCurrentAnimation = animation; 12557 if (animation != null) { 12558 animation.reset(); 12559 } 12560 } 12561 12562 /** 12563 * Invoked by a parent ViewGroup to notify the start of the animation 12564 * currently associated with this view. If you override this method, 12565 * always call super.onAnimationStart(); 12566 * 12567 * @see #setAnimation(android.view.animation.Animation) 12568 * @see #getAnimation() 12569 */ 12570 protected void onAnimationStart() { 12571 mPrivateFlags |= ANIMATION_STARTED; 12572 } 12573 12574 /** 12575 * Invoked by a parent ViewGroup to notify the end of the animation 12576 * currently associated with this view. If you override this method, 12577 * always call super.onAnimationEnd(); 12578 * 12579 * @see #setAnimation(android.view.animation.Animation) 12580 * @see #getAnimation() 12581 */ 12582 protected void onAnimationEnd() { 12583 mPrivateFlags &= ~ANIMATION_STARTED; 12584 } 12585 12586 /** 12587 * Invoked if there is a Transform that involves alpha. Subclass that can 12588 * draw themselves with the specified alpha should return true, and then 12589 * respect that alpha when their onDraw() is called. If this returns false 12590 * then the view may be redirected to draw into an offscreen buffer to 12591 * fulfill the request, which will look fine, but may be slower than if the 12592 * subclass handles it internally. The default implementation returns false. 12593 * 12594 * @param alpha The alpha (0..255) to apply to the view's drawing 12595 * @return true if the view can draw with the specified alpha. 12596 */ 12597 protected boolean onSetAlpha(int alpha) { 12598 return false; 12599 } 12600 12601 /** 12602 * This is used by the RootView to perform an optimization when 12603 * the view hierarchy contains one or several SurfaceView. 12604 * SurfaceView is always considered transparent, but its children are not, 12605 * therefore all View objects remove themselves from the global transparent 12606 * region (passed as a parameter to this function). 12607 * 12608 * @param region The transparent region for this ViewAncestor (window). 12609 * 12610 * @return Returns true if the effective visibility of the view at this 12611 * point is opaque, regardless of the transparent region; returns false 12612 * if it is possible for underlying windows to be seen behind the view. 12613 * 12614 * {@hide} 12615 */ 12616 public boolean gatherTransparentRegion(Region region) { 12617 final AttachInfo attachInfo = mAttachInfo; 12618 if (region != null && attachInfo != null) { 12619 final int pflags = mPrivateFlags; 12620 if ((pflags & SKIP_DRAW) == 0) { 12621 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 12622 // remove it from the transparent region. 12623 final int[] location = attachInfo.mTransparentLocation; 12624 getLocationInWindow(location); 12625 region.op(location[0], location[1], location[0] + mRight - mLeft, 12626 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 12627 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) { 12628 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 12629 // exists, so we remove the background drawable's non-transparent 12630 // parts from this transparent region. 12631 applyDrawableToTransparentRegion(mBGDrawable, region); 12632 } 12633 } 12634 return true; 12635 } 12636 12637 /** 12638 * Play a sound effect for this view. 12639 * 12640 * <p>The framework will play sound effects for some built in actions, such as 12641 * clicking, but you may wish to play these effects in your widget, 12642 * for instance, for internal navigation. 12643 * 12644 * <p>The sound effect will only be played if sound effects are enabled by the user, and 12645 * {@link #isSoundEffectsEnabled()} is true. 12646 * 12647 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 12648 */ 12649 public void playSoundEffect(int soundConstant) { 12650 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 12651 return; 12652 } 12653 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 12654 } 12655 12656 /** 12657 * BZZZTT!!1! 12658 * 12659 * <p>Provide haptic feedback to the user for this view. 12660 * 12661 * <p>The framework will provide haptic feedback for some built in actions, 12662 * such as long presses, but you may wish to provide feedback for your 12663 * own widget. 12664 * 12665 * <p>The feedback will only be performed if 12666 * {@link #isHapticFeedbackEnabled()} is true. 12667 * 12668 * @param feedbackConstant One of the constants defined in 12669 * {@link HapticFeedbackConstants} 12670 */ 12671 public boolean performHapticFeedback(int feedbackConstant) { 12672 return performHapticFeedback(feedbackConstant, 0); 12673 } 12674 12675 /** 12676 * BZZZTT!!1! 12677 * 12678 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 12679 * 12680 * @param feedbackConstant One of the constants defined in 12681 * {@link HapticFeedbackConstants} 12682 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 12683 */ 12684 public boolean performHapticFeedback(int feedbackConstant, int flags) { 12685 if (mAttachInfo == null) { 12686 return false; 12687 } 12688 //noinspection SimplifiableIfStatement 12689 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 12690 && !isHapticFeedbackEnabled()) { 12691 return false; 12692 } 12693 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 12694 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 12695 } 12696 12697 /** 12698 * Request that the visibility of the status bar be changed. 12699 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or 12700 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. 12701 * 12702 * This value will be re-applied immediately, even if the flags have not changed, so a view may 12703 * easily reassert a particular SystemUiVisibility condition even if the system UI itself has 12704 * since countermanded the original request. 12705 */ 12706 public void setSystemUiVisibility(int visibility) { 12707 mSystemUiVisibility = visibility; 12708 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 12709 mParent.recomputeViewAttributes(this); 12710 } 12711 } 12712 12713 /** 12714 * Returns the status bar visibility that this view has requested. 12715 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or 12716 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. 12717 */ 12718 public int getSystemUiVisibility() { 12719 return mSystemUiVisibility; 12720 } 12721 12722 /** 12723 * Set a listener to receive callbacks when the visibility of the system bar changes. 12724 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 12725 */ 12726 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 12727 mOnSystemUiVisibilityChangeListener = l; 12728 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 12729 mParent.recomputeViewAttributes(this); 12730 } 12731 } 12732 12733 /** 12734 */ 12735 public void dispatchSystemUiVisibilityChanged(int visibility) { 12736 if (mOnSystemUiVisibilityChangeListener != null) { 12737 mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 12738 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 12739 } 12740 } 12741 12742 /** 12743 * Creates an image that the system displays during the drag and drop 12744 * operation. This is called a "drag shadow". The default implementation 12745 * for a DragShadowBuilder based on a View returns an image that has exactly the same 12746 * appearance as the given View. The default also positions the center of the drag shadow 12747 * directly under the touch point. If no View is provided (the constructor with no parameters 12748 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 12749 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 12750 * default is an invisible drag shadow. 12751 * <p> 12752 * You are not required to use the View you provide to the constructor as the basis of the 12753 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 12754 * anything you want as the drag shadow. 12755 * </p> 12756 * <p> 12757 * You pass a DragShadowBuilder object to the system when you start the drag. The system 12758 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 12759 * size and position of the drag shadow. It uses this data to construct a 12760 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 12761 * so that your application can draw the shadow image in the Canvas. 12762 * </p> 12763 */ 12764 public static class DragShadowBuilder { 12765 private final WeakReference<View> mView; 12766 12767 /** 12768 * Constructs a shadow image builder based on a View. By default, the resulting drag 12769 * shadow will have the same appearance and dimensions as the View, with the touch point 12770 * over the center of the View. 12771 * @param view A View. Any View in scope can be used. 12772 */ 12773 public DragShadowBuilder(View view) { 12774 mView = new WeakReference<View>(view); 12775 } 12776 12777 /** 12778 * Construct a shadow builder object with no associated View. This 12779 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 12780 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 12781 * to supply the drag shadow's dimensions and appearance without 12782 * reference to any View object. If they are not overridden, then the result is an 12783 * invisible drag shadow. 12784 */ 12785 public DragShadowBuilder() { 12786 mView = new WeakReference<View>(null); 12787 } 12788 12789 /** 12790 * Returns the View object that had been passed to the 12791 * {@link #View.DragShadowBuilder(View)} 12792 * constructor. If that View parameter was {@code null} or if the 12793 * {@link #View.DragShadowBuilder()} 12794 * constructor was used to instantiate the builder object, this method will return 12795 * null. 12796 * 12797 * @return The View object associate with this builder object. 12798 */ 12799 @SuppressWarnings({"JavadocReference"}) 12800 final public View getView() { 12801 return mView.get(); 12802 } 12803 12804 /** 12805 * Provides the metrics for the shadow image. These include the dimensions of 12806 * the shadow image, and the point within that shadow that should 12807 * be centered under the touch location while dragging. 12808 * <p> 12809 * The default implementation sets the dimensions of the shadow to be the 12810 * same as the dimensions of the View itself and centers the shadow under 12811 * the touch point. 12812 * </p> 12813 * 12814 * @param shadowSize A {@link android.graphics.Point} containing the width and height 12815 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 12816 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 12817 * image. 12818 * 12819 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 12820 * shadow image that should be underneath the touch point during the drag and drop 12821 * operation. Your application must set {@link android.graphics.Point#x} to the 12822 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 12823 */ 12824 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 12825 final View view = mView.get(); 12826 if (view != null) { 12827 shadowSize.set(view.getWidth(), view.getHeight()); 12828 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 12829 } else { 12830 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 12831 } 12832 } 12833 12834 /** 12835 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 12836 * based on the dimensions it received from the 12837 * {@link #onProvideShadowMetrics(Point, Point)} callback. 12838 * 12839 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 12840 */ 12841 public void onDrawShadow(Canvas canvas) { 12842 final View view = mView.get(); 12843 if (view != null) { 12844 view.draw(canvas); 12845 } else { 12846 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 12847 } 12848 } 12849 } 12850 12851 /** 12852 * Starts a drag and drop operation. When your application calls this method, it passes a 12853 * {@link android.view.View.DragShadowBuilder} object to the system. The 12854 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 12855 * to get metrics for the drag shadow, and then calls the object's 12856 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 12857 * <p> 12858 * Once the system has the drag shadow, it begins the drag and drop operation by sending 12859 * drag events to all the View objects in your application that are currently visible. It does 12860 * this either by calling the View object's drag listener (an implementation of 12861 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 12862 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 12863 * Both are passed a {@link android.view.DragEvent} object that has a 12864 * {@link android.view.DragEvent#getAction()} value of 12865 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 12866 * </p> 12867 * <p> 12868 * Your application can invoke startDrag() on any attached View object. The View object does not 12869 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 12870 * be related to the View the user selected for dragging. 12871 * </p> 12872 * @param data A {@link android.content.ClipData} object pointing to the data to be 12873 * transferred by the drag and drop operation. 12874 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 12875 * drag shadow. 12876 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 12877 * drop operation. This Object is put into every DragEvent object sent by the system during the 12878 * current drag. 12879 * <p> 12880 * myLocalState is a lightweight mechanism for the sending information from the dragged View 12881 * to the target Views. For example, it can contain flags that differentiate between a 12882 * a copy operation and a move operation. 12883 * </p> 12884 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 12885 * so the parameter should be set to 0. 12886 * @return {@code true} if the method completes successfully, or 12887 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 12888 * do a drag, and so no drag operation is in progress. 12889 */ 12890 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 12891 Object myLocalState, int flags) { 12892 if (ViewDebug.DEBUG_DRAG) { 12893 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 12894 } 12895 boolean okay = false; 12896 12897 Point shadowSize = new Point(); 12898 Point shadowTouchPoint = new Point(); 12899 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 12900 12901 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 12902 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 12903 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 12904 } 12905 12906 if (ViewDebug.DEBUG_DRAG) { 12907 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 12908 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 12909 } 12910 Surface surface = new Surface(); 12911 try { 12912 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 12913 flags, shadowSize.x, shadowSize.y, surface); 12914 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 12915 + " surface=" + surface); 12916 if (token != null) { 12917 Canvas canvas = surface.lockCanvas(null); 12918 try { 12919 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 12920 shadowBuilder.onDrawShadow(canvas); 12921 } finally { 12922 surface.unlockCanvasAndPost(canvas); 12923 } 12924 12925 final ViewRootImpl root = getViewRootImpl(); 12926 12927 // Cache the local state object for delivery with DragEvents 12928 root.setLocalDragState(myLocalState); 12929 12930 // repurpose 'shadowSize' for the last touch point 12931 root.getLastTouchPoint(shadowSize); 12932 12933 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 12934 shadowSize.x, shadowSize.y, 12935 shadowTouchPoint.x, shadowTouchPoint.y, data); 12936 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 12937 } 12938 } catch (Exception e) { 12939 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 12940 surface.destroy(); 12941 } 12942 12943 return okay; 12944 } 12945 12946 /** 12947 * Handles drag events sent by the system following a call to 12948 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 12949 *<p> 12950 * When the system calls this method, it passes a 12951 * {@link android.view.DragEvent} object. A call to 12952 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 12953 * in DragEvent. The method uses these to determine what is happening in the drag and drop 12954 * operation. 12955 * @param event The {@link android.view.DragEvent} sent by the system. 12956 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 12957 * in DragEvent, indicating the type of drag event represented by this object. 12958 * @return {@code true} if the method was successful, otherwise {@code false}. 12959 * <p> 12960 * The method should return {@code true} in response to an action type of 12961 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 12962 * operation. 12963 * </p> 12964 * <p> 12965 * The method should also return {@code true} in response to an action type of 12966 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 12967 * {@code false} if it didn't. 12968 * </p> 12969 */ 12970 public boolean onDragEvent(DragEvent event) { 12971 return false; 12972 } 12973 12974 /** 12975 * Detects if this View is enabled and has a drag event listener. 12976 * If both are true, then it calls the drag event listener with the 12977 * {@link android.view.DragEvent} it received. If the drag event listener returns 12978 * {@code true}, then dispatchDragEvent() returns {@code true}. 12979 * <p> 12980 * For all other cases, the method calls the 12981 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 12982 * method and returns its result. 12983 * </p> 12984 * <p> 12985 * This ensures that a drag event is always consumed, even if the View does not have a drag 12986 * event listener. However, if the View has a listener and the listener returns true, then 12987 * onDragEvent() is not called. 12988 * </p> 12989 */ 12990 public boolean dispatchDragEvent(DragEvent event) { 12991 //noinspection SimplifiableIfStatement 12992 if (mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 12993 && mOnDragListener.onDrag(this, event)) { 12994 return true; 12995 } 12996 return onDragEvent(event); 12997 } 12998 12999 boolean canAcceptDrag() { 13000 return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0; 13001 } 13002 13003 /** 13004 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 13005 * it is ever exposed at all. 13006 * @hide 13007 */ 13008 public void onCloseSystemDialogs(String reason) { 13009 } 13010 13011 /** 13012 * Given a Drawable whose bounds have been set to draw into this view, 13013 * update a Region being computed for 13014 * {@link #gatherTransparentRegion(android.graphics.Region)} so 13015 * that any non-transparent parts of the Drawable are removed from the 13016 * given transparent region. 13017 * 13018 * @param dr The Drawable whose transparency is to be applied to the region. 13019 * @param region A Region holding the current transparency information, 13020 * where any parts of the region that are set are considered to be 13021 * transparent. On return, this region will be modified to have the 13022 * transparency information reduced by the corresponding parts of the 13023 * Drawable that are not transparent. 13024 * {@hide} 13025 */ 13026 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 13027 if (DBG) { 13028 Log.i("View", "Getting transparent region for: " + this); 13029 } 13030 final Region r = dr.getTransparentRegion(); 13031 final Rect db = dr.getBounds(); 13032 final AttachInfo attachInfo = mAttachInfo; 13033 if (r != null && attachInfo != null) { 13034 final int w = getRight()-getLeft(); 13035 final int h = getBottom()-getTop(); 13036 if (db.left > 0) { 13037 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 13038 r.op(0, 0, db.left, h, Region.Op.UNION); 13039 } 13040 if (db.right < w) { 13041 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 13042 r.op(db.right, 0, w, h, Region.Op.UNION); 13043 } 13044 if (db.top > 0) { 13045 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 13046 r.op(0, 0, w, db.top, Region.Op.UNION); 13047 } 13048 if (db.bottom < h) { 13049 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 13050 r.op(0, db.bottom, w, h, Region.Op.UNION); 13051 } 13052 final int[] location = attachInfo.mTransparentLocation; 13053 getLocationInWindow(location); 13054 r.translate(location[0], location[1]); 13055 region.op(r, Region.Op.INTERSECT); 13056 } else { 13057 region.op(db, Region.Op.DIFFERENCE); 13058 } 13059 } 13060 13061 private void checkForLongClick(int delayOffset) { 13062 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 13063 mHasPerformedLongPress = false; 13064 13065 if (mPendingCheckForLongPress == null) { 13066 mPendingCheckForLongPress = new CheckForLongPress(); 13067 } 13068 mPendingCheckForLongPress.rememberWindowAttachCount(); 13069 postDelayed(mPendingCheckForLongPress, 13070 ViewConfiguration.getLongPressTimeout() - delayOffset); 13071 } 13072 } 13073 13074 /** 13075 * Inflate a view from an XML resource. This convenience method wraps the {@link 13076 * LayoutInflater} class, which provides a full range of options for view inflation. 13077 * 13078 * @param context The Context object for your activity or application. 13079 * @param resource The resource ID to inflate 13080 * @param root A view group that will be the parent. Used to properly inflate the 13081 * layout_* parameters. 13082 * @see LayoutInflater 13083 */ 13084 public static View inflate(Context context, int resource, ViewGroup root) { 13085 LayoutInflater factory = LayoutInflater.from(context); 13086 return factory.inflate(resource, root); 13087 } 13088 13089 /** 13090 * Scroll the view with standard behavior for scrolling beyond the normal 13091 * content boundaries. Views that call this method should override 13092 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 13093 * results of an over-scroll operation. 13094 * 13095 * Views can use this method to handle any touch or fling-based scrolling. 13096 * 13097 * @param deltaX Change in X in pixels 13098 * @param deltaY Change in Y in pixels 13099 * @param scrollX Current X scroll value in pixels before applying deltaX 13100 * @param scrollY Current Y scroll value in pixels before applying deltaY 13101 * @param scrollRangeX Maximum content scroll range along the X axis 13102 * @param scrollRangeY Maximum content scroll range along the Y axis 13103 * @param maxOverScrollX Number of pixels to overscroll by in either direction 13104 * along the X axis. 13105 * @param maxOverScrollY Number of pixels to overscroll by in either direction 13106 * along the Y axis. 13107 * @param isTouchEvent true if this scroll operation is the result of a touch event. 13108 * @return true if scrolling was clamped to an over-scroll boundary along either 13109 * axis, false otherwise. 13110 */ 13111 @SuppressWarnings({"UnusedParameters"}) 13112 protected boolean overScrollBy(int deltaX, int deltaY, 13113 int scrollX, int scrollY, 13114 int scrollRangeX, int scrollRangeY, 13115 int maxOverScrollX, int maxOverScrollY, 13116 boolean isTouchEvent) { 13117 final int overScrollMode = mOverScrollMode; 13118 final boolean canScrollHorizontal = 13119 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 13120 final boolean canScrollVertical = 13121 computeVerticalScrollRange() > computeVerticalScrollExtent(); 13122 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 13123 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 13124 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 13125 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 13126 13127 int newScrollX = scrollX + deltaX; 13128 if (!overScrollHorizontal) { 13129 maxOverScrollX = 0; 13130 } 13131 13132 int newScrollY = scrollY + deltaY; 13133 if (!overScrollVertical) { 13134 maxOverScrollY = 0; 13135 } 13136 13137 // Clamp values if at the limits and record 13138 final int left = -maxOverScrollX; 13139 final int right = maxOverScrollX + scrollRangeX; 13140 final int top = -maxOverScrollY; 13141 final int bottom = maxOverScrollY + scrollRangeY; 13142 13143 boolean clampedX = false; 13144 if (newScrollX > right) { 13145 newScrollX = right; 13146 clampedX = true; 13147 } else if (newScrollX < left) { 13148 newScrollX = left; 13149 clampedX = true; 13150 } 13151 13152 boolean clampedY = false; 13153 if (newScrollY > bottom) { 13154 newScrollY = bottom; 13155 clampedY = true; 13156 } else if (newScrollY < top) { 13157 newScrollY = top; 13158 clampedY = true; 13159 } 13160 13161 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 13162 13163 return clampedX || clampedY; 13164 } 13165 13166 /** 13167 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 13168 * respond to the results of an over-scroll operation. 13169 * 13170 * @param scrollX New X scroll value in pixels 13171 * @param scrollY New Y scroll value in pixels 13172 * @param clampedX True if scrollX was clamped to an over-scroll boundary 13173 * @param clampedY True if scrollY was clamped to an over-scroll boundary 13174 */ 13175 protected void onOverScrolled(int scrollX, int scrollY, 13176 boolean clampedX, boolean clampedY) { 13177 // Intentionally empty. 13178 } 13179 13180 /** 13181 * Returns the over-scroll mode for this view. The result will be 13182 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 13183 * (allow over-scrolling only if the view content is larger than the container), 13184 * or {@link #OVER_SCROLL_NEVER}. 13185 * 13186 * @return This view's over-scroll mode. 13187 */ 13188 public int getOverScrollMode() { 13189 return mOverScrollMode; 13190 } 13191 13192 /** 13193 * Set the over-scroll mode for this view. Valid over-scroll modes are 13194 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 13195 * (allow over-scrolling only if the view content is larger than the container), 13196 * or {@link #OVER_SCROLL_NEVER}. 13197 * 13198 * Setting the over-scroll mode of a view will have an effect only if the 13199 * view is capable of scrolling. 13200 * 13201 * @param overScrollMode The new over-scroll mode for this view. 13202 */ 13203 public void setOverScrollMode(int overScrollMode) { 13204 if (overScrollMode != OVER_SCROLL_ALWAYS && 13205 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 13206 overScrollMode != OVER_SCROLL_NEVER) { 13207 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 13208 } 13209 mOverScrollMode = overScrollMode; 13210 } 13211 13212 /** 13213 * Gets a scale factor that determines the distance the view should scroll 13214 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 13215 * @return The vertical scroll scale factor. 13216 * @hide 13217 */ 13218 protected float getVerticalScrollFactor() { 13219 if (mVerticalScrollFactor == 0) { 13220 TypedValue outValue = new TypedValue(); 13221 if (!mContext.getTheme().resolveAttribute( 13222 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 13223 throw new IllegalStateException( 13224 "Expected theme to define listPreferredItemHeight."); 13225 } 13226 mVerticalScrollFactor = outValue.getDimension( 13227 mContext.getResources().getDisplayMetrics()); 13228 } 13229 return mVerticalScrollFactor; 13230 } 13231 13232 /** 13233 * Gets a scale factor that determines the distance the view should scroll 13234 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 13235 * @return The horizontal scroll scale factor. 13236 * @hide 13237 */ 13238 protected float getHorizontalScrollFactor() { 13239 // TODO: Should use something else. 13240 return getVerticalScrollFactor(); 13241 } 13242 13243 /** 13244 * Return the value specifying the text direction or policy that was set with 13245 * {@link #setTextDirection(int)}. 13246 * 13247 * @return the defined text direction. It can be one of: 13248 * 13249 * {@link #TEXT_DIRECTION_INHERIT}, 13250 * {@link #TEXT_DIRECTION_FIRST_STRONG} 13251 * {@link #TEXT_DIRECTION_ANY_RTL}, 13252 * {@link #TEXT_DIRECTION_LTR}, 13253 * {@link #TEXT_DIRECTION_RTL}, 13254 * 13255 * @hide 13256 */ 13257 public int getTextDirection() { 13258 return mTextDirection; 13259 } 13260 13261 /** 13262 * Set the text direction. 13263 * 13264 * @param textDirection the direction to set. Should be one of: 13265 * 13266 * {@link #TEXT_DIRECTION_INHERIT}, 13267 * {@link #TEXT_DIRECTION_FIRST_STRONG} 13268 * {@link #TEXT_DIRECTION_ANY_RTL}, 13269 * {@link #TEXT_DIRECTION_LTR}, 13270 * {@link #TEXT_DIRECTION_RTL}, 13271 * 13272 * @hide 13273 */ 13274 public void setTextDirection(int textDirection) { 13275 if (textDirection != mTextDirection) { 13276 mTextDirection = textDirection; 13277 resetResolvedTextDirection(); 13278 requestLayout(); 13279 } 13280 } 13281 13282 /** 13283 * Return the resolved text direction. 13284 * 13285 * @return the resolved text direction. Return one of: 13286 * 13287 * {@link #TEXT_DIRECTION_FIRST_STRONG} 13288 * {@link #TEXT_DIRECTION_ANY_RTL}, 13289 * {@link #TEXT_DIRECTION_LTR}, 13290 * {@link #TEXT_DIRECTION_RTL}, 13291 * 13292 * @hide 13293 */ 13294 public int getResolvedTextDirection() { 13295 if (mResolvedTextDirection == TEXT_DIRECTION_INHERIT) { 13296 resolveTextDirection(); 13297 } 13298 return mResolvedTextDirection; 13299 } 13300 13301 /** 13302 * Resolve the text direction. 13303 * 13304 * @hide 13305 */ 13306 protected void resolveTextDirection() { 13307 if (mTextDirection != TEXT_DIRECTION_INHERIT) { 13308 mResolvedTextDirection = mTextDirection; 13309 return; 13310 } 13311 if (mParent != null && mParent instanceof ViewGroup) { 13312 mResolvedTextDirection = ((ViewGroup) mParent).getResolvedTextDirection(); 13313 return; 13314 } 13315 mResolvedTextDirection = TEXT_DIRECTION_FIRST_STRONG; 13316 } 13317 13318 /** 13319 * Reset resolved text direction. Will be resolved during a call to getResolvedTextDirection(). 13320 * 13321 * @hide 13322 */ 13323 protected void resetResolvedTextDirection() { 13324 mResolvedTextDirection = TEXT_DIRECTION_INHERIT; 13325 } 13326 13327 // 13328 // Properties 13329 // 13330 /** 13331 * A Property wrapper around the <code>alpha</code> functionality handled by the 13332 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 13333 */ 13334 public static Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 13335 @Override 13336 public void setValue(View object, float value) { 13337 object.setAlpha(value); 13338 } 13339 13340 @Override 13341 public Float get(View object) { 13342 return object.getAlpha(); 13343 } 13344 }; 13345 13346 /** 13347 * A Property wrapper around the <code>translationX</code> functionality handled by the 13348 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 13349 */ 13350 public static Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 13351 @Override 13352 public void setValue(View object, float value) { 13353 object.setTranslationX(value); 13354 } 13355 13356 @Override 13357 public Float get(View object) { 13358 return object.getTranslationX(); 13359 } 13360 }; 13361 13362 /** 13363 * A Property wrapper around the <code>translationY</code> functionality handled by the 13364 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 13365 */ 13366 public static Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 13367 @Override 13368 public void setValue(View object, float value) { 13369 object.setTranslationY(value); 13370 } 13371 13372 @Override 13373 public Float get(View object) { 13374 return object.getTranslationY(); 13375 } 13376 }; 13377 13378 /** 13379 * A Property wrapper around the <code>x</code> functionality handled by the 13380 * {@link View#setX(float)} and {@link View#getX()} methods. 13381 */ 13382 public static Property<View, Float> X = new FloatProperty<View>("x") { 13383 @Override 13384 public void setValue(View object, float value) { 13385 object.setX(value); 13386 } 13387 13388 @Override 13389 public Float get(View object) { 13390 return object.getX(); 13391 } 13392 }; 13393 13394 /** 13395 * A Property wrapper around the <code>y</code> functionality handled by the 13396 * {@link View#setY(float)} and {@link View#getY()} methods. 13397 */ 13398 public static Property<View, Float> Y = new FloatProperty<View>("y") { 13399 @Override 13400 public void setValue(View object, float value) { 13401 object.setY(value); 13402 } 13403 13404 @Override 13405 public Float get(View object) { 13406 return object.getY(); 13407 } 13408 }; 13409 13410 /** 13411 * A Property wrapper around the <code>rotation</code> functionality handled by the 13412 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 13413 */ 13414 public static Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 13415 @Override 13416 public void setValue(View object, float value) { 13417 object.setRotation(value); 13418 } 13419 13420 @Override 13421 public Float get(View object) { 13422 return object.getRotation(); 13423 } 13424 }; 13425 13426 /** 13427 * A Property wrapper around the <code>rotationX</code> functionality handled by the 13428 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 13429 */ 13430 public static Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 13431 @Override 13432 public void setValue(View object, float value) { 13433 object.setRotationX(value); 13434 } 13435 13436 @Override 13437 public Float get(View object) { 13438 return object.getRotationX(); 13439 } 13440 }; 13441 13442 /** 13443 * A Property wrapper around the <code>rotationY</code> functionality handled by the 13444 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 13445 */ 13446 public static Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 13447 @Override 13448 public void setValue(View object, float value) { 13449 object.setRotationY(value); 13450 } 13451 13452 @Override 13453 public Float get(View object) { 13454 return object.getRotationY(); 13455 } 13456 }; 13457 13458 /** 13459 * A Property wrapper around the <code>scaleX</code> functionality handled by the 13460 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 13461 */ 13462 public static Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 13463 @Override 13464 public void setValue(View object, float value) { 13465 object.setScaleX(value); 13466 } 13467 13468 @Override 13469 public Float get(View object) { 13470 return object.getScaleX(); 13471 } 13472 }; 13473 13474 /** 13475 * A Property wrapper around the <code>scaleY</code> functionality handled by the 13476 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 13477 */ 13478 public static Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 13479 @Override 13480 public void setValue(View object, float value) { 13481 object.setScaleY(value); 13482 } 13483 13484 @Override 13485 public Float get(View object) { 13486 return object.getScaleY(); 13487 } 13488 }; 13489 13490 /** 13491 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 13492 * Each MeasureSpec represents a requirement for either the width or the height. 13493 * A MeasureSpec is comprised of a size and a mode. There are three possible 13494 * modes: 13495 * <dl> 13496 * <dt>UNSPECIFIED</dt> 13497 * <dd> 13498 * The parent has not imposed any constraint on the child. It can be whatever size 13499 * it wants. 13500 * </dd> 13501 * 13502 * <dt>EXACTLY</dt> 13503 * <dd> 13504 * The parent has determined an exact size for the child. The child is going to be 13505 * given those bounds regardless of how big it wants to be. 13506 * </dd> 13507 * 13508 * <dt>AT_MOST</dt> 13509 * <dd> 13510 * The child can be as large as it wants up to the specified size. 13511 * </dd> 13512 * </dl> 13513 * 13514 * MeasureSpecs are implemented as ints to reduce object allocation. This class 13515 * is provided to pack and unpack the <size, mode> tuple into the int. 13516 */ 13517 public static class MeasureSpec { 13518 private static final int MODE_SHIFT = 30; 13519 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 13520 13521 /** 13522 * Measure specification mode: The parent has not imposed any constraint 13523 * on the child. It can be whatever size it wants. 13524 */ 13525 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 13526 13527 /** 13528 * Measure specification mode: The parent has determined an exact size 13529 * for the child. The child is going to be given those bounds regardless 13530 * of how big it wants to be. 13531 */ 13532 public static final int EXACTLY = 1 << MODE_SHIFT; 13533 13534 /** 13535 * Measure specification mode: The child can be as large as it wants up 13536 * to the specified size. 13537 */ 13538 public static final int AT_MOST = 2 << MODE_SHIFT; 13539 13540 /** 13541 * Creates a measure specification based on the supplied size and mode. 13542 * 13543 * The mode must always be one of the following: 13544 * <ul> 13545 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 13546 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 13547 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 13548 * </ul> 13549 * 13550 * @param size the size of the measure specification 13551 * @param mode the mode of the measure specification 13552 * @return the measure specification based on size and mode 13553 */ 13554 public static int makeMeasureSpec(int size, int mode) { 13555 return size + mode; 13556 } 13557 13558 /** 13559 * Extracts the mode from the supplied measure specification. 13560 * 13561 * @param measureSpec the measure specification to extract the mode from 13562 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 13563 * {@link android.view.View.MeasureSpec#AT_MOST} or 13564 * {@link android.view.View.MeasureSpec#EXACTLY} 13565 */ 13566 public static int getMode(int measureSpec) { 13567 return (measureSpec & MODE_MASK); 13568 } 13569 13570 /** 13571 * Extracts the size from the supplied measure specification. 13572 * 13573 * @param measureSpec the measure specification to extract the size from 13574 * @return the size in pixels defined in the supplied measure specification 13575 */ 13576 public static int getSize(int measureSpec) { 13577 return (measureSpec & ~MODE_MASK); 13578 } 13579 13580 /** 13581 * Returns a String representation of the specified measure 13582 * specification. 13583 * 13584 * @param measureSpec the measure specification to convert to a String 13585 * @return a String with the following format: "MeasureSpec: MODE SIZE" 13586 */ 13587 public static String toString(int measureSpec) { 13588 int mode = getMode(measureSpec); 13589 int size = getSize(measureSpec); 13590 13591 StringBuilder sb = new StringBuilder("MeasureSpec: "); 13592 13593 if (mode == UNSPECIFIED) 13594 sb.append("UNSPECIFIED "); 13595 else if (mode == EXACTLY) 13596 sb.append("EXACTLY "); 13597 else if (mode == AT_MOST) 13598 sb.append("AT_MOST "); 13599 else 13600 sb.append(mode).append(" "); 13601 13602 sb.append(size); 13603 return sb.toString(); 13604 } 13605 } 13606 13607 class CheckForLongPress implements Runnable { 13608 13609 private int mOriginalWindowAttachCount; 13610 13611 public void run() { 13612 if (isPressed() && (mParent != null) 13613 && mOriginalWindowAttachCount == mWindowAttachCount) { 13614 if (performLongClick()) { 13615 mHasPerformedLongPress = true; 13616 } 13617 } 13618 } 13619 13620 public void rememberWindowAttachCount() { 13621 mOriginalWindowAttachCount = mWindowAttachCount; 13622 } 13623 } 13624 13625 private final class CheckForTap implements Runnable { 13626 public void run() { 13627 mPrivateFlags &= ~PREPRESSED; 13628 mPrivateFlags |= PRESSED; 13629 refreshDrawableState(); 13630 checkForLongClick(ViewConfiguration.getTapTimeout()); 13631 } 13632 } 13633 13634 private final class PerformClick implements Runnable { 13635 public void run() { 13636 performClick(); 13637 } 13638 } 13639 13640 /** @hide */ 13641 public void hackTurnOffWindowResizeAnim(boolean off) { 13642 mAttachInfo.mTurnOffWindowResizeAnim = off; 13643 } 13644 13645 /** 13646 * This method returns a ViewPropertyAnimator object, which can be used to animate 13647 * specific properties on this View. 13648 * 13649 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 13650 */ 13651 public ViewPropertyAnimator animate() { 13652 if (mAnimator == null) { 13653 mAnimator = new ViewPropertyAnimator(this); 13654 } 13655 return mAnimator; 13656 } 13657 13658 /** 13659 * Interface definition for a callback to be invoked when a key event is 13660 * dispatched to this view. The callback will be invoked before the key 13661 * event is given to the view. 13662 */ 13663 public interface OnKeyListener { 13664 /** 13665 * Called when a key is dispatched to a view. This allows listeners to 13666 * get a chance to respond before the target view. 13667 * 13668 * @param v The view the key has been dispatched to. 13669 * @param keyCode The code for the physical key that was pressed 13670 * @param event The KeyEvent object containing full information about 13671 * the event. 13672 * @return True if the listener has consumed the event, false otherwise. 13673 */ 13674 boolean onKey(View v, int keyCode, KeyEvent event); 13675 } 13676 13677 /** 13678 * Interface definition for a callback to be invoked when a touch event is 13679 * dispatched to this view. The callback will be invoked before the touch 13680 * event is given to the view. 13681 */ 13682 public interface OnTouchListener { 13683 /** 13684 * Called when a touch event is dispatched to a view. This allows listeners to 13685 * get a chance to respond before the target view. 13686 * 13687 * @param v The view the touch event has been dispatched to. 13688 * @param event The MotionEvent object containing full information about 13689 * the event. 13690 * @return True if the listener has consumed the event, false otherwise. 13691 */ 13692 boolean onTouch(View v, MotionEvent event); 13693 } 13694 13695 /** 13696 * Interface definition for a callback to be invoked when a hover event is 13697 * dispatched to this view. The callback will be invoked before the hover 13698 * event is given to the view. 13699 */ 13700 public interface OnHoverListener { 13701 /** 13702 * Called when a hover event is dispatched to a view. This allows listeners to 13703 * get a chance to respond before the target view. 13704 * 13705 * @param v The view the hover event has been dispatched to. 13706 * @param event The MotionEvent object containing full information about 13707 * the event. 13708 * @return True if the listener has consumed the event, false otherwise. 13709 */ 13710 boolean onHover(View v, MotionEvent event); 13711 } 13712 13713 /** 13714 * Interface definition for a callback to be invoked when a generic motion event is 13715 * dispatched to this view. The callback will be invoked before the generic motion 13716 * event is given to the view. 13717 */ 13718 public interface OnGenericMotionListener { 13719 /** 13720 * Called when a generic motion event is dispatched to a view. This allows listeners to 13721 * get a chance to respond before the target view. 13722 * 13723 * @param v The view the generic motion event has been dispatched to. 13724 * @param event The MotionEvent object containing full information about 13725 * the event. 13726 * @return True if the listener has consumed the event, false otherwise. 13727 */ 13728 boolean onGenericMotion(View v, MotionEvent event); 13729 } 13730 13731 /** 13732 * Interface definition for a callback to be invoked when a view has been clicked and held. 13733 */ 13734 public interface OnLongClickListener { 13735 /** 13736 * Called when a view has been clicked and held. 13737 * 13738 * @param v The view that was clicked and held. 13739 * 13740 * @return true if the callback consumed the long click, false otherwise. 13741 */ 13742 boolean onLongClick(View v); 13743 } 13744 13745 /** 13746 * Interface definition for a callback to be invoked when a drag is being dispatched 13747 * to this view. The callback will be invoked before the hosting view's own 13748 * onDrag(event) method. If the listener wants to fall back to the hosting view's 13749 * onDrag(event) behavior, it should return 'false' from this callback. 13750 */ 13751 public interface OnDragListener { 13752 /** 13753 * Called when a drag event is dispatched to a view. This allows listeners 13754 * to get a chance to override base View behavior. 13755 * 13756 * @param v The View that received the drag event. 13757 * @param event The {@link android.view.DragEvent} object for the drag event. 13758 * @return {@code true} if the drag event was handled successfully, or {@code false} 13759 * if the drag event was not handled. Note that {@code false} will trigger the View 13760 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 13761 */ 13762 boolean onDrag(View v, DragEvent event); 13763 } 13764 13765 /** 13766 * Interface definition for a callback to be invoked when the focus state of 13767 * a view changed. 13768 */ 13769 public interface OnFocusChangeListener { 13770 /** 13771 * Called when the focus state of a view has changed. 13772 * 13773 * @param v The view whose state has changed. 13774 * @param hasFocus The new focus state of v. 13775 */ 13776 void onFocusChange(View v, boolean hasFocus); 13777 } 13778 13779 /** 13780 * Interface definition for a callback to be invoked when a view is clicked. 13781 */ 13782 public interface OnClickListener { 13783 /** 13784 * Called when a view has been clicked. 13785 * 13786 * @param v The view that was clicked. 13787 */ 13788 void onClick(View v); 13789 } 13790 13791 /** 13792 * Interface definition for a callback to be invoked when the context menu 13793 * for this view is being built. 13794 */ 13795 public interface OnCreateContextMenuListener { 13796 /** 13797 * Called when the context menu for this view is being built. It is not 13798 * safe to hold onto the menu after this method returns. 13799 * 13800 * @param menu The context menu that is being built 13801 * @param v The view for which the context menu is being built 13802 * @param menuInfo Extra information about the item for which the 13803 * context menu should be shown. This information will vary 13804 * depending on the class of v. 13805 */ 13806 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 13807 } 13808 13809 /** 13810 * Interface definition for a callback to be invoked when the status bar changes 13811 * visibility. 13812 * 13813 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 13814 */ 13815 public interface OnSystemUiVisibilityChangeListener { 13816 /** 13817 * Called when the status bar changes visibility because of a call to 13818 * {@link View#setSystemUiVisibility(int)}. 13819 * 13820 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or 13821 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. 13822 */ 13823 public void onSystemUiVisibilityChange(int visibility); 13824 } 13825 13826 /** 13827 * Interface definition for a callback to be invoked when this view is attached 13828 * or detached from its window. 13829 */ 13830 public interface OnAttachStateChangeListener { 13831 /** 13832 * Called when the view is attached to a window. 13833 * @param v The view that was attached 13834 */ 13835 public void onViewAttachedToWindow(View v); 13836 /** 13837 * Called when the view is detached from a window. 13838 * @param v The view that was detached 13839 */ 13840 public void onViewDetachedFromWindow(View v); 13841 } 13842 13843 private final class UnsetPressedState implements Runnable { 13844 public void run() { 13845 setPressed(false); 13846 } 13847 } 13848 13849 /** 13850 * Base class for derived classes that want to save and restore their own 13851 * state in {@link android.view.View#onSaveInstanceState()}. 13852 */ 13853 public static class BaseSavedState extends AbsSavedState { 13854 /** 13855 * Constructor used when reading from a parcel. Reads the state of the superclass. 13856 * 13857 * @param source 13858 */ 13859 public BaseSavedState(Parcel source) { 13860 super(source); 13861 } 13862 13863 /** 13864 * Constructor called by derived classes when creating their SavedState objects 13865 * 13866 * @param superState The state of the superclass of this view 13867 */ 13868 public BaseSavedState(Parcelable superState) { 13869 super(superState); 13870 } 13871 13872 public static final Parcelable.Creator<BaseSavedState> CREATOR = 13873 new Parcelable.Creator<BaseSavedState>() { 13874 public BaseSavedState createFromParcel(Parcel in) { 13875 return new BaseSavedState(in); 13876 } 13877 13878 public BaseSavedState[] newArray(int size) { 13879 return new BaseSavedState[size]; 13880 } 13881 }; 13882 } 13883 13884 /** 13885 * A set of information given to a view when it is attached to its parent 13886 * window. 13887 */ 13888 static class AttachInfo { 13889 interface Callbacks { 13890 void playSoundEffect(int effectId); 13891 boolean performHapticFeedback(int effectId, boolean always); 13892 } 13893 13894 /** 13895 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 13896 * to a Handler. This class contains the target (View) to invalidate and 13897 * the coordinates of the dirty rectangle. 13898 * 13899 * For performance purposes, this class also implements a pool of up to 13900 * POOL_LIMIT objects that get reused. This reduces memory allocations 13901 * whenever possible. 13902 */ 13903 static class InvalidateInfo implements Poolable<InvalidateInfo> { 13904 private static final int POOL_LIMIT = 10; 13905 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool( 13906 Pools.finitePool(new PoolableManager<InvalidateInfo>() { 13907 public InvalidateInfo newInstance() { 13908 return new InvalidateInfo(); 13909 } 13910 13911 public void onAcquired(InvalidateInfo element) { 13912 } 13913 13914 public void onReleased(InvalidateInfo element) { 13915 element.target = null; 13916 } 13917 }, POOL_LIMIT) 13918 ); 13919 13920 private InvalidateInfo mNext; 13921 private boolean mIsPooled; 13922 13923 View target; 13924 13925 int left; 13926 int top; 13927 int right; 13928 int bottom; 13929 13930 public void setNextPoolable(InvalidateInfo element) { 13931 mNext = element; 13932 } 13933 13934 public InvalidateInfo getNextPoolable() { 13935 return mNext; 13936 } 13937 13938 static InvalidateInfo acquire() { 13939 return sPool.acquire(); 13940 } 13941 13942 void release() { 13943 sPool.release(this); 13944 } 13945 13946 public boolean isPooled() { 13947 return mIsPooled; 13948 } 13949 13950 public void setPooled(boolean isPooled) { 13951 mIsPooled = isPooled; 13952 } 13953 } 13954 13955 final IWindowSession mSession; 13956 13957 final IWindow mWindow; 13958 13959 final IBinder mWindowToken; 13960 13961 final Callbacks mRootCallbacks; 13962 13963 HardwareCanvas mHardwareCanvas; 13964 13965 /** 13966 * The top view of the hierarchy. 13967 */ 13968 View mRootView; 13969 13970 IBinder mPanelParentWindowToken; 13971 Surface mSurface; 13972 13973 boolean mHardwareAccelerated; 13974 boolean mHardwareAccelerationRequested; 13975 HardwareRenderer mHardwareRenderer; 13976 13977 /** 13978 * Scale factor used by the compatibility mode 13979 */ 13980 float mApplicationScale; 13981 13982 /** 13983 * Indicates whether the application is in compatibility mode 13984 */ 13985 boolean mScalingRequired; 13986 13987 /** 13988 * If set, ViewAncestor doesn't use its lame animation for when the window resizes. 13989 */ 13990 boolean mTurnOffWindowResizeAnim; 13991 13992 /** 13993 * Left position of this view's window 13994 */ 13995 int mWindowLeft; 13996 13997 /** 13998 * Top position of this view's window 13999 */ 14000 int mWindowTop; 14001 14002 /** 14003 * Indicates whether views need to use 32-bit drawing caches 14004 */ 14005 boolean mUse32BitDrawingCache; 14006 14007 /** 14008 * For windows that are full-screen but using insets to layout inside 14009 * of the screen decorations, these are the current insets for the 14010 * content of the window. 14011 */ 14012 final Rect mContentInsets = new Rect(); 14013 14014 /** 14015 * For windows that are full-screen but using insets to layout inside 14016 * of the screen decorations, these are the current insets for the 14017 * actual visible parts of the window. 14018 */ 14019 final Rect mVisibleInsets = new Rect(); 14020 14021 /** 14022 * The internal insets given by this window. This value is 14023 * supplied by the client (through 14024 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 14025 * be given to the window manager when changed to be used in laying 14026 * out windows behind it. 14027 */ 14028 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 14029 = new ViewTreeObserver.InternalInsetsInfo(); 14030 14031 /** 14032 * All views in the window's hierarchy that serve as scroll containers, 14033 * used to determine if the window can be resized or must be panned 14034 * to adjust for a soft input area. 14035 */ 14036 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 14037 14038 final KeyEvent.DispatcherState mKeyDispatchState 14039 = new KeyEvent.DispatcherState(); 14040 14041 /** 14042 * Indicates whether the view's window currently has the focus. 14043 */ 14044 boolean mHasWindowFocus; 14045 14046 /** 14047 * The current visibility of the window. 14048 */ 14049 int mWindowVisibility; 14050 14051 /** 14052 * Indicates the time at which drawing started to occur. 14053 */ 14054 long mDrawingTime; 14055 14056 /** 14057 * Indicates whether or not ignoring the DIRTY_MASK flags. 14058 */ 14059 boolean mIgnoreDirtyState; 14060 14061 /** 14062 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 14063 * to avoid clearing that flag prematurely. 14064 */ 14065 boolean mSetIgnoreDirtyState = false; 14066 14067 /** 14068 * Indicates whether the view's window is currently in touch mode. 14069 */ 14070 boolean mInTouchMode; 14071 14072 /** 14073 * Indicates that ViewAncestor should trigger a global layout change 14074 * the next time it performs a traversal 14075 */ 14076 boolean mRecomputeGlobalAttributes; 14077 14078 /** 14079 * Set during a traveral if any views want to keep the screen on. 14080 */ 14081 boolean mKeepScreenOn; 14082 14083 /** 14084 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 14085 */ 14086 int mSystemUiVisibility; 14087 14088 /** 14089 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 14090 * attached. 14091 */ 14092 boolean mHasSystemUiListeners; 14093 14094 /** 14095 * Set if the visibility of any views has changed. 14096 */ 14097 boolean mViewVisibilityChanged; 14098 14099 /** 14100 * Set to true if a view has been scrolled. 14101 */ 14102 boolean mViewScrollChanged; 14103 14104 /** 14105 * Global to the view hierarchy used as a temporary for dealing with 14106 * x/y points in the transparent region computations. 14107 */ 14108 final int[] mTransparentLocation = new int[2]; 14109 14110 /** 14111 * Global to the view hierarchy used as a temporary for dealing with 14112 * x/y points in the ViewGroup.invalidateChild implementation. 14113 */ 14114 final int[] mInvalidateChildLocation = new int[2]; 14115 14116 14117 /** 14118 * Global to the view hierarchy used as a temporary for dealing with 14119 * x/y location when view is transformed. 14120 */ 14121 final float[] mTmpTransformLocation = new float[2]; 14122 14123 /** 14124 * The view tree observer used to dispatch global events like 14125 * layout, pre-draw, touch mode change, etc. 14126 */ 14127 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 14128 14129 /** 14130 * A Canvas used by the view hierarchy to perform bitmap caching. 14131 */ 14132 Canvas mCanvas; 14133 14134 /** 14135 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 14136 * handler can be used to pump events in the UI events queue. 14137 */ 14138 final Handler mHandler; 14139 14140 /** 14141 * Identifier for messages requesting the view to be invalidated. 14142 * Such messages should be sent to {@link #mHandler}. 14143 */ 14144 static final int INVALIDATE_MSG = 0x1; 14145 14146 /** 14147 * Identifier for messages requesting the view to invalidate a region. 14148 * Such messages should be sent to {@link #mHandler}. 14149 */ 14150 static final int INVALIDATE_RECT_MSG = 0x2; 14151 14152 /** 14153 * Temporary for use in computing invalidate rectangles while 14154 * calling up the hierarchy. 14155 */ 14156 final Rect mTmpInvalRect = new Rect(); 14157 14158 /** 14159 * Temporary for use in computing hit areas with transformed views 14160 */ 14161 final RectF mTmpTransformRect = new RectF(); 14162 14163 /** 14164 * Temporary list for use in collecting focusable descendents of a view. 14165 */ 14166 final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24); 14167 14168 /** 14169 * The id of the window for accessibility purposes. 14170 */ 14171 int mAccessibilityWindowId = View.NO_ID; 14172 14173 /** 14174 * Creates a new set of attachment information with the specified 14175 * events handler and thread. 14176 * 14177 * @param handler the events handler the view must use 14178 */ 14179 AttachInfo(IWindowSession session, IWindow window, 14180 Handler handler, Callbacks effectPlayer) { 14181 mSession = session; 14182 mWindow = window; 14183 mWindowToken = window.asBinder(); 14184 mHandler = handler; 14185 mRootCallbacks = effectPlayer; 14186 } 14187 } 14188 14189 /** 14190 * <p>ScrollabilityCache holds various fields used by a View when scrolling 14191 * is supported. This avoids keeping too many unused fields in most 14192 * instances of View.</p> 14193 */ 14194 private static class ScrollabilityCache implements Runnable { 14195 14196 /** 14197 * Scrollbars are not visible 14198 */ 14199 public static final int OFF = 0; 14200 14201 /** 14202 * Scrollbars are visible 14203 */ 14204 public static final int ON = 1; 14205 14206 /** 14207 * Scrollbars are fading away 14208 */ 14209 public static final int FADING = 2; 14210 14211 public boolean fadeScrollBars; 14212 14213 public int fadingEdgeLength; 14214 public int scrollBarDefaultDelayBeforeFade; 14215 public int scrollBarFadeDuration; 14216 14217 public int scrollBarSize; 14218 public ScrollBarDrawable scrollBar; 14219 public float[] interpolatorValues; 14220 public View host; 14221 14222 public final Paint paint; 14223 public final Matrix matrix; 14224 public Shader shader; 14225 14226 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 14227 14228 private static final float[] OPAQUE = { 255 }; 14229 private static final float[] TRANSPARENT = { 0.0f }; 14230 14231 /** 14232 * When fading should start. This time moves into the future every time 14233 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 14234 */ 14235 public long fadeStartTime; 14236 14237 14238 /** 14239 * The current state of the scrollbars: ON, OFF, or FADING 14240 */ 14241 public int state = OFF; 14242 14243 private int mLastColor; 14244 14245 public ScrollabilityCache(ViewConfiguration configuration, View host) { 14246 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 14247 scrollBarSize = configuration.getScaledScrollBarSize(); 14248 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 14249 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 14250 14251 paint = new Paint(); 14252 matrix = new Matrix(); 14253 // use use a height of 1, and then wack the matrix each time we 14254 // actually use it. 14255 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 14256 14257 paint.setShader(shader); 14258 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 14259 this.host = host; 14260 } 14261 14262 public void setFadeColor(int color) { 14263 if (color != 0 && color != mLastColor) { 14264 mLastColor = color; 14265 color |= 0xFF000000; 14266 14267 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 14268 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 14269 14270 paint.setShader(shader); 14271 // Restore the default transfer mode (src_over) 14272 paint.setXfermode(null); 14273 } 14274 } 14275 14276 public void run() { 14277 long now = AnimationUtils.currentAnimationTimeMillis(); 14278 if (now >= fadeStartTime) { 14279 14280 // the animation fades the scrollbars out by changing 14281 // the opacity (alpha) from fully opaque to fully 14282 // transparent 14283 int nextFrame = (int) now; 14284 int framesCount = 0; 14285 14286 Interpolator interpolator = scrollBarInterpolator; 14287 14288 // Start opaque 14289 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 14290 14291 // End transparent 14292 nextFrame += scrollBarFadeDuration; 14293 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 14294 14295 state = FADING; 14296 14297 // Kick off the fade animation 14298 host.invalidate(true); 14299 } 14300 } 14301 } 14302 14303 /** 14304 * Resuable callback for sending 14305 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 14306 */ 14307 private class SendViewScrolledAccessibilityEvent implements Runnable { 14308 public volatile boolean mIsPending; 14309 14310 public void run() { 14311 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 14312 mIsPending = false; 14313 } 14314 } 14315} 14316