View.java revision 71fcc865e3ac3a3b05ffa204e6a2eaa8bad48a8c
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 com.android.internal.R; 20import com.android.internal.util.Predicate; 21import com.android.internal.view.menu.MenuBuilder; 22 23import android.content.ClipData; 24import android.content.Context; 25import android.content.res.Configuration; 26import android.content.res.Resources; 27import android.content.res.TypedArray; 28import android.graphics.Bitmap; 29import android.graphics.Camera; 30import android.graphics.Canvas; 31import android.graphics.Interpolator; 32import android.graphics.LinearGradient; 33import android.graphics.Matrix; 34import android.graphics.Paint; 35import android.graphics.PixelFormat; 36import android.graphics.Point; 37import android.graphics.PorterDuff; 38import android.graphics.PorterDuffXfermode; 39import android.graphics.Rect; 40import android.graphics.RectF; 41import android.graphics.Region; 42import android.graphics.Shader; 43import android.graphics.drawable.ColorDrawable; 44import android.graphics.drawable.Drawable; 45import android.os.Handler; 46import android.os.IBinder; 47import android.os.Message; 48import android.os.Parcel; 49import android.os.Parcelable; 50import android.os.RemoteException; 51import android.os.SystemClock; 52import android.util.AttributeSet; 53import android.util.Log; 54import android.util.Pool; 55import android.util.Poolable; 56import android.util.PoolableManager; 57import android.util.Pools; 58import android.util.SparseArray; 59import android.util.TypedValue; 60import android.view.ContextMenu.ContextMenuInfo; 61import android.view.accessibility.AccessibilityEvent; 62import android.view.accessibility.AccessibilityEventSource; 63import android.view.accessibility.AccessibilityManager; 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 java.lang.ref.WeakReference; 72import java.lang.reflect.InvocationTargetException; 73import java.lang.reflect.Method; 74import java.util.ArrayList; 75import java.util.Arrays; 76import java.util.WeakHashMap; 77import java.util.concurrent.CopyOnWriteArrayList; 78 79/** 80 * <p> 81 * This class represents the basic building block for user interface components. A View 82 * occupies a rectangular area on the screen and is responsible for drawing and 83 * event handling. View is the base class for <em>widgets</em>, which are 84 * used to create interactive UI components (buttons, text fields, etc.). The 85 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 86 * are invisible containers that hold other Views (or other ViewGroups) and define 87 * their layout properties. 88 * </p> 89 * 90 * <div class="special"> 91 * <p>For an introduction to using this class to develop your 92 * application's user interface, read the Developer Guide documentation on 93 * <strong><a href="{@docRoot}guide/topics/ui/index.html">User Interface</a></strong>. Special topics 94 * include: 95 * <br/><a href="{@docRoot}guide/topics/ui/declaring-layout.html">Declaring Layout</a> 96 * <br/><a href="{@docRoot}guide/topics/ui/menus.html">Creating Menus</a> 97 * <br/><a href="{@docRoot}guide/topics/ui/layout-objects.html">Common Layout Objects</a> 98 * <br/><a href="{@docRoot}guide/topics/ui/binding.html">Binding to Data with AdapterView</a> 99 * <br/><a href="{@docRoot}guide/topics/ui/ui-events.html">Handling UI Events</a> 100 * <br/><a href="{@docRoot}guide/topics/ui/themes.html">Applying Styles and Themes</a> 101 * <br/><a href="{@docRoot}guide/topics/ui/custom-components.html">Building Custom Components</a> 102 * <br/><a href="{@docRoot}guide/topics/ui/how-android-draws.html">How Android Draws Views</a>. 103 * </p> 104 * </div> 105 * 106 * <a name="Using"></a> 107 * <h3>Using Views</h3> 108 * <p> 109 * All of the views in a window are arranged in a single tree. You can add views 110 * either from code or by specifying a tree of views in one or more XML layout 111 * files. There are many specialized subclasses of views that act as controls or 112 * are capable of displaying text, images, or other content. 113 * </p> 114 * <p> 115 * Once you have created a tree of views, there are typically a few types of 116 * common operations you may wish to perform: 117 * <ul> 118 * <li><strong>Set properties:</strong> for example setting the text of a 119 * {@link android.widget.TextView}. The available properties and the methods 120 * that set them will vary among the different subclasses of views. Note that 121 * properties that are known at build time can be set in the XML layout 122 * files.</li> 123 * <li><strong>Set focus:</strong> The framework will handled moving focus in 124 * response to user input. To force focus to a specific view, call 125 * {@link #requestFocus}.</li> 126 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 127 * that will be notified when something interesting happens to the view. For 128 * example, all views will let you set a listener to be notified when the view 129 * gains or loses focus. You can register such a listener using 130 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 131 * Other view subclasses offer more specialized listeners. For example, a Button 132 * exposes a listener to notify clients when the button is clicked.</li> 133 * <li><strong>Set visibility:</strong> You can hide or show views using 134 * {@link #setVisibility(int)}.</li> 135 * </ul> 136 * </p> 137 * <p><em> 138 * Note: The Android framework is responsible for measuring, laying out and 139 * drawing views. You should not call methods that perform these actions on 140 * views yourself unless you are actually implementing a 141 * {@link android.view.ViewGroup}. 142 * </em></p> 143 * 144 * <a name="Lifecycle"></a> 145 * <h3>Implementing a Custom View</h3> 146 * 147 * <p> 148 * To implement a custom view, you will usually begin by providing overrides for 149 * some of the standard methods that the framework calls on all views. You do 150 * not need to override all of these methods. In fact, you can start by just 151 * overriding {@link #onDraw(android.graphics.Canvas)}. 152 * <table border="2" width="85%" align="center" cellpadding="5"> 153 * <thead> 154 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 155 * </thead> 156 * 157 * <tbody> 158 * <tr> 159 * <td rowspan="2">Creation</td> 160 * <td>Constructors</td> 161 * <td>There is a form of the constructor that are called when the view 162 * is created from code and a form that is called when the view is 163 * inflated from a layout file. The second form should parse and apply 164 * any attributes defined in the layout file. 165 * </td> 166 * </tr> 167 * <tr> 168 * <td><code>{@link #onFinishInflate()}</code></td> 169 * <td>Called after a view and all of its children has been inflated 170 * from XML.</td> 171 * </tr> 172 * 173 * <tr> 174 * <td rowspan="3">Layout</td> 175 * <td><code>{@link #onMeasure(int, int)}</code></td> 176 * <td>Called to determine the size requirements for this view and all 177 * of its children. 178 * </td> 179 * </tr> 180 * <tr> 181 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 182 * <td>Called when this view should assign a size and position to all 183 * of its children. 184 * </td> 185 * </tr> 186 * <tr> 187 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 188 * <td>Called when the size of this view has changed. 189 * </td> 190 * </tr> 191 * 192 * <tr> 193 * <td>Drawing</td> 194 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 195 * <td>Called when the view should render its content. 196 * </td> 197 * </tr> 198 * 199 * <tr> 200 * <td rowspan="4">Event processing</td> 201 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 202 * <td>Called when a new key event occurs. 203 * </td> 204 * </tr> 205 * <tr> 206 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 207 * <td>Called when a key up event occurs. 208 * </td> 209 * </tr> 210 * <tr> 211 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 212 * <td>Called when a trackball motion event occurs. 213 * </td> 214 * </tr> 215 * <tr> 216 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 217 * <td>Called when a touch screen motion event occurs. 218 * </td> 219 * </tr> 220 * 221 * <tr> 222 * <td rowspan="2">Focus</td> 223 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 224 * <td>Called when the view gains or loses focus. 225 * </td> 226 * </tr> 227 * 228 * <tr> 229 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 230 * <td>Called when the window containing the view gains or loses focus. 231 * </td> 232 * </tr> 233 * 234 * <tr> 235 * <td rowspan="3">Attaching</td> 236 * <td><code>{@link #onAttachedToWindow()}</code></td> 237 * <td>Called when the view is attached to a window. 238 * </td> 239 * </tr> 240 * 241 * <tr> 242 * <td><code>{@link #onDetachedFromWindow}</code></td> 243 * <td>Called when the view is detached from its window. 244 * </td> 245 * </tr> 246 * 247 * <tr> 248 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 249 * <td>Called when the visibility of the window containing the view 250 * has changed. 251 * </td> 252 * </tr> 253 * </tbody> 254 * 255 * </table> 256 * </p> 257 * 258 * <a name="IDs"></a> 259 * <h3>IDs</h3> 260 * Views may have an integer id associated with them. These ids are typically 261 * assigned in the layout XML files, and are used to find specific views within 262 * the view tree. A common pattern is to: 263 * <ul> 264 * <li>Define a Button in the layout file and assign it a unique ID. 265 * <pre> 266 * <Button 267 * android:id="@+id/my_button" 268 * android:layout_width="wrap_content" 269 * android:layout_height="wrap_content" 270 * android:text="@string/my_button_text"/> 271 * </pre></li> 272 * <li>From the onCreate method of an Activity, find the Button 273 * <pre class="prettyprint"> 274 * Button myButton = (Button) findViewById(R.id.my_button); 275 * </pre></li> 276 * </ul> 277 * <p> 278 * View IDs need not be unique throughout the tree, but it is good practice to 279 * ensure that they are at least unique within the part of the tree you are 280 * searching. 281 * </p> 282 * 283 * <a name="Position"></a> 284 * <h3>Position</h3> 285 * <p> 286 * The geometry of a view is that of a rectangle. A view has a location, 287 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 288 * two dimensions, expressed as a width and a height. The unit for location 289 * and dimensions is the pixel. 290 * </p> 291 * 292 * <p> 293 * It is possible to retrieve the location of a view by invoking the methods 294 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 295 * coordinate of the rectangle representing the view. The latter returns the 296 * top, or Y, coordinate of the rectangle representing the view. These methods 297 * both return the location of the view relative to its parent. For instance, 298 * when getLeft() returns 20, that means the view is located 20 pixels to the 299 * right of the left edge of its direct parent. 300 * </p> 301 * 302 * <p> 303 * In addition, several convenience methods are offered to avoid unnecessary 304 * computations, namely {@link #getRight()} and {@link #getBottom()}. 305 * These methods return the coordinates of the right and bottom edges of the 306 * rectangle representing the view. For instance, calling {@link #getRight()} 307 * is similar to the following computation: <code>getLeft() + getWidth()</code> 308 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 309 * </p> 310 * 311 * <a name="SizePaddingMargins"></a> 312 * <h3>Size, padding and margins</h3> 313 * <p> 314 * The size of a view is expressed with a width and a height. A view actually 315 * possess two pairs of width and height values. 316 * </p> 317 * 318 * <p> 319 * The first pair is known as <em>measured width</em> and 320 * <em>measured height</em>. These dimensions define how big a view wants to be 321 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 322 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 323 * and {@link #getMeasuredHeight()}. 324 * </p> 325 * 326 * <p> 327 * The second pair is simply known as <em>width</em> and <em>height</em>, or 328 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 329 * dimensions define the actual size of the view on screen, at drawing time and 330 * after layout. These values may, but do not have to, be different from the 331 * measured width and height. The width and height can be obtained by calling 332 * {@link #getWidth()} and {@link #getHeight()}. 333 * </p> 334 * 335 * <p> 336 * To measure its dimensions, a view takes into account its padding. The padding 337 * is expressed in pixels for the left, top, right and bottom parts of the view. 338 * Padding can be used to offset the content of the view by a specific amount of 339 * pixels. For instance, a left padding of 2 will push the view's content by 340 * 2 pixels to the right of the left edge. Padding can be set using the 341 * {@link #setPadding(int, int, int, int)} method and queried by calling 342 * {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 343 * {@link #getPaddingRight()} and {@link #getPaddingBottom()}. 344 * </p> 345 * 346 * <p> 347 * Even though a view can define a padding, it does not provide any support for 348 * margins. However, view groups provide such a support. Refer to 349 * {@link android.view.ViewGroup} and 350 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 351 * </p> 352 * 353 * <a name="Layout"></a> 354 * <h3>Layout</h3> 355 * <p> 356 * Layout is a two pass process: a measure pass and a layout pass. The measuring 357 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 358 * of the view tree. Each view pushes dimension specifications down the tree 359 * during the recursion. At the end of the measure pass, every view has stored 360 * its measurements. The second pass happens in 361 * {@link #layout(int,int,int,int)} and is also top-down. During 362 * this pass each parent is responsible for positioning all of its children 363 * using the sizes computed in the measure pass. 364 * </p> 365 * 366 * <p> 367 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 368 * {@link #getMeasuredHeight()} values must be set, along with those for all of 369 * that view's descendants. A view's measured width and measured height values 370 * must respect the constraints imposed by the view's parents. This guarantees 371 * that at the end of the measure pass, all parents accept all of their 372 * children's measurements. A parent view may call measure() more than once on 373 * its children. For example, the parent may measure each child once with 374 * unspecified dimensions to find out how big they want to be, then call 375 * measure() on them again with actual numbers if the sum of all the children's 376 * unconstrained sizes is too big or too small. 377 * </p> 378 * 379 * <p> 380 * The measure pass uses two classes to communicate dimensions. The 381 * {@link MeasureSpec} class is used by views to tell their parents how they 382 * want to be measured and positioned. The base LayoutParams class just 383 * describes how big the view wants to be for both width and height. For each 384 * dimension, it can specify one of: 385 * <ul> 386 * <li> an exact number 387 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 388 * (minus padding) 389 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 390 * enclose its content (plus padding). 391 * </ul> 392 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 393 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 394 * an X and Y value. 395 * </p> 396 * 397 * <p> 398 * MeasureSpecs are used to push requirements down the tree from parent to 399 * child. A MeasureSpec can be in one of three modes: 400 * <ul> 401 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 402 * of a child view. For example, a LinearLayout may call measure() on its child 403 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 404 * tall the child view wants to be given a width of 240 pixels. 405 * <li>EXACTLY: This is used by the parent to impose an exact size on the 406 * child. The child must use this size, and guarantee that all of its 407 * descendants will fit within this size. 408 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 409 * child. The child must gurantee that it and all of its descendants will fit 410 * within this size. 411 * </ul> 412 * </p> 413 * 414 * <p> 415 * To intiate a layout, call {@link #requestLayout}. This method is typically 416 * called by a view on itself when it believes that is can no longer fit within 417 * its current bounds. 418 * </p> 419 * 420 * <a name="Drawing"></a> 421 * <h3>Drawing</h3> 422 * <p> 423 * Drawing is handled by walking the tree and rendering each view that 424 * intersects the the invalid region. Because the tree is traversed in-order, 425 * this means that parents will draw before (i.e., behind) their children, with 426 * siblings drawn in the order they appear in the tree. 427 * If you set a background drawable for a View, then the View will draw it for you 428 * before calling back to its <code>onDraw()</code> method. 429 * </p> 430 * 431 * <p> 432 * Note that the framework will not draw views that are not in the invalid region. 433 * </p> 434 * 435 * <p> 436 * To force a view to draw, call {@link #invalidate()}. 437 * </p> 438 * 439 * <a name="EventHandlingThreading"></a> 440 * <h3>Event Handling and Threading</h3> 441 * <p> 442 * The basic cycle of a view is as follows: 443 * <ol> 444 * <li>An event comes in and is dispatched to the appropriate view. The view 445 * handles the event and notifies any listeners.</li> 446 * <li>If in the course of processing the event, the view's bounds may need 447 * to be changed, the view will call {@link #requestLayout()}.</li> 448 * <li>Similarly, if in the course of processing the event the view's appearance 449 * may need to be changed, the view will call {@link #invalidate()}.</li> 450 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 451 * the framework will take care of measuring, laying out, and drawing the tree 452 * as appropriate.</li> 453 * </ol> 454 * </p> 455 * 456 * <p><em>Note: The entire view tree is single threaded. You must always be on 457 * the UI thread when calling any method on any view.</em> 458 * If you are doing work on other threads and want to update the state of a view 459 * from that thread, you should use a {@link Handler}. 460 * </p> 461 * 462 * <a name="FocusHandling"></a> 463 * <h3>Focus Handling</h3> 464 * <p> 465 * The framework will handle routine focus movement in response to user input. 466 * This includes changing the focus as views are removed or hidden, or as new 467 * views become available. Views indicate their willingness to take focus 468 * through the {@link #isFocusable} method. To change whether a view can take 469 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 470 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 471 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 472 * </p> 473 * <p> 474 * Focus movement is based on an algorithm which finds the nearest neighbor in a 475 * given direction. In rare cases, the default algorithm may not match the 476 * intended behavior of the developer. In these situations, you can provide 477 * explicit overrides by using these XML attributes in the layout file: 478 * <pre> 479 * nextFocusDown 480 * nextFocusLeft 481 * nextFocusRight 482 * nextFocusUp 483 * </pre> 484 * </p> 485 * 486 * 487 * <p> 488 * To get a particular view to take focus, call {@link #requestFocus()}. 489 * </p> 490 * 491 * <a name="TouchMode"></a> 492 * <h3>Touch Mode</h3> 493 * <p> 494 * When a user is navigating a user interface via directional keys such as a D-pad, it is 495 * necessary to give focus to actionable items such as buttons so the user can see 496 * what will take input. If the device has touch capabilities, however, and the user 497 * begins interacting with the interface by touching it, it is no longer necessary to 498 * always highlight, or give focus to, a particular view. This motivates a mode 499 * for interaction named 'touch mode'. 500 * </p> 501 * <p> 502 * For a touch capable device, once the user touches the screen, the device 503 * will enter touch mode. From this point onward, only views for which 504 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 505 * Other views that are touchable, like buttons, will not take focus when touched; they will 506 * only fire the on click listeners. 507 * </p> 508 * <p> 509 * Any time a user hits a directional key, such as a D-pad direction, the view device will 510 * exit touch mode, and find a view to take focus, so that the user may resume interacting 511 * with the user interface without touching the screen again. 512 * </p> 513 * <p> 514 * The touch mode state is maintained across {@link android.app.Activity}s. Call 515 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 516 * </p> 517 * 518 * <a name="Scrolling"></a> 519 * <h3>Scrolling</h3> 520 * <p> 521 * The framework provides basic support for views that wish to internally 522 * scroll their content. This includes keeping track of the X and Y scroll 523 * offset as well as mechanisms for drawing scrollbars. See 524 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 525 * {@link #awakenScrollBars()} for more details. 526 * </p> 527 * 528 * <a name="Tags"></a> 529 * <h3>Tags</h3> 530 * <p> 531 * Unlike IDs, tags are not used to identify views. Tags are essentially an 532 * extra piece of information that can be associated with a view. They are most 533 * often used as a convenience to store data related to views in the views 534 * themselves rather than by putting them in a separate structure. 535 * </p> 536 * 537 * <a name="Animation"></a> 538 * <h3>Animation</h3> 539 * <p> 540 * You can attach an {@link Animation} object to a view using 541 * {@link #setAnimation(Animation)} or 542 * {@link #startAnimation(Animation)}. The animation can alter the scale, 543 * rotation, translation and alpha of a view over time. If the animation is 544 * attached to a view that has children, the animation will affect the entire 545 * subtree rooted by that node. When an animation is started, the framework will 546 * take care of redrawing the appropriate views until the animation completes. 547 * </p> 548 * <p> 549 * Starting with Android 3.0, the preferred way of animating views is to use the 550 * {@link android.animation} package APIs. 551 * </p> 552 * 553 * <a name="Security"></a> 554 * <h3>Security</h3> 555 * <p> 556 * Sometimes it is essential that an application be able to verify that an action 557 * is being performed with the full knowledge and consent of the user, such as 558 * granting a permission request, making a purchase or clicking on an advertisement. 559 * Unfortunately, a malicious application could try to spoof the user into 560 * performing these actions, unaware, by concealing the intended purpose of the view. 561 * As a remedy, the framework offers a touch filtering mechanism that can be used to 562 * improve the security of views that provide access to sensitive functionality. 563 * </p><p> 564 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 565 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 566 * will discard touches that are received whenever the view's window is obscured by 567 * another visible window. As a result, the view will not receive touches whenever a 568 * toast, dialog or other window appears above the view's window. 569 * </p><p> 570 * For more fine-grained control over security, consider overriding the 571 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 572 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 573 * </p> 574 * 575 * @attr ref android.R.styleable#View_alpha 576 * @attr ref android.R.styleable#View_background 577 * @attr ref android.R.styleable#View_clickable 578 * @attr ref android.R.styleable#View_contentDescription 579 * @attr ref android.R.styleable#View_drawingCacheQuality 580 * @attr ref android.R.styleable#View_duplicateParentState 581 * @attr ref android.R.styleable#View_id 582 * @attr ref android.R.styleable#View_fadingEdge 583 * @attr ref android.R.styleable#View_fadingEdgeLength 584 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 585 * @attr ref android.R.styleable#View_fitsSystemWindows 586 * @attr ref android.R.styleable#View_isScrollContainer 587 * @attr ref android.R.styleable#View_focusable 588 * @attr ref android.R.styleable#View_focusableInTouchMode 589 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 590 * @attr ref android.R.styleable#View_keepScreenOn 591 * @attr ref android.R.styleable#View_layerType 592 * @attr ref android.R.styleable#View_longClickable 593 * @attr ref android.R.styleable#View_minHeight 594 * @attr ref android.R.styleable#View_minWidth 595 * @attr ref android.R.styleable#View_nextFocusDown 596 * @attr ref android.R.styleable#View_nextFocusLeft 597 * @attr ref android.R.styleable#View_nextFocusRight 598 * @attr ref android.R.styleable#View_nextFocusUp 599 * @attr ref android.R.styleable#View_onClick 600 * @attr ref android.R.styleable#View_padding 601 * @attr ref android.R.styleable#View_paddingBottom 602 * @attr ref android.R.styleable#View_paddingLeft 603 * @attr ref android.R.styleable#View_paddingRight 604 * @attr ref android.R.styleable#View_paddingTop 605 * @attr ref android.R.styleable#View_saveEnabled 606 * @attr ref android.R.styleable#View_rotation 607 * @attr ref android.R.styleable#View_rotationX 608 * @attr ref android.R.styleable#View_rotationY 609 * @attr ref android.R.styleable#View_scaleX 610 * @attr ref android.R.styleable#View_scaleY 611 * @attr ref android.R.styleable#View_scrollX 612 * @attr ref android.R.styleable#View_scrollY 613 * @attr ref android.R.styleable#View_scrollbarSize 614 * @attr ref android.R.styleable#View_scrollbarStyle 615 * @attr ref android.R.styleable#View_scrollbars 616 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 617 * @attr ref android.R.styleable#View_scrollbarFadeDuration 618 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 619 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 620 * @attr ref android.R.styleable#View_scrollbarThumbVertical 621 * @attr ref android.R.styleable#View_scrollbarTrackVertical 622 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 623 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 624 * @attr ref android.R.styleable#View_soundEffectsEnabled 625 * @attr ref android.R.styleable#View_tag 626 * @attr ref android.R.styleable#View_transformPivotX 627 * @attr ref android.R.styleable#View_transformPivotY 628 * @attr ref android.R.styleable#View_translationX 629 * @attr ref android.R.styleable#View_translationY 630 * @attr ref android.R.styleable#View_visibility 631 * 632 * @see android.view.ViewGroup 633 */ 634public class View implements Drawable.Callback, KeyEvent.Callback, AccessibilityEventSource { 635 private static final boolean DBG = false; 636 637 /** 638 * The logging tag used by this class with android.util.Log. 639 */ 640 protected static final String VIEW_LOG_TAG = "View"; 641 642 /** 643 * Used to mark a View that has no ID. 644 */ 645 public static final int NO_ID = -1; 646 647 /** 648 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 649 * calling setFlags. 650 */ 651 private static final int NOT_FOCUSABLE = 0x00000000; 652 653 /** 654 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 655 * setFlags. 656 */ 657 private static final int FOCUSABLE = 0x00000001; 658 659 /** 660 * Mask for use with setFlags indicating bits used for focus. 661 */ 662 private static final int FOCUSABLE_MASK = 0x00000001; 663 664 /** 665 * This view will adjust its padding to fit sytem windows (e.g. status bar) 666 */ 667 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 668 669 /** 670 * This view is visible. Use with {@link #setVisibility(int)}. 671 */ 672 public static final int VISIBLE = 0x00000000; 673 674 /** 675 * This view is invisible, but it still takes up space for layout purposes. 676 * Use with {@link #setVisibility(int)}. 677 */ 678 public static final int INVISIBLE = 0x00000004; 679 680 /** 681 * This view is invisible, and it doesn't take any space for layout 682 * purposes. Use with {@link #setVisibility(int)}. 683 */ 684 public static final int GONE = 0x00000008; 685 686 /** 687 * Mask for use with setFlags indicating bits used for visibility. 688 * {@hide} 689 */ 690 static final int VISIBILITY_MASK = 0x0000000C; 691 692 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 693 694 /** 695 * This view is enabled. Intrepretation varies by subclass. 696 * Use with ENABLED_MASK when calling setFlags. 697 * {@hide} 698 */ 699 static final int ENABLED = 0x00000000; 700 701 /** 702 * This view is disabled. Intrepretation varies by subclass. 703 * Use with ENABLED_MASK when calling setFlags. 704 * {@hide} 705 */ 706 static final int DISABLED = 0x00000020; 707 708 /** 709 * Mask for use with setFlags indicating bits used for indicating whether 710 * this view is enabled 711 * {@hide} 712 */ 713 static final int ENABLED_MASK = 0x00000020; 714 715 /** 716 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 717 * called and further optimizations will be performed. It is okay to have 718 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 719 * {@hide} 720 */ 721 static final int WILL_NOT_DRAW = 0x00000080; 722 723 /** 724 * Mask for use with setFlags indicating bits used for indicating whether 725 * this view is will draw 726 * {@hide} 727 */ 728 static final int DRAW_MASK = 0x00000080; 729 730 /** 731 * <p>This view doesn't show scrollbars.</p> 732 * {@hide} 733 */ 734 static final int SCROLLBARS_NONE = 0x00000000; 735 736 /** 737 * <p>This view shows horizontal scrollbars.</p> 738 * {@hide} 739 */ 740 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 741 742 /** 743 * <p>This view shows vertical scrollbars.</p> 744 * {@hide} 745 */ 746 static final int SCROLLBARS_VERTICAL = 0x00000200; 747 748 /** 749 * <p>Mask for use with setFlags indicating bits used for indicating which 750 * scrollbars are enabled.</p> 751 * {@hide} 752 */ 753 static final int SCROLLBARS_MASK = 0x00000300; 754 755 /** 756 * Indicates that the view should filter touches when its window is obscured. 757 * Refer to the class comments for more information about this security feature. 758 * {@hide} 759 */ 760 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 761 762 // note flag value 0x00000800 is now available for next flags... 763 764 /** 765 * <p>This view doesn't show fading edges.</p> 766 * {@hide} 767 */ 768 static final int FADING_EDGE_NONE = 0x00000000; 769 770 /** 771 * <p>This view shows horizontal fading edges.</p> 772 * {@hide} 773 */ 774 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 775 776 /** 777 * <p>This view shows vertical fading edges.</p> 778 * {@hide} 779 */ 780 static final int FADING_EDGE_VERTICAL = 0x00002000; 781 782 /** 783 * <p>Mask for use with setFlags indicating bits used for indicating which 784 * fading edges are enabled.</p> 785 * {@hide} 786 */ 787 static final int FADING_EDGE_MASK = 0x00003000; 788 789 /** 790 * <p>Indicates this view can be clicked. When clickable, a View reacts 791 * to clicks by notifying the OnClickListener.<p> 792 * {@hide} 793 */ 794 static final int CLICKABLE = 0x00004000; 795 796 /** 797 * <p>Indicates this view is caching its drawing into a bitmap.</p> 798 * {@hide} 799 */ 800 static final int DRAWING_CACHE_ENABLED = 0x00008000; 801 802 /** 803 * <p>Indicates that no icicle should be saved for this view.<p> 804 * {@hide} 805 */ 806 static final int SAVE_DISABLED = 0x000010000; 807 808 /** 809 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 810 * property.</p> 811 * {@hide} 812 */ 813 static final int SAVE_DISABLED_MASK = 0x000010000; 814 815 /** 816 * <p>Indicates that no drawing cache should ever be created for this view.<p> 817 * {@hide} 818 */ 819 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 820 821 /** 822 * <p>Indicates this view can take / keep focus when int touch mode.</p> 823 * {@hide} 824 */ 825 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 826 827 /** 828 * <p>Enables low quality mode for the drawing cache.</p> 829 */ 830 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 831 832 /** 833 * <p>Enables high quality mode for the drawing cache.</p> 834 */ 835 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 836 837 /** 838 * <p>Enables automatic quality mode for the drawing cache.</p> 839 */ 840 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 841 842 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 843 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 844 }; 845 846 /** 847 * <p>Mask for use with setFlags indicating bits used for the cache 848 * quality property.</p> 849 * {@hide} 850 */ 851 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 852 853 /** 854 * <p> 855 * Indicates this view can be long clicked. When long clickable, a View 856 * reacts to long clicks by notifying the OnLongClickListener or showing a 857 * context menu. 858 * </p> 859 * {@hide} 860 */ 861 static final int LONG_CLICKABLE = 0x00200000; 862 863 /** 864 * <p>Indicates that this view gets its drawable states from its direct parent 865 * and ignores its original internal states.</p> 866 * 867 * @hide 868 */ 869 static final int DUPLICATE_PARENT_STATE = 0x00400000; 870 871 /** 872 * The scrollbar style to display the scrollbars inside the content area, 873 * without increasing the padding. The scrollbars will be overlaid with 874 * translucency on the view's content. 875 */ 876 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 877 878 /** 879 * The scrollbar style to display the scrollbars inside the padded area, 880 * increasing the padding of the view. The scrollbars will not overlap the 881 * content area of the view. 882 */ 883 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 884 885 /** 886 * The scrollbar style to display the scrollbars at the edge of the view, 887 * without increasing the padding. The scrollbars will be overlaid with 888 * translucency. 889 */ 890 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 891 892 /** 893 * The scrollbar style to display the scrollbars at the edge of the view, 894 * increasing the padding of the view. The scrollbars will only overlap the 895 * background, if any. 896 */ 897 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 898 899 /** 900 * Mask to check if the scrollbar style is overlay or inset. 901 * {@hide} 902 */ 903 static final int SCROLLBARS_INSET_MASK = 0x01000000; 904 905 /** 906 * Mask to check if the scrollbar style is inside or outside. 907 * {@hide} 908 */ 909 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 910 911 /** 912 * Mask for scrollbar style. 913 * {@hide} 914 */ 915 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 916 917 /** 918 * View flag indicating that the screen should remain on while the 919 * window containing this view is visible to the user. This effectively 920 * takes care of automatically setting the WindowManager's 921 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 922 */ 923 public static final int KEEP_SCREEN_ON = 0x04000000; 924 925 /** 926 * View flag indicating whether this view should have sound effects enabled 927 * for events such as clicking and touching. 928 */ 929 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 930 931 /** 932 * View flag indicating whether this view should have haptic feedback 933 * enabled for events such as long presses. 934 */ 935 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 936 937 /** 938 * <p>Indicates that the view hierarchy should stop saving state when 939 * it reaches this view. If state saving is initiated immediately at 940 * the view, it will be allowed. 941 * {@hide} 942 */ 943 static final int PARENT_SAVE_DISABLED = 0x20000000; 944 945 /** 946 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 947 * {@hide} 948 */ 949 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 950 951 /** 952 * Horizontal direction of this view is from Left to Right. 953 * Use with {@link #setHorizontalDirection}. 954 * {@hide} 955 */ 956 public static final int HORIZONTAL_DIRECTION_LTR = 0x00000000; 957 958 /** 959 * Horizontal direction of this view is from Right to Left. 960 * Use with {@link #setHorizontalDirection}. 961 * {@hide} 962 */ 963 public static final int HORIZONTAL_DIRECTION_RTL = 0x40000000; 964 965 /** 966 * Horizontal direction of this view is inherited from its parent. 967 * Use with {@link #setHorizontalDirection}. 968 * {@hide} 969 */ 970 public static final int HORIZONTAL_DIRECTION_INHERIT = 0x80000000; 971 972 /** 973 * Horizontal direction of this view is from deduced from the default language 974 * script for the locale. Use with {@link #setHorizontalDirection}. 975 * {@hide} 976 */ 977 public static final int HORIZONTAL_DIRECTION_LOCALE = 0xC0000000; 978 979 /** 980 * Mask for use with setFlags indicating bits used for horizontalDirection. 981 * {@hide} 982 */ 983 static final int HORIZONTAL_DIRECTION_MASK = 0xC0000000; 984 985 private static final int[] HORIZONTAL_DIRECTION_FLAGS = { HORIZONTAL_DIRECTION_LTR, 986 HORIZONTAL_DIRECTION_RTL, HORIZONTAL_DIRECTION_INHERIT, HORIZONTAL_DIRECTION_LOCALE}; 987 988 /** 989 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 990 * should add all focusable Views regardless if they are focusable in touch mode. 991 */ 992 public static final int FOCUSABLES_ALL = 0x00000000; 993 994 /** 995 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 996 * should add only Views focusable in touch mode. 997 */ 998 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 999 1000 /** 1001 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1002 * item. 1003 */ 1004 public static final int FOCUS_BACKWARD = 0x00000001; 1005 1006 /** 1007 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1008 * item. 1009 */ 1010 public static final int FOCUS_FORWARD = 0x00000002; 1011 1012 /** 1013 * Use with {@link #focusSearch(int)}. Move focus to the left. 1014 */ 1015 public static final int FOCUS_LEFT = 0x00000011; 1016 1017 /** 1018 * Use with {@link #focusSearch(int)}. Move focus up. 1019 */ 1020 public static final int FOCUS_UP = 0x00000021; 1021 1022 /** 1023 * Use with {@link #focusSearch(int)}. Move focus to the right. 1024 */ 1025 public static final int FOCUS_RIGHT = 0x00000042; 1026 1027 /** 1028 * Use with {@link #focusSearch(int)}. Move focus down. 1029 */ 1030 public static final int FOCUS_DOWN = 0x00000082; 1031 1032 /** 1033 * Bits of {@link #getMeasuredWidthAndState()} and 1034 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1035 */ 1036 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1037 1038 /** 1039 * Bits of {@link #getMeasuredWidthAndState()} and 1040 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1041 */ 1042 public static final int MEASURED_STATE_MASK = 0xff000000; 1043 1044 /** 1045 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1046 * for functions that combine both width and height into a single int, 1047 * such as {@link #getMeasuredState()} and the childState argument of 1048 * {@link #resolveSizeAndState(int, int, int)}. 1049 */ 1050 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1051 1052 /** 1053 * Bit of {@link #getMeasuredWidthAndState()} and 1054 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1055 * is smaller that the space the view would like to have. 1056 */ 1057 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1058 1059 /** 1060 * Base View state sets 1061 */ 1062 // Singles 1063 /** 1064 * Indicates the view has no states set. States are used with 1065 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1066 * view depending on its state. 1067 * 1068 * @see android.graphics.drawable.Drawable 1069 * @see #getDrawableState() 1070 */ 1071 protected static final int[] EMPTY_STATE_SET; 1072 /** 1073 * Indicates the view is enabled. States are used with 1074 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1075 * view depending on its state. 1076 * 1077 * @see android.graphics.drawable.Drawable 1078 * @see #getDrawableState() 1079 */ 1080 protected static final int[] ENABLED_STATE_SET; 1081 /** 1082 * Indicates the view is focused. States are used with 1083 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1084 * view depending on its state. 1085 * 1086 * @see android.graphics.drawable.Drawable 1087 * @see #getDrawableState() 1088 */ 1089 protected static final int[] FOCUSED_STATE_SET; 1090 /** 1091 * Indicates the view is selected. States are used with 1092 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1093 * view depending on its state. 1094 * 1095 * @see android.graphics.drawable.Drawable 1096 * @see #getDrawableState() 1097 */ 1098 protected static final int[] SELECTED_STATE_SET; 1099 /** 1100 * Indicates the view is pressed. States are used with 1101 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1102 * view depending on its state. 1103 * 1104 * @see android.graphics.drawable.Drawable 1105 * @see #getDrawableState() 1106 * @hide 1107 */ 1108 protected static final int[] PRESSED_STATE_SET; 1109 /** 1110 * Indicates the view's window has focus. States are used with 1111 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1112 * view depending on its state. 1113 * 1114 * @see android.graphics.drawable.Drawable 1115 * @see #getDrawableState() 1116 */ 1117 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1118 // Doubles 1119 /** 1120 * Indicates the view is enabled and has the focus. 1121 * 1122 * @see #ENABLED_STATE_SET 1123 * @see #FOCUSED_STATE_SET 1124 */ 1125 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1126 /** 1127 * Indicates the view is enabled and selected. 1128 * 1129 * @see #ENABLED_STATE_SET 1130 * @see #SELECTED_STATE_SET 1131 */ 1132 protected static final int[] ENABLED_SELECTED_STATE_SET; 1133 /** 1134 * Indicates the view is enabled and that its window has focus. 1135 * 1136 * @see #ENABLED_STATE_SET 1137 * @see #WINDOW_FOCUSED_STATE_SET 1138 */ 1139 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1140 /** 1141 * Indicates the view is focused and selected. 1142 * 1143 * @see #FOCUSED_STATE_SET 1144 * @see #SELECTED_STATE_SET 1145 */ 1146 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1147 /** 1148 * Indicates the view has the focus and that its window has the focus. 1149 * 1150 * @see #FOCUSED_STATE_SET 1151 * @see #WINDOW_FOCUSED_STATE_SET 1152 */ 1153 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1154 /** 1155 * Indicates the view is selected and that its window has the focus. 1156 * 1157 * @see #SELECTED_STATE_SET 1158 * @see #WINDOW_FOCUSED_STATE_SET 1159 */ 1160 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1161 // Triples 1162 /** 1163 * Indicates the view is enabled, focused and selected. 1164 * 1165 * @see #ENABLED_STATE_SET 1166 * @see #FOCUSED_STATE_SET 1167 * @see #SELECTED_STATE_SET 1168 */ 1169 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1170 /** 1171 * Indicates the view is enabled, focused and its window has the focus. 1172 * 1173 * @see #ENABLED_STATE_SET 1174 * @see #FOCUSED_STATE_SET 1175 * @see #WINDOW_FOCUSED_STATE_SET 1176 */ 1177 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1178 /** 1179 * Indicates the view is enabled, selected and its window has the focus. 1180 * 1181 * @see #ENABLED_STATE_SET 1182 * @see #SELECTED_STATE_SET 1183 * @see #WINDOW_FOCUSED_STATE_SET 1184 */ 1185 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1186 /** 1187 * Indicates the view is focused, selected and its window has the focus. 1188 * 1189 * @see #FOCUSED_STATE_SET 1190 * @see #SELECTED_STATE_SET 1191 * @see #WINDOW_FOCUSED_STATE_SET 1192 */ 1193 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1194 /** 1195 * Indicates the view is enabled, focused, selected and its window 1196 * has the focus. 1197 * 1198 * @see #ENABLED_STATE_SET 1199 * @see #FOCUSED_STATE_SET 1200 * @see #SELECTED_STATE_SET 1201 * @see #WINDOW_FOCUSED_STATE_SET 1202 */ 1203 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1204 /** 1205 * Indicates the view is pressed and its window has the focus. 1206 * 1207 * @see #PRESSED_STATE_SET 1208 * @see #WINDOW_FOCUSED_STATE_SET 1209 */ 1210 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1211 /** 1212 * Indicates the view is pressed and selected. 1213 * 1214 * @see #PRESSED_STATE_SET 1215 * @see #SELECTED_STATE_SET 1216 */ 1217 protected static final int[] PRESSED_SELECTED_STATE_SET; 1218 /** 1219 * Indicates the view is pressed, selected and its window has the focus. 1220 * 1221 * @see #PRESSED_STATE_SET 1222 * @see #SELECTED_STATE_SET 1223 * @see #WINDOW_FOCUSED_STATE_SET 1224 */ 1225 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1226 /** 1227 * Indicates the view is pressed and focused. 1228 * 1229 * @see #PRESSED_STATE_SET 1230 * @see #FOCUSED_STATE_SET 1231 */ 1232 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1233 /** 1234 * Indicates the view is pressed, focused and its window has the focus. 1235 * 1236 * @see #PRESSED_STATE_SET 1237 * @see #FOCUSED_STATE_SET 1238 * @see #WINDOW_FOCUSED_STATE_SET 1239 */ 1240 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1241 /** 1242 * Indicates the view is pressed, focused and selected. 1243 * 1244 * @see #PRESSED_STATE_SET 1245 * @see #SELECTED_STATE_SET 1246 * @see #FOCUSED_STATE_SET 1247 */ 1248 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1249 /** 1250 * Indicates the view is pressed, focused, selected and its window has the focus. 1251 * 1252 * @see #PRESSED_STATE_SET 1253 * @see #FOCUSED_STATE_SET 1254 * @see #SELECTED_STATE_SET 1255 * @see #WINDOW_FOCUSED_STATE_SET 1256 */ 1257 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1258 /** 1259 * Indicates the view is pressed and enabled. 1260 * 1261 * @see #PRESSED_STATE_SET 1262 * @see #ENABLED_STATE_SET 1263 */ 1264 protected static final int[] PRESSED_ENABLED_STATE_SET; 1265 /** 1266 * Indicates the view is pressed, enabled and its window has the focus. 1267 * 1268 * @see #PRESSED_STATE_SET 1269 * @see #ENABLED_STATE_SET 1270 * @see #WINDOW_FOCUSED_STATE_SET 1271 */ 1272 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1273 /** 1274 * Indicates the view is pressed, enabled and selected. 1275 * 1276 * @see #PRESSED_STATE_SET 1277 * @see #ENABLED_STATE_SET 1278 * @see #SELECTED_STATE_SET 1279 */ 1280 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1281 /** 1282 * Indicates the view is pressed, enabled, selected and its window has the 1283 * focus. 1284 * 1285 * @see #PRESSED_STATE_SET 1286 * @see #ENABLED_STATE_SET 1287 * @see #SELECTED_STATE_SET 1288 * @see #WINDOW_FOCUSED_STATE_SET 1289 */ 1290 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1291 /** 1292 * Indicates the view is pressed, enabled and focused. 1293 * 1294 * @see #PRESSED_STATE_SET 1295 * @see #ENABLED_STATE_SET 1296 * @see #FOCUSED_STATE_SET 1297 */ 1298 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1299 /** 1300 * Indicates the view is pressed, enabled, focused and its window has the 1301 * focus. 1302 * 1303 * @see #PRESSED_STATE_SET 1304 * @see #ENABLED_STATE_SET 1305 * @see #FOCUSED_STATE_SET 1306 * @see #WINDOW_FOCUSED_STATE_SET 1307 */ 1308 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1309 /** 1310 * Indicates the view is pressed, enabled, focused and selected. 1311 * 1312 * @see #PRESSED_STATE_SET 1313 * @see #ENABLED_STATE_SET 1314 * @see #SELECTED_STATE_SET 1315 * @see #FOCUSED_STATE_SET 1316 */ 1317 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1318 /** 1319 * Indicates the view is pressed, enabled, focused, selected and its window 1320 * has the focus. 1321 * 1322 * @see #PRESSED_STATE_SET 1323 * @see #ENABLED_STATE_SET 1324 * @see #SELECTED_STATE_SET 1325 * @see #FOCUSED_STATE_SET 1326 * @see #WINDOW_FOCUSED_STATE_SET 1327 */ 1328 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1329 1330 /** 1331 * The order here is very important to {@link #getDrawableState()} 1332 */ 1333 private static final int[][] VIEW_STATE_SETS; 1334 1335 static final int VIEW_STATE_WINDOW_FOCUSED = 1; 1336 static final int VIEW_STATE_SELECTED = 1 << 1; 1337 static final int VIEW_STATE_FOCUSED = 1 << 2; 1338 static final int VIEW_STATE_ENABLED = 1 << 3; 1339 static final int VIEW_STATE_PRESSED = 1 << 4; 1340 static final int VIEW_STATE_ACTIVATED = 1 << 5; 1341 static final int VIEW_STATE_ACCELERATED = 1 << 6; 1342 static final int VIEW_STATE_HOVERED = 1 << 7; 1343 static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8; 1344 static final int VIEW_STATE_DRAG_HOVERED = 1 << 9; 1345 1346 static final int[] VIEW_STATE_IDS = new int[] { 1347 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED, 1348 R.attr.state_selected, VIEW_STATE_SELECTED, 1349 R.attr.state_focused, VIEW_STATE_FOCUSED, 1350 R.attr.state_enabled, VIEW_STATE_ENABLED, 1351 R.attr.state_pressed, VIEW_STATE_PRESSED, 1352 R.attr.state_activated, VIEW_STATE_ACTIVATED, 1353 R.attr.state_accelerated, VIEW_STATE_ACCELERATED, 1354 R.attr.state_hovered, VIEW_STATE_HOVERED, 1355 R.attr.state_drag_can_accept, VIEW_STATE_DRAG_CAN_ACCEPT, 1356 R.attr.state_drag_hovered, VIEW_STATE_DRAG_HOVERED, 1357 }; 1358 1359 static { 1360 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) { 1361 throw new IllegalStateException( 1362 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array"); 1363 } 1364 int[] orderedIds = new int[VIEW_STATE_IDS.length]; 1365 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) { 1366 int viewState = R.styleable.ViewDrawableStates[i]; 1367 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) { 1368 if (VIEW_STATE_IDS[j] == viewState) { 1369 orderedIds[i * 2] = viewState; 1370 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1]; 1371 } 1372 } 1373 } 1374 final int NUM_BITS = VIEW_STATE_IDS.length / 2; 1375 VIEW_STATE_SETS = new int[1 << NUM_BITS][]; 1376 for (int i = 0; i < VIEW_STATE_SETS.length; i++) { 1377 int numBits = Integer.bitCount(i); 1378 int[] set = new int[numBits]; 1379 int pos = 0; 1380 for (int j = 0; j < orderedIds.length; j += 2) { 1381 if ((i & orderedIds[j+1]) != 0) { 1382 set[pos++] = orderedIds[j]; 1383 } 1384 } 1385 VIEW_STATE_SETS[i] = set; 1386 } 1387 1388 EMPTY_STATE_SET = VIEW_STATE_SETS[0]; 1389 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED]; 1390 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED]; 1391 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1392 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED]; 1393 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED]; 1394 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1395 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED]; 1396 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1397 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED]; 1398 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1399 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1400 | VIEW_STATE_FOCUSED]; 1401 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED]; 1402 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1403 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED]; 1404 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1405 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED]; 1406 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1407 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1408 | VIEW_STATE_ENABLED]; 1409 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1410 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED]; 1411 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1412 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1413 | VIEW_STATE_ENABLED]; 1414 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1415 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1416 | VIEW_STATE_ENABLED]; 1417 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1418 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1419 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED]; 1420 1421 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED]; 1422 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1423 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED]; 1424 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1425 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED]; 1426 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1427 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1428 | VIEW_STATE_PRESSED]; 1429 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1430 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1431 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1432 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1433 | VIEW_STATE_PRESSED]; 1434 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1435 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1436 | VIEW_STATE_PRESSED]; 1437 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1438 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1439 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1440 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[ 1441 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1442 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1443 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED 1444 | VIEW_STATE_PRESSED]; 1445 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1446 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED 1447 | VIEW_STATE_PRESSED]; 1448 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1449 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1450 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1451 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1452 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED 1453 | VIEW_STATE_PRESSED]; 1454 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1455 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1456 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1457 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1458 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1459 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1460 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1461 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1462 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED 1463 | VIEW_STATE_PRESSED]; 1464 } 1465 1466 /** 1467 * Temporary Rect currently for use in setBackground(). This will probably 1468 * be extended in the future to hold our own class with more than just 1469 * a Rect. :) 1470 */ 1471 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1472 1473 /** 1474 * Map used to store views' tags. 1475 */ 1476 private static WeakHashMap<View, SparseArray<Object>> sTags; 1477 1478 /** 1479 * Lock used to access sTags. 1480 */ 1481 private static final Object sTagsLock = new Object(); 1482 1483 /** 1484 * The animation currently associated with this view. 1485 * @hide 1486 */ 1487 protected Animation mCurrentAnimation = null; 1488 1489 /** 1490 * Width as measured during measure pass. 1491 * {@hide} 1492 */ 1493 @ViewDebug.ExportedProperty(category = "measurement") 1494 int mMeasuredWidth; 1495 1496 /** 1497 * Height as measured during measure pass. 1498 * {@hide} 1499 */ 1500 @ViewDebug.ExportedProperty(category = "measurement") 1501 int mMeasuredHeight; 1502 1503 /** 1504 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1505 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1506 * its display list. This flag, used only when hw accelerated, allows us to clear the 1507 * flag while retaining this information until it's needed (at getDisplayList() time and 1508 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1509 * 1510 * {@hide} 1511 */ 1512 boolean mRecreateDisplayList = false; 1513 1514 /** 1515 * The view's identifier. 1516 * {@hide} 1517 * 1518 * @see #setId(int) 1519 * @see #getId() 1520 */ 1521 @ViewDebug.ExportedProperty(resolveId = true) 1522 int mID = NO_ID; 1523 1524 /** 1525 * The view's tag. 1526 * {@hide} 1527 * 1528 * @see #setTag(Object) 1529 * @see #getTag() 1530 */ 1531 protected Object mTag; 1532 1533 // for mPrivateFlags: 1534 /** {@hide} */ 1535 static final int WANTS_FOCUS = 0x00000001; 1536 /** {@hide} */ 1537 static final int FOCUSED = 0x00000002; 1538 /** {@hide} */ 1539 static final int SELECTED = 0x00000004; 1540 /** {@hide} */ 1541 static final int IS_ROOT_NAMESPACE = 0x00000008; 1542 /** {@hide} */ 1543 static final int HAS_BOUNDS = 0x00000010; 1544 /** {@hide} */ 1545 static final int DRAWN = 0x00000020; 1546 /** 1547 * When this flag is set, this view is running an animation on behalf of its 1548 * children and should therefore not cancel invalidate requests, even if they 1549 * lie outside of this view's bounds. 1550 * 1551 * {@hide} 1552 */ 1553 static final int DRAW_ANIMATION = 0x00000040; 1554 /** {@hide} */ 1555 static final int SKIP_DRAW = 0x00000080; 1556 /** {@hide} */ 1557 static final int ONLY_DRAWS_BACKGROUND = 0x00000100; 1558 /** {@hide} */ 1559 static final int REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1560 /** {@hide} */ 1561 static final int DRAWABLE_STATE_DIRTY = 0x00000400; 1562 /** {@hide} */ 1563 static final int MEASURED_DIMENSION_SET = 0x00000800; 1564 /** {@hide} */ 1565 static final int FORCE_LAYOUT = 0x00001000; 1566 /** {@hide} */ 1567 static final int LAYOUT_REQUIRED = 0x00002000; 1568 1569 private static final int PRESSED = 0x00004000; 1570 1571 /** {@hide} */ 1572 static final int DRAWING_CACHE_VALID = 0x00008000; 1573 /** 1574 * Flag used to indicate that this view should be drawn once more (and only once 1575 * more) after its animation has completed. 1576 * {@hide} 1577 */ 1578 static final int ANIMATION_STARTED = 0x00010000; 1579 1580 private static final int SAVE_STATE_CALLED = 0x00020000; 1581 1582 /** 1583 * Indicates that the View returned true when onSetAlpha() was called and that 1584 * the alpha must be restored. 1585 * {@hide} 1586 */ 1587 static final int ALPHA_SET = 0x00040000; 1588 1589 /** 1590 * Set by {@link #setScrollContainer(boolean)}. 1591 */ 1592 static final int SCROLL_CONTAINER = 0x00080000; 1593 1594 /** 1595 * Set by {@link #setScrollContainer(boolean)}. 1596 */ 1597 static final int SCROLL_CONTAINER_ADDED = 0x00100000; 1598 1599 /** 1600 * View flag indicating whether this view was invalidated (fully or partially.) 1601 * 1602 * @hide 1603 */ 1604 static final int DIRTY = 0x00200000; 1605 1606 /** 1607 * View flag indicating whether this view was invalidated by an opaque 1608 * invalidate request. 1609 * 1610 * @hide 1611 */ 1612 static final int DIRTY_OPAQUE = 0x00400000; 1613 1614 /** 1615 * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}. 1616 * 1617 * @hide 1618 */ 1619 static final int DIRTY_MASK = 0x00600000; 1620 1621 /** 1622 * Indicates whether the background is opaque. 1623 * 1624 * @hide 1625 */ 1626 static final int OPAQUE_BACKGROUND = 0x00800000; 1627 1628 /** 1629 * Indicates whether the scrollbars are opaque. 1630 * 1631 * @hide 1632 */ 1633 static final int OPAQUE_SCROLLBARS = 0x01000000; 1634 1635 /** 1636 * Indicates whether the view is opaque. 1637 * 1638 * @hide 1639 */ 1640 static final int OPAQUE_MASK = 0x01800000; 1641 1642 /** 1643 * Indicates a prepressed state; 1644 * the short time between ACTION_DOWN and recognizing 1645 * a 'real' press. Prepressed is used to recognize quick taps 1646 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1647 * 1648 * @hide 1649 */ 1650 private static final int PREPRESSED = 0x02000000; 1651 1652 /** 1653 * Indicates whether the view is temporarily detached. 1654 * 1655 * @hide 1656 */ 1657 static final int CANCEL_NEXT_UP_EVENT = 0x04000000; 1658 1659 /** 1660 * Indicates that we should awaken scroll bars once attached 1661 * 1662 * @hide 1663 */ 1664 private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1665 1666 /** 1667 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1668 * @hide 1669 */ 1670 private static final int HOVERED = 0x10000000; 1671 1672 /** 1673 * Indicates that pivotX or pivotY were explicitly set and we should not assume the center 1674 * for transform operations 1675 * 1676 * @hide 1677 */ 1678 private static final int PIVOT_EXPLICITLY_SET = 0x20000000; 1679 1680 /** {@hide} */ 1681 static final int ACTIVATED = 0x40000000; 1682 1683 /** 1684 * Indicates that this view was specifically invalidated, not just dirtied because some 1685 * child view was invalidated. The flag is used to determine when we need to recreate 1686 * a view's display list (as opposed to just returning a reference to its existing 1687 * display list). 1688 * 1689 * @hide 1690 */ 1691 static final int INVALIDATED = 0x80000000; 1692 1693 /* Masks for mPrivateFlags2 */ 1694 1695 /** 1696 * Indicates that this view has reported that it can accept the current drag's content. 1697 * Cleared when the drag operation concludes. 1698 * @hide 1699 */ 1700 static final int DRAG_CAN_ACCEPT = 0x00000001; 1701 1702 /** 1703 * Indicates that this view is currently directly under the drag location in a 1704 * drag-and-drop operation involving content that it can accept. Cleared when 1705 * the drag exits the view, or when the drag operation concludes. 1706 * @hide 1707 */ 1708 static final int DRAG_HOVERED = 0x00000002; 1709 1710 /** 1711 * Indicates whether the view is drawn in right-to-left direction. 1712 * 1713 * @hide 1714 */ 1715 static final int RESOLVED_LAYOUT_RTL = 0x00000004; 1716 1717 /* End of masks for mPrivateFlags2 */ 1718 1719 static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED; 1720 1721 /** 1722 * Always allow a user to over-scroll this view, provided it is a 1723 * view that can scroll. 1724 * 1725 * @see #getOverScrollMode() 1726 * @see #setOverScrollMode(int) 1727 */ 1728 public static final int OVER_SCROLL_ALWAYS = 0; 1729 1730 /** 1731 * Allow a user to over-scroll this view only if the content is large 1732 * enough to meaningfully scroll, provided it is a view that can scroll. 1733 * 1734 * @see #getOverScrollMode() 1735 * @see #setOverScrollMode(int) 1736 */ 1737 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 1738 1739 /** 1740 * Never allow a user to over-scroll this view. 1741 * 1742 * @see #getOverScrollMode() 1743 * @see #setOverScrollMode(int) 1744 */ 1745 public static final int OVER_SCROLL_NEVER = 2; 1746 1747 /** 1748 * View has requested the status bar to be visible (the default). 1749 * 1750 * @see #setSystemUiVisibility(int) 1751 */ 1752 public static final int STATUS_BAR_VISIBLE = 0; 1753 1754 /** 1755 * View has requested the status bar to be hidden. 1756 * 1757 * @see #setSystemUiVisibility(int) 1758 */ 1759 public static final int STATUS_BAR_HIDDEN = 0x00000001; 1760 1761 /** 1762 * @hide 1763 * 1764 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1765 * out of the public fields to keep the undefined bits out of the developer's way. 1766 * 1767 * Flag to make the status bar not expandable. Unless you also 1768 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 1769 */ 1770 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 1771 1772 /** 1773 * @hide 1774 * 1775 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1776 * out of the public fields to keep the undefined bits out of the developer's way. 1777 * 1778 * Flag to hide notification icons and scrolling ticker text. 1779 */ 1780 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 1781 1782 /** 1783 * @hide 1784 * 1785 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1786 * out of the public fields to keep the undefined bits out of the developer's way. 1787 * 1788 * Flag to disable incoming notification alerts. This will not block 1789 * icons, but it will block sound, vibrating and other visual or aural notifications. 1790 */ 1791 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 1792 1793 /** 1794 * @hide 1795 * 1796 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1797 * out of the public fields to keep the undefined bits out of the developer's way. 1798 * 1799 * Flag to hide only the scrolling ticker. Note that 1800 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 1801 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 1802 */ 1803 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 1804 1805 /** 1806 * @hide 1807 * 1808 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1809 * out of the public fields to keep the undefined bits out of the developer's way. 1810 * 1811 * Flag to hide the center system info area. 1812 */ 1813 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 1814 1815 /** 1816 * @hide 1817 * 1818 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1819 * out of the public fields to keep the undefined bits out of the developer's way. 1820 * 1821 * Flag to hide only the navigation buttons. Don't use this 1822 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 1823 * 1824 * THIS DOES NOT DISABLE THE BACK BUTTON 1825 */ 1826 public static final int STATUS_BAR_DISABLE_NAVIGATION = 0x00200000; 1827 1828 /** 1829 * @hide 1830 * 1831 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1832 * out of the public fields to keep the undefined bits out of the developer's way. 1833 * 1834 * Flag to hide only the back button. Don't use this 1835 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 1836 */ 1837 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 1838 1839 /** 1840 * @hide 1841 * 1842 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 1843 * out of the public fields to keep the undefined bits out of the developer's way. 1844 * 1845 * Flag to hide only the clock. You might use this if your activity has 1846 * its own clock making the status bar's clock redundant. 1847 */ 1848 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 1849 1850 /** 1851 * @hide 1852 */ 1853 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = STATUS_BAR_HIDDEN; 1854 1855 /** 1856 * Controls the over-scroll mode for this view. 1857 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 1858 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 1859 * and {@link #OVER_SCROLL_NEVER}. 1860 */ 1861 private int mOverScrollMode; 1862 1863 /** 1864 * The parent this view is attached to. 1865 * {@hide} 1866 * 1867 * @see #getParent() 1868 */ 1869 protected ViewParent mParent; 1870 1871 /** 1872 * {@hide} 1873 */ 1874 AttachInfo mAttachInfo; 1875 1876 /** 1877 * {@hide} 1878 */ 1879 @ViewDebug.ExportedProperty(flagMapping = { 1880 @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT, 1881 name = "FORCE_LAYOUT"), 1882 @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED, 1883 name = "LAYOUT_REQUIRED"), 1884 @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID, 1885 name = "DRAWING_CACHE_INVALID", outputIf = false), 1886 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true), 1887 @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false), 1888 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 1889 @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY") 1890 }) 1891 int mPrivateFlags; 1892 int mPrivateFlags2; 1893 1894 /** 1895 * This view's request for the visibility of the status bar. 1896 * @hide 1897 */ 1898 @ViewDebug.ExportedProperty() 1899 int mSystemUiVisibility; 1900 1901 /** 1902 * Count of how many windows this view has been attached to. 1903 */ 1904 int mWindowAttachCount; 1905 1906 /** 1907 * The layout parameters associated with this view and used by the parent 1908 * {@link android.view.ViewGroup} to determine how this view should be 1909 * laid out. 1910 * {@hide} 1911 */ 1912 protected ViewGroup.LayoutParams mLayoutParams; 1913 1914 /** 1915 * The view flags hold various views states. 1916 * {@hide} 1917 */ 1918 @ViewDebug.ExportedProperty 1919 int mViewFlags; 1920 1921 /** 1922 * The transform matrix for the View. This transform is calculated internally 1923 * based on the rotation, scaleX, and scaleY properties. The identity matrix 1924 * is used by default. Do *not* use this variable directly; instead call 1925 * getMatrix(), which will automatically recalculate the matrix if necessary 1926 * to get the correct matrix based on the latest rotation and scale properties. 1927 */ 1928 private final Matrix mMatrix = new Matrix(); 1929 1930 /** 1931 * The transform matrix for the View. This transform is calculated internally 1932 * based on the rotation, scaleX, and scaleY properties. The identity matrix 1933 * is used by default. Do *not* use this variable directly; instead call 1934 * getInverseMatrix(), which will automatically recalculate the matrix if necessary 1935 * to get the correct matrix based on the latest rotation and scale properties. 1936 */ 1937 private Matrix mInverseMatrix; 1938 1939 /** 1940 * An internal variable that tracks whether we need to recalculate the 1941 * transform matrix, based on whether the rotation or scaleX/Y properties 1942 * have changed since the matrix was last calculated. 1943 */ 1944 boolean mMatrixDirty = false; 1945 1946 /** 1947 * An internal variable that tracks whether we need to recalculate the 1948 * transform matrix, based on whether the rotation or scaleX/Y properties 1949 * have changed since the matrix was last calculated. 1950 */ 1951 private boolean mInverseMatrixDirty = true; 1952 1953 /** 1954 * A variable that tracks whether we need to recalculate the 1955 * transform matrix, based on whether the rotation or scaleX/Y properties 1956 * have changed since the matrix was last calculated. This variable 1957 * is only valid after a call to updateMatrix() or to a function that 1958 * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix(). 1959 */ 1960 private boolean mMatrixIsIdentity = true; 1961 1962 /** 1963 * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set. 1964 */ 1965 private Camera mCamera = null; 1966 1967 /** 1968 * This matrix is used when computing the matrix for 3D rotations. 1969 */ 1970 private Matrix matrix3D = null; 1971 1972 /** 1973 * These prev values are used to recalculate a centered pivot point when necessary. The 1974 * pivot point is only used in matrix operations (when rotation, scale, or translation are 1975 * set), so thes values are only used then as well. 1976 */ 1977 private int mPrevWidth = -1; 1978 private int mPrevHeight = -1; 1979 1980 private boolean mLastIsOpaque; 1981 1982 /** 1983 * Convenience value to check for float values that are close enough to zero to be considered 1984 * zero. 1985 */ 1986 private static final float NONZERO_EPSILON = .001f; 1987 1988 /** 1989 * The degrees rotation around the vertical axis through the pivot point. 1990 */ 1991 @ViewDebug.ExportedProperty 1992 float mRotationY = 0f; 1993 1994 /** 1995 * The degrees rotation around the horizontal axis through the pivot point. 1996 */ 1997 @ViewDebug.ExportedProperty 1998 float mRotationX = 0f; 1999 2000 /** 2001 * The degrees rotation around the pivot point. 2002 */ 2003 @ViewDebug.ExportedProperty 2004 float mRotation = 0f; 2005 2006 /** 2007 * The amount of translation of the object away from its left property (post-layout). 2008 */ 2009 @ViewDebug.ExportedProperty 2010 float mTranslationX = 0f; 2011 2012 /** 2013 * The amount of translation of the object away from its top property (post-layout). 2014 */ 2015 @ViewDebug.ExportedProperty 2016 float mTranslationY = 0f; 2017 2018 /** 2019 * The amount of scale in the x direction around the pivot point. A 2020 * value of 1 means no scaling is applied. 2021 */ 2022 @ViewDebug.ExportedProperty 2023 float mScaleX = 1f; 2024 2025 /** 2026 * The amount of scale in the y direction around the pivot point. A 2027 * value of 1 means no scaling is applied. 2028 */ 2029 @ViewDebug.ExportedProperty 2030 float mScaleY = 1f; 2031 2032 /** 2033 * The amount of scale in the x direction around the pivot point. A 2034 * value of 1 means no scaling is applied. 2035 */ 2036 @ViewDebug.ExportedProperty 2037 float mPivotX = 0f; 2038 2039 /** 2040 * The amount of scale in the y direction around the pivot point. A 2041 * value of 1 means no scaling is applied. 2042 */ 2043 @ViewDebug.ExportedProperty 2044 float mPivotY = 0f; 2045 2046 /** 2047 * The opacity of the View. This is a value from 0 to 1, where 0 means 2048 * completely transparent and 1 means completely opaque. 2049 */ 2050 @ViewDebug.ExportedProperty 2051 float mAlpha = 1f; 2052 2053 /** 2054 * The distance in pixels from the left edge of this view's parent 2055 * to the left edge of this view. 2056 * {@hide} 2057 */ 2058 @ViewDebug.ExportedProperty(category = "layout") 2059 protected int mLeft; 2060 /** 2061 * The distance in pixels from the left edge of this view's parent 2062 * to the right edge of this view. 2063 * {@hide} 2064 */ 2065 @ViewDebug.ExportedProperty(category = "layout") 2066 protected int mRight; 2067 /** 2068 * The distance in pixels from the top edge of this view's parent 2069 * to the top edge of this view. 2070 * {@hide} 2071 */ 2072 @ViewDebug.ExportedProperty(category = "layout") 2073 protected int mTop; 2074 /** 2075 * The distance in pixels from the top edge of this view's parent 2076 * to the bottom edge of this view. 2077 * {@hide} 2078 */ 2079 @ViewDebug.ExportedProperty(category = "layout") 2080 protected int mBottom; 2081 2082 /** 2083 * The offset, in pixels, by which the content of this view is scrolled 2084 * horizontally. 2085 * {@hide} 2086 */ 2087 @ViewDebug.ExportedProperty(category = "scrolling") 2088 protected int mScrollX; 2089 /** 2090 * The offset, in pixels, by which the content of this view is scrolled 2091 * vertically. 2092 * {@hide} 2093 */ 2094 @ViewDebug.ExportedProperty(category = "scrolling") 2095 protected int mScrollY; 2096 2097 /** 2098 * The left padding in pixels, that is the distance in pixels between the 2099 * left edge of this view and the left edge of its content. 2100 * {@hide} 2101 */ 2102 @ViewDebug.ExportedProperty(category = "padding") 2103 protected int mPaddingLeft; 2104 /** 2105 * The right padding in pixels, that is the distance in pixels between the 2106 * right edge of this view and the right edge of its content. 2107 * {@hide} 2108 */ 2109 @ViewDebug.ExportedProperty(category = "padding") 2110 protected int mPaddingRight; 2111 /** 2112 * The top padding in pixels, that is the distance in pixels between the 2113 * top edge of this view and the top edge of its content. 2114 * {@hide} 2115 */ 2116 @ViewDebug.ExportedProperty(category = "padding") 2117 protected int mPaddingTop; 2118 /** 2119 * The bottom padding in pixels, that is the distance in pixels between the 2120 * bottom edge of this view and the bottom edge of its content. 2121 * {@hide} 2122 */ 2123 @ViewDebug.ExportedProperty(category = "padding") 2124 protected int mPaddingBottom; 2125 2126 /** 2127 * Briefly describes the view and is primarily used for accessibility support. 2128 */ 2129 private CharSequence mContentDescription; 2130 2131 /** 2132 * Cache the paddingRight set by the user to append to the scrollbar's size. 2133 */ 2134 @ViewDebug.ExportedProperty(category = "padding") 2135 int mUserPaddingRight; 2136 2137 /** 2138 * Cache the paddingBottom set by the user to append to the scrollbar's size. 2139 */ 2140 @ViewDebug.ExportedProperty(category = "padding") 2141 int mUserPaddingBottom; 2142 2143 /** 2144 * Cache the paddingLeft set by the user to append to the scrollbar's size. 2145 */ 2146 @ViewDebug.ExportedProperty(category = "padding") 2147 int mUserPaddingLeft; 2148 2149 /** 2150 * @hide 2151 */ 2152 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 2153 /** 2154 * @hide 2155 */ 2156 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 2157 2158 private Resources mResources = null; 2159 2160 private Drawable mBGDrawable; 2161 2162 private int mBackgroundResource; 2163 private boolean mBackgroundSizeChanged; 2164 2165 /** 2166 * Listener used to dispatch focus change events. 2167 * This field should be made private, so it is hidden from the SDK. 2168 * {@hide} 2169 */ 2170 protected OnFocusChangeListener mOnFocusChangeListener; 2171 2172 /** 2173 * Listeners for layout change events. 2174 */ 2175 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 2176 2177 /** 2178 * Listeners for attach events. 2179 */ 2180 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 2181 2182 /** 2183 * Listener used to dispatch click events. 2184 * This field should be made private, so it is hidden from the SDK. 2185 * {@hide} 2186 */ 2187 protected OnClickListener mOnClickListener; 2188 2189 /** 2190 * Listener used to dispatch long click events. 2191 * This field should be made private, so it is hidden from the SDK. 2192 * {@hide} 2193 */ 2194 protected OnLongClickListener mOnLongClickListener; 2195 2196 /** 2197 * Listener used to build the context menu. 2198 * This field should be made private, so it is hidden from the SDK. 2199 * {@hide} 2200 */ 2201 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 2202 2203 private OnKeyListener mOnKeyListener; 2204 2205 private OnTouchListener mOnTouchListener; 2206 2207 private OnGenericMotionListener mOnGenericMotionListener; 2208 2209 private OnDragListener mOnDragListener; 2210 2211 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 2212 2213 /** 2214 * The application environment this view lives in. 2215 * This field should be made private, so it is hidden from the SDK. 2216 * {@hide} 2217 */ 2218 protected Context mContext; 2219 2220 private ScrollabilityCache mScrollCache; 2221 2222 private int[] mDrawableState = null; 2223 2224 /** 2225 * Set to true when drawing cache is enabled and cannot be created. 2226 * 2227 * @hide 2228 */ 2229 public boolean mCachingFailed; 2230 2231 private Bitmap mDrawingCache; 2232 private Bitmap mUnscaledDrawingCache; 2233 private DisplayList mDisplayList; 2234 private HardwareLayer mHardwareLayer; 2235 2236 /** 2237 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 2238 * the user may specify which view to go to next. 2239 */ 2240 private int mNextFocusLeftId = View.NO_ID; 2241 2242 /** 2243 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 2244 * the user may specify which view to go to next. 2245 */ 2246 private int mNextFocusRightId = View.NO_ID; 2247 2248 /** 2249 * When this view has focus and the next focus is {@link #FOCUS_UP}, 2250 * the user may specify which view to go to next. 2251 */ 2252 private int mNextFocusUpId = View.NO_ID; 2253 2254 /** 2255 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 2256 * the user may specify which view to go to next. 2257 */ 2258 private int mNextFocusDownId = View.NO_ID; 2259 2260 /** 2261 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 2262 * the user may specify which view to go to next. 2263 */ 2264 int mNextFocusForwardId = View.NO_ID; 2265 2266 private CheckForLongPress mPendingCheckForLongPress; 2267 private CheckForTap mPendingCheckForTap = null; 2268 private PerformClick mPerformClick; 2269 2270 private UnsetPressedState mUnsetPressedState; 2271 2272 /** 2273 * Whether the long press's action has been invoked. The tap's action is invoked on the 2274 * up event while a long press is invoked as soon as the long press duration is reached, so 2275 * a long press could be performed before the tap is checked, in which case the tap's action 2276 * should not be invoked. 2277 */ 2278 private boolean mHasPerformedLongPress; 2279 2280 /** 2281 * The minimum height of the view. We'll try our best to have the height 2282 * of this view to at least this amount. 2283 */ 2284 @ViewDebug.ExportedProperty(category = "measurement") 2285 private int mMinHeight; 2286 2287 /** 2288 * The minimum width of the view. We'll try our best to have the width 2289 * of this view to at least this amount. 2290 */ 2291 @ViewDebug.ExportedProperty(category = "measurement") 2292 private int mMinWidth; 2293 2294 /** 2295 * The delegate to handle touch events that are physically in this view 2296 * but should be handled by another view. 2297 */ 2298 private TouchDelegate mTouchDelegate = null; 2299 2300 /** 2301 * Solid color to use as a background when creating the drawing cache. Enables 2302 * the cache to use 16 bit bitmaps instead of 32 bit. 2303 */ 2304 private int mDrawingCacheBackgroundColor = 0; 2305 2306 /** 2307 * Special tree observer used when mAttachInfo is null. 2308 */ 2309 private ViewTreeObserver mFloatingTreeObserver; 2310 2311 /** 2312 * Cache the touch slop from the context that created the view. 2313 */ 2314 private int mTouchSlop; 2315 2316 /** 2317 * Object that handles automatic animation of view properties. 2318 */ 2319 private ViewPropertyAnimator mAnimator = null; 2320 2321 /** 2322 * Flag indicating that a drag can cross window boundaries. When 2323 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 2324 * with this flag set, all visible applications will be able to participate 2325 * in the drag operation and receive the dragged content. 2326 * 2327 * @hide 2328 */ 2329 public static final int DRAG_FLAG_GLOBAL = 1; 2330 2331 /** 2332 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 2333 */ 2334 private float mVerticalScrollFactor; 2335 2336 /** 2337 * Position of the vertical scroll bar. 2338 */ 2339 private int mVerticalScrollbarPosition; 2340 2341 /** 2342 * Position the scroll bar at the default position as determined by the system. 2343 */ 2344 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 2345 2346 /** 2347 * Position the scroll bar along the left edge. 2348 */ 2349 public static final int SCROLLBAR_POSITION_LEFT = 1; 2350 2351 /** 2352 * Position the scroll bar along the right edge. 2353 */ 2354 public static final int SCROLLBAR_POSITION_RIGHT = 2; 2355 2356 /** 2357 * Indicates that the view does not have a layer. 2358 * 2359 * @see #getLayerType() 2360 * @see #setLayerType(int, android.graphics.Paint) 2361 * @see #LAYER_TYPE_SOFTWARE 2362 * @see #LAYER_TYPE_HARDWARE 2363 */ 2364 public static final int LAYER_TYPE_NONE = 0; 2365 2366 /** 2367 * <p>Indicates that the view has a software layer. A software layer is backed 2368 * by a bitmap and causes the view to be rendered using Android's software 2369 * rendering pipeline, even if hardware acceleration is enabled.</p> 2370 * 2371 * <p>Software layers have various usages:</p> 2372 * <p>When the application is not using hardware acceleration, a software layer 2373 * is useful to apply a specific color filter and/or blending mode and/or 2374 * translucency to a view and all its children.</p> 2375 * <p>When the application is using hardware acceleration, a software layer 2376 * is useful to render drawing primitives not supported by the hardware 2377 * accelerated pipeline. It can also be used to cache a complex view tree 2378 * into a texture and reduce the complexity of drawing operations. For instance, 2379 * when animating a complex view tree with a translation, a software layer can 2380 * be used to render the view tree only once.</p> 2381 * <p>Software layers should be avoided when the affected view tree updates 2382 * often. Every update will require to re-render the software layer, which can 2383 * potentially be slow (particularly when hardware acceleration is turned on 2384 * since the layer will have to be uploaded into a hardware texture after every 2385 * update.)</p> 2386 * 2387 * @see #getLayerType() 2388 * @see #setLayerType(int, android.graphics.Paint) 2389 * @see #LAYER_TYPE_NONE 2390 * @see #LAYER_TYPE_HARDWARE 2391 */ 2392 public static final int LAYER_TYPE_SOFTWARE = 1; 2393 2394 /** 2395 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 2396 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 2397 * OpenGL hardware) and causes the view to be rendered using Android's hardware 2398 * rendering pipeline, but only if hardware acceleration is turned on for the 2399 * view hierarchy. When hardware acceleration is turned off, hardware layers 2400 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 2401 * 2402 * <p>A hardware layer is useful to apply a specific color filter and/or 2403 * blending mode and/or translucency to a view and all its children.</p> 2404 * <p>A hardware layer can be used to cache a complex view tree into a 2405 * texture and reduce the complexity of drawing operations. For instance, 2406 * when animating a complex view tree with a translation, a hardware layer can 2407 * be used to render the view tree only once.</p> 2408 * <p>A hardware layer can also be used to increase the rendering quality when 2409 * rotation transformations are applied on a view. It can also be used to 2410 * prevent potential clipping issues when applying 3D transforms on a view.</p> 2411 * 2412 * @see #getLayerType() 2413 * @see #setLayerType(int, android.graphics.Paint) 2414 * @see #LAYER_TYPE_NONE 2415 * @see #LAYER_TYPE_SOFTWARE 2416 */ 2417 public static final int LAYER_TYPE_HARDWARE = 2; 2418 2419 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 2420 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 2421 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 2422 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 2423 }) 2424 int mLayerType = LAYER_TYPE_NONE; 2425 Paint mLayerPaint; 2426 Rect mLocalDirtyRect; 2427 2428 /** 2429 * Consistency verifier for debugging purposes. 2430 * @hide 2431 */ 2432 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 2433 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 2434 new InputEventConsistencyVerifier(this, 0) : null; 2435 2436 /** 2437 * Simple constructor to use when creating a view from code. 2438 * 2439 * @param context The Context the view is running in, through which it can 2440 * access the current theme, resources, etc. 2441 */ 2442 public View(Context context) { 2443 mContext = context; 2444 mResources = context != null ? context.getResources() : null; 2445 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 2446 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 2447 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 2448 } 2449 2450 /** 2451 * Constructor that is called when inflating a view from XML. This is called 2452 * when a view is being constructed from an XML file, supplying attributes 2453 * that were specified in the XML file. This version uses a default style of 2454 * 0, so the only attribute values applied are those in the Context's Theme 2455 * and the given AttributeSet. 2456 * 2457 * <p> 2458 * The method onFinishInflate() will be called after all children have been 2459 * added. 2460 * 2461 * @param context The Context the view is running in, through which it can 2462 * access the current theme, resources, etc. 2463 * @param attrs The attributes of the XML tag that is inflating the view. 2464 * @see #View(Context, AttributeSet, int) 2465 */ 2466 public View(Context context, AttributeSet attrs) { 2467 this(context, attrs, 0); 2468 } 2469 2470 /** 2471 * Perform inflation from XML and apply a class-specific base style. This 2472 * constructor of View allows subclasses to use their own base style when 2473 * they are inflating. For example, a Button class's constructor would call 2474 * this version of the super class constructor and supply 2475 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows 2476 * the theme's button style to modify all of the base view attributes (in 2477 * particular its background) as well as the Button class's attributes. 2478 * 2479 * @param context The Context the view is running in, through which it can 2480 * access the current theme, resources, etc. 2481 * @param attrs The attributes of the XML tag that is inflating the view. 2482 * @param defStyle The default style to apply to this view. If 0, no style 2483 * will be applied (beyond what is included in the theme). This may 2484 * either be an attribute resource, whose value will be retrieved 2485 * from the current theme, or an explicit style resource. 2486 * @see #View(Context, AttributeSet) 2487 */ 2488 public View(Context context, AttributeSet attrs, int defStyle) { 2489 this(context); 2490 2491 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View, 2492 defStyle, 0); 2493 2494 Drawable background = null; 2495 2496 int leftPadding = -1; 2497 int topPadding = -1; 2498 int rightPadding = -1; 2499 int bottomPadding = -1; 2500 2501 int padding = -1; 2502 2503 int viewFlagValues = 0; 2504 int viewFlagMasks = 0; 2505 2506 boolean setScrollContainer = false; 2507 2508 int x = 0; 2509 int y = 0; 2510 2511 float tx = 0; 2512 float ty = 0; 2513 float rotation = 0; 2514 float rotationX = 0; 2515 float rotationY = 0; 2516 float sx = 1f; 2517 float sy = 1f; 2518 boolean transformSet = false; 2519 2520 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 2521 2522 int overScrollMode = mOverScrollMode; 2523 final int N = a.getIndexCount(); 2524 for (int i = 0; i < N; i++) { 2525 int attr = a.getIndex(i); 2526 switch (attr) { 2527 case com.android.internal.R.styleable.View_background: 2528 background = a.getDrawable(attr); 2529 break; 2530 case com.android.internal.R.styleable.View_padding: 2531 padding = a.getDimensionPixelSize(attr, -1); 2532 break; 2533 case com.android.internal.R.styleable.View_paddingLeft: 2534 leftPadding = a.getDimensionPixelSize(attr, -1); 2535 break; 2536 case com.android.internal.R.styleable.View_paddingTop: 2537 topPadding = a.getDimensionPixelSize(attr, -1); 2538 break; 2539 case com.android.internal.R.styleable.View_paddingRight: 2540 rightPadding = a.getDimensionPixelSize(attr, -1); 2541 break; 2542 case com.android.internal.R.styleable.View_paddingBottom: 2543 bottomPadding = a.getDimensionPixelSize(attr, -1); 2544 break; 2545 case com.android.internal.R.styleable.View_scrollX: 2546 x = a.getDimensionPixelOffset(attr, 0); 2547 break; 2548 case com.android.internal.R.styleable.View_scrollY: 2549 y = a.getDimensionPixelOffset(attr, 0); 2550 break; 2551 case com.android.internal.R.styleable.View_alpha: 2552 setAlpha(a.getFloat(attr, 1f)); 2553 break; 2554 case com.android.internal.R.styleable.View_transformPivotX: 2555 setPivotX(a.getDimensionPixelOffset(attr, 0)); 2556 break; 2557 case com.android.internal.R.styleable.View_transformPivotY: 2558 setPivotY(a.getDimensionPixelOffset(attr, 0)); 2559 break; 2560 case com.android.internal.R.styleable.View_translationX: 2561 tx = a.getDimensionPixelOffset(attr, 0); 2562 transformSet = true; 2563 break; 2564 case com.android.internal.R.styleable.View_translationY: 2565 ty = a.getDimensionPixelOffset(attr, 0); 2566 transformSet = true; 2567 break; 2568 case com.android.internal.R.styleable.View_rotation: 2569 rotation = a.getFloat(attr, 0); 2570 transformSet = true; 2571 break; 2572 case com.android.internal.R.styleable.View_rotationX: 2573 rotationX = a.getFloat(attr, 0); 2574 transformSet = true; 2575 break; 2576 case com.android.internal.R.styleable.View_rotationY: 2577 rotationY = a.getFloat(attr, 0); 2578 transformSet = true; 2579 break; 2580 case com.android.internal.R.styleable.View_scaleX: 2581 sx = a.getFloat(attr, 1f); 2582 transformSet = true; 2583 break; 2584 case com.android.internal.R.styleable.View_scaleY: 2585 sy = a.getFloat(attr, 1f); 2586 transformSet = true; 2587 break; 2588 case com.android.internal.R.styleable.View_id: 2589 mID = a.getResourceId(attr, NO_ID); 2590 break; 2591 case com.android.internal.R.styleable.View_tag: 2592 mTag = a.getText(attr); 2593 break; 2594 case com.android.internal.R.styleable.View_fitsSystemWindows: 2595 if (a.getBoolean(attr, false)) { 2596 viewFlagValues |= FITS_SYSTEM_WINDOWS; 2597 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 2598 } 2599 break; 2600 case com.android.internal.R.styleable.View_focusable: 2601 if (a.getBoolean(attr, false)) { 2602 viewFlagValues |= FOCUSABLE; 2603 viewFlagMasks |= FOCUSABLE_MASK; 2604 } 2605 break; 2606 case com.android.internal.R.styleable.View_focusableInTouchMode: 2607 if (a.getBoolean(attr, false)) { 2608 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 2609 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 2610 } 2611 break; 2612 case com.android.internal.R.styleable.View_clickable: 2613 if (a.getBoolean(attr, false)) { 2614 viewFlagValues |= CLICKABLE; 2615 viewFlagMasks |= CLICKABLE; 2616 } 2617 break; 2618 case com.android.internal.R.styleable.View_longClickable: 2619 if (a.getBoolean(attr, false)) { 2620 viewFlagValues |= LONG_CLICKABLE; 2621 viewFlagMasks |= LONG_CLICKABLE; 2622 } 2623 break; 2624 case com.android.internal.R.styleable.View_saveEnabled: 2625 if (!a.getBoolean(attr, true)) { 2626 viewFlagValues |= SAVE_DISABLED; 2627 viewFlagMasks |= SAVE_DISABLED_MASK; 2628 } 2629 break; 2630 case com.android.internal.R.styleable.View_duplicateParentState: 2631 if (a.getBoolean(attr, false)) { 2632 viewFlagValues |= DUPLICATE_PARENT_STATE; 2633 viewFlagMasks |= DUPLICATE_PARENT_STATE; 2634 } 2635 break; 2636 case com.android.internal.R.styleable.View_visibility: 2637 final int visibility = a.getInt(attr, 0); 2638 if (visibility != 0) { 2639 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 2640 viewFlagMasks |= VISIBILITY_MASK; 2641 } 2642 break; 2643 case com.android.internal.R.styleable.View_horizontalDirection: 2644 final int layoutDirection = a.getInt(attr, 0); 2645 if (layoutDirection != 0) { 2646 viewFlagValues |= HORIZONTAL_DIRECTION_FLAGS[layoutDirection]; 2647 viewFlagMasks |= HORIZONTAL_DIRECTION_MASK; 2648 } 2649 break; 2650 case com.android.internal.R.styleable.View_drawingCacheQuality: 2651 final int cacheQuality = a.getInt(attr, 0); 2652 if (cacheQuality != 0) { 2653 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 2654 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 2655 } 2656 break; 2657 case com.android.internal.R.styleable.View_contentDescription: 2658 mContentDescription = a.getString(attr); 2659 break; 2660 case com.android.internal.R.styleable.View_soundEffectsEnabled: 2661 if (!a.getBoolean(attr, true)) { 2662 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 2663 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 2664 } 2665 break; 2666 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 2667 if (!a.getBoolean(attr, true)) { 2668 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 2669 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 2670 } 2671 break; 2672 case R.styleable.View_scrollbars: 2673 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 2674 if (scrollbars != SCROLLBARS_NONE) { 2675 viewFlagValues |= scrollbars; 2676 viewFlagMasks |= SCROLLBARS_MASK; 2677 initializeScrollbars(a); 2678 } 2679 break; 2680 case R.styleable.View_fadingEdge: 2681 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 2682 if (fadingEdge != FADING_EDGE_NONE) { 2683 viewFlagValues |= fadingEdge; 2684 viewFlagMasks |= FADING_EDGE_MASK; 2685 initializeFadingEdge(a); 2686 } 2687 break; 2688 case R.styleable.View_scrollbarStyle: 2689 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 2690 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 2691 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 2692 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 2693 } 2694 break; 2695 case R.styleable.View_isScrollContainer: 2696 setScrollContainer = true; 2697 if (a.getBoolean(attr, false)) { 2698 setScrollContainer(true); 2699 } 2700 break; 2701 case com.android.internal.R.styleable.View_keepScreenOn: 2702 if (a.getBoolean(attr, false)) { 2703 viewFlagValues |= KEEP_SCREEN_ON; 2704 viewFlagMasks |= KEEP_SCREEN_ON; 2705 } 2706 break; 2707 case R.styleable.View_filterTouchesWhenObscured: 2708 if (a.getBoolean(attr, false)) { 2709 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 2710 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 2711 } 2712 break; 2713 case R.styleable.View_nextFocusLeft: 2714 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 2715 break; 2716 case R.styleable.View_nextFocusRight: 2717 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 2718 break; 2719 case R.styleable.View_nextFocusUp: 2720 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 2721 break; 2722 case R.styleable.View_nextFocusDown: 2723 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 2724 break; 2725 case R.styleable.View_nextFocusForward: 2726 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 2727 break; 2728 case R.styleable.View_minWidth: 2729 mMinWidth = a.getDimensionPixelSize(attr, 0); 2730 break; 2731 case R.styleable.View_minHeight: 2732 mMinHeight = a.getDimensionPixelSize(attr, 0); 2733 break; 2734 case R.styleable.View_onClick: 2735 if (context.isRestricted()) { 2736 throw new IllegalStateException("The android:onClick attribute cannot " 2737 + "be used within a restricted context"); 2738 } 2739 2740 final String handlerName = a.getString(attr); 2741 if (handlerName != null) { 2742 setOnClickListener(new OnClickListener() { 2743 private Method mHandler; 2744 2745 public void onClick(View v) { 2746 if (mHandler == null) { 2747 try { 2748 mHandler = getContext().getClass().getMethod(handlerName, 2749 View.class); 2750 } catch (NoSuchMethodException e) { 2751 int id = getId(); 2752 String idText = id == NO_ID ? "" : " with id '" 2753 + getContext().getResources().getResourceEntryName( 2754 id) + "'"; 2755 throw new IllegalStateException("Could not find a method " + 2756 handlerName + "(View) in the activity " 2757 + getContext().getClass() + " for onClick handler" 2758 + " on view " + View.this.getClass() + idText, e); 2759 } 2760 } 2761 2762 try { 2763 mHandler.invoke(getContext(), View.this); 2764 } catch (IllegalAccessException e) { 2765 throw new IllegalStateException("Could not execute non " 2766 + "public method of the activity", e); 2767 } catch (InvocationTargetException e) { 2768 throw new IllegalStateException("Could not execute " 2769 + "method of the activity", e); 2770 } 2771 } 2772 }); 2773 } 2774 break; 2775 case R.styleable.View_overScrollMode: 2776 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 2777 break; 2778 case R.styleable.View_verticalScrollbarPosition: 2779 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 2780 break; 2781 case R.styleable.View_layerType: 2782 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 2783 break; 2784 } 2785 } 2786 2787 setOverScrollMode(overScrollMode); 2788 2789 if (background != null) { 2790 setBackgroundDrawable(background); 2791 } 2792 2793 if (padding >= 0) { 2794 leftPadding = padding; 2795 topPadding = padding; 2796 rightPadding = padding; 2797 bottomPadding = padding; 2798 } 2799 2800 // If the user specified the padding (either with android:padding or 2801 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise 2802 // use the default padding or the padding from the background drawable 2803 // (stored at this point in mPadding*) 2804 setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft, 2805 topPadding >= 0 ? topPadding : mPaddingTop, 2806 rightPadding >= 0 ? rightPadding : mPaddingRight, 2807 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 2808 2809 if (viewFlagMasks != 0) { 2810 setFlags(viewFlagValues, viewFlagMasks); 2811 } 2812 2813 // Needs to be called after mViewFlags is set 2814 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 2815 recomputePadding(); 2816 } 2817 2818 if (x != 0 || y != 0) { 2819 scrollTo(x, y); 2820 } 2821 2822 if (transformSet) { 2823 setTranslationX(tx); 2824 setTranslationY(ty); 2825 setRotation(rotation); 2826 setRotationX(rotationX); 2827 setRotationY(rotationY); 2828 setScaleX(sx); 2829 setScaleY(sy); 2830 } 2831 2832 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 2833 setScrollContainer(true); 2834 } 2835 2836 computeOpaqueFlags(); 2837 2838 a.recycle(); 2839 } 2840 2841 /** 2842 * Non-public constructor for use in testing 2843 */ 2844 View() { 2845 } 2846 2847 /** 2848 * <p> 2849 * Initializes the fading edges from a given set of styled attributes. This 2850 * method should be called by subclasses that need fading edges and when an 2851 * instance of these subclasses is created programmatically rather than 2852 * being inflated from XML. This method is automatically called when the XML 2853 * is inflated. 2854 * </p> 2855 * 2856 * @param a the styled attributes set to initialize the fading edges from 2857 */ 2858 protected void initializeFadingEdge(TypedArray a) { 2859 initScrollCache(); 2860 2861 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 2862 R.styleable.View_fadingEdgeLength, 2863 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 2864 } 2865 2866 /** 2867 * Returns the size of the vertical faded edges used to indicate that more 2868 * content in this view is visible. 2869 * 2870 * @return The size in pixels of the vertical faded edge or 0 if vertical 2871 * faded edges are not enabled for this view. 2872 * @attr ref android.R.styleable#View_fadingEdgeLength 2873 */ 2874 public int getVerticalFadingEdgeLength() { 2875 if (isVerticalFadingEdgeEnabled()) { 2876 ScrollabilityCache cache = mScrollCache; 2877 if (cache != null) { 2878 return cache.fadingEdgeLength; 2879 } 2880 } 2881 return 0; 2882 } 2883 2884 /** 2885 * Set the size of the faded edge used to indicate that more content in this 2886 * view is available. Will not change whether the fading edge is enabled; use 2887 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 2888 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 2889 * for the vertical or horizontal fading edges. 2890 * 2891 * @param length The size in pixels of the faded edge used to indicate that more 2892 * content in this view is visible. 2893 */ 2894 public void setFadingEdgeLength(int length) { 2895 initScrollCache(); 2896 mScrollCache.fadingEdgeLength = length; 2897 } 2898 2899 /** 2900 * Returns the size of the horizontal faded edges used to indicate that more 2901 * content in this view is visible. 2902 * 2903 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 2904 * faded edges are not enabled for this view. 2905 * @attr ref android.R.styleable#View_fadingEdgeLength 2906 */ 2907 public int getHorizontalFadingEdgeLength() { 2908 if (isHorizontalFadingEdgeEnabled()) { 2909 ScrollabilityCache cache = mScrollCache; 2910 if (cache != null) { 2911 return cache.fadingEdgeLength; 2912 } 2913 } 2914 return 0; 2915 } 2916 2917 /** 2918 * Returns the width of the vertical scrollbar. 2919 * 2920 * @return The width in pixels of the vertical scrollbar or 0 if there 2921 * is no vertical scrollbar. 2922 */ 2923 public int getVerticalScrollbarWidth() { 2924 ScrollabilityCache cache = mScrollCache; 2925 if (cache != null) { 2926 ScrollBarDrawable scrollBar = cache.scrollBar; 2927 if (scrollBar != null) { 2928 int size = scrollBar.getSize(true); 2929 if (size <= 0) { 2930 size = cache.scrollBarSize; 2931 } 2932 return size; 2933 } 2934 return 0; 2935 } 2936 return 0; 2937 } 2938 2939 /** 2940 * Returns the height of the horizontal scrollbar. 2941 * 2942 * @return The height in pixels of the horizontal scrollbar or 0 if 2943 * there is no horizontal scrollbar. 2944 */ 2945 protected int getHorizontalScrollbarHeight() { 2946 ScrollabilityCache cache = mScrollCache; 2947 if (cache != null) { 2948 ScrollBarDrawable scrollBar = cache.scrollBar; 2949 if (scrollBar != null) { 2950 int size = scrollBar.getSize(false); 2951 if (size <= 0) { 2952 size = cache.scrollBarSize; 2953 } 2954 return size; 2955 } 2956 return 0; 2957 } 2958 return 0; 2959 } 2960 2961 /** 2962 * <p> 2963 * Initializes the scrollbars from a given set of styled attributes. This 2964 * method should be called by subclasses that need scrollbars and when an 2965 * instance of these subclasses is created programmatically rather than 2966 * being inflated from XML. This method is automatically called when the XML 2967 * is inflated. 2968 * </p> 2969 * 2970 * @param a the styled attributes set to initialize the scrollbars from 2971 */ 2972 protected void initializeScrollbars(TypedArray a) { 2973 initScrollCache(); 2974 2975 final ScrollabilityCache scrollabilityCache = mScrollCache; 2976 2977 if (scrollabilityCache.scrollBar == null) { 2978 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 2979 } 2980 2981 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 2982 2983 if (!fadeScrollbars) { 2984 scrollabilityCache.state = ScrollabilityCache.ON; 2985 } 2986 scrollabilityCache.fadeScrollBars = fadeScrollbars; 2987 2988 2989 scrollabilityCache.scrollBarFadeDuration = a.getInt( 2990 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 2991 .getScrollBarFadeDuration()); 2992 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 2993 R.styleable.View_scrollbarDefaultDelayBeforeFade, 2994 ViewConfiguration.getScrollDefaultDelay()); 2995 2996 2997 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 2998 com.android.internal.R.styleable.View_scrollbarSize, 2999 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 3000 3001 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 3002 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 3003 3004 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 3005 if (thumb != null) { 3006 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 3007 } 3008 3009 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 3010 false); 3011 if (alwaysDraw) { 3012 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 3013 } 3014 3015 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 3016 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 3017 3018 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 3019 if (thumb != null) { 3020 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 3021 } 3022 3023 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 3024 false); 3025 if (alwaysDraw) { 3026 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 3027 } 3028 3029 // Re-apply user/background padding so that scrollbar(s) get added 3030 recomputePadding(); 3031 } 3032 3033 /** 3034 * <p> 3035 * Initalizes the scrollability cache if necessary. 3036 * </p> 3037 */ 3038 private void initScrollCache() { 3039 if (mScrollCache == null) { 3040 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 3041 } 3042 } 3043 3044 /** 3045 * Set the position of the vertical scroll bar. Should be one of 3046 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 3047 * {@link #SCROLLBAR_POSITION_RIGHT}. 3048 * 3049 * @param position Where the vertical scroll bar should be positioned. 3050 */ 3051 public void setVerticalScrollbarPosition(int position) { 3052 if (mVerticalScrollbarPosition != position) { 3053 mVerticalScrollbarPosition = position; 3054 computeOpaqueFlags(); 3055 recomputePadding(); 3056 } 3057 } 3058 3059 /** 3060 * @return The position where the vertical scroll bar will show, if applicable. 3061 * @see #setVerticalScrollbarPosition(int) 3062 */ 3063 public int getVerticalScrollbarPosition() { 3064 return mVerticalScrollbarPosition; 3065 } 3066 3067 /** 3068 * Register a callback to be invoked when focus of this view changed. 3069 * 3070 * @param l The callback that will run. 3071 */ 3072 public void setOnFocusChangeListener(OnFocusChangeListener l) { 3073 mOnFocusChangeListener = l; 3074 } 3075 3076 /** 3077 * Add a listener that will be called when the bounds of the view change due to 3078 * layout processing. 3079 * 3080 * @param listener The listener that will be called when layout bounds change. 3081 */ 3082 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 3083 if (mOnLayoutChangeListeners == null) { 3084 mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 3085 } 3086 mOnLayoutChangeListeners.add(listener); 3087 } 3088 3089 /** 3090 * Remove a listener for layout changes. 3091 * 3092 * @param listener The listener for layout bounds change. 3093 */ 3094 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 3095 if (mOnLayoutChangeListeners == null) { 3096 return; 3097 } 3098 mOnLayoutChangeListeners.remove(listener); 3099 } 3100 3101 /** 3102 * Add a listener for attach state changes. 3103 * 3104 * This listener will be called whenever this view is attached or detached 3105 * from a window. Remove the listener using 3106 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 3107 * 3108 * @param listener Listener to attach 3109 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 3110 */ 3111 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 3112 if (mOnAttachStateChangeListeners == null) { 3113 mOnAttachStateChangeListeners = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 3114 } 3115 mOnAttachStateChangeListeners.add(listener); 3116 } 3117 3118 /** 3119 * Remove a listener for attach state changes. The listener will receive no further 3120 * notification of window attach/detach events. 3121 * 3122 * @param listener Listener to remove 3123 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 3124 */ 3125 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 3126 if (mOnAttachStateChangeListeners == null) { 3127 return; 3128 } 3129 mOnAttachStateChangeListeners.remove(listener); 3130 } 3131 3132 /** 3133 * Returns the focus-change callback registered for this view. 3134 * 3135 * @return The callback, or null if one is not registered. 3136 */ 3137 public OnFocusChangeListener getOnFocusChangeListener() { 3138 return mOnFocusChangeListener; 3139 } 3140 3141 /** 3142 * Register a callback to be invoked when this view is clicked. If this view is not 3143 * clickable, it becomes clickable. 3144 * 3145 * @param l The callback that will run 3146 * 3147 * @see #setClickable(boolean) 3148 */ 3149 public void setOnClickListener(OnClickListener l) { 3150 if (!isClickable()) { 3151 setClickable(true); 3152 } 3153 mOnClickListener = l; 3154 } 3155 3156 /** 3157 * Register a callback to be invoked when this view is clicked and held. If this view is not 3158 * long clickable, it becomes long clickable. 3159 * 3160 * @param l The callback that will run 3161 * 3162 * @see #setLongClickable(boolean) 3163 */ 3164 public void setOnLongClickListener(OnLongClickListener l) { 3165 if (!isLongClickable()) { 3166 setLongClickable(true); 3167 } 3168 mOnLongClickListener = l; 3169 } 3170 3171 /** 3172 * Register a callback to be invoked when the context menu for this view is 3173 * being built. If this view is not long clickable, it becomes long clickable. 3174 * 3175 * @param l The callback that will run 3176 * 3177 */ 3178 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 3179 if (!isLongClickable()) { 3180 setLongClickable(true); 3181 } 3182 mOnCreateContextMenuListener = l; 3183 } 3184 3185 /** 3186 * Call this view's OnClickListener, if it is defined. 3187 * 3188 * @return True there was an assigned OnClickListener that was called, false 3189 * otherwise is returned. 3190 */ 3191 public boolean performClick() { 3192 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 3193 3194 if (mOnClickListener != null) { 3195 playSoundEffect(SoundEffectConstants.CLICK); 3196 mOnClickListener.onClick(this); 3197 return true; 3198 } 3199 3200 return false; 3201 } 3202 3203 /** 3204 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 3205 * OnLongClickListener did not consume the event. 3206 * 3207 * @return True if one of the above receivers consumed the event, false otherwise. 3208 */ 3209 public boolean performLongClick() { 3210 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 3211 3212 boolean handled = false; 3213 if (mOnLongClickListener != null) { 3214 handled = mOnLongClickListener.onLongClick(View.this); 3215 } 3216 if (!handled) { 3217 handled = showContextMenu(); 3218 } 3219 if (handled) { 3220 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 3221 } 3222 return handled; 3223 } 3224 3225 /** 3226 * Performs button-related actions during a touch down event. 3227 * 3228 * @param event The event. 3229 * @return True if the down was consumed. 3230 * 3231 * @hide 3232 */ 3233 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 3234 if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 3235 if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) { 3236 return true; 3237 } 3238 } 3239 return false; 3240 } 3241 3242 /** 3243 * Bring up the context menu for this view. 3244 * 3245 * @return Whether a context menu was displayed. 3246 */ 3247 public boolean showContextMenu() { 3248 return getParent().showContextMenuForChild(this); 3249 } 3250 3251 /** 3252 * Bring up the context menu for this view, referring to the item under the specified point. 3253 * 3254 * @param x The referenced x coordinate. 3255 * @param y The referenced y coordinate. 3256 * @param metaState The keyboard modifiers that were pressed. 3257 * @return Whether a context menu was displayed. 3258 * 3259 * @hide 3260 */ 3261 public boolean showContextMenu(float x, float y, int metaState) { 3262 return showContextMenu(); 3263 } 3264 3265 /** 3266 * Start an action mode. 3267 * 3268 * @param callback Callback that will control the lifecycle of the action mode 3269 * @return The new action mode if it is started, null otherwise 3270 * 3271 * @see ActionMode 3272 */ 3273 public ActionMode startActionMode(ActionMode.Callback callback) { 3274 return getParent().startActionModeForChild(this, callback); 3275 } 3276 3277 /** 3278 * Register a callback to be invoked when a key is pressed in this view. 3279 * @param l the key listener to attach to this view 3280 */ 3281 public void setOnKeyListener(OnKeyListener l) { 3282 mOnKeyListener = l; 3283 } 3284 3285 /** 3286 * Register a callback to be invoked when a touch event is sent to this view. 3287 * @param l the touch listener to attach to this view 3288 */ 3289 public void setOnTouchListener(OnTouchListener l) { 3290 mOnTouchListener = l; 3291 } 3292 3293 /** 3294 * Register a callback to be invoked when a generic motion event is sent to this view. 3295 * @param l the generic motion listener to attach to this view 3296 */ 3297 public void setOnGenericMotionListener(OnGenericMotionListener l) { 3298 mOnGenericMotionListener = l; 3299 } 3300 3301 /** 3302 * Register a drag event listener callback object for this View. The parameter is 3303 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 3304 * View, the system calls the 3305 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 3306 * @param l An implementation of {@link android.view.View.OnDragListener}. 3307 */ 3308 public void setOnDragListener(OnDragListener l) { 3309 mOnDragListener = l; 3310 } 3311 3312 /** 3313 * Give this view focus. This will cause 3314 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 3315 * 3316 * Note: this does not check whether this {@link View} should get focus, it just 3317 * gives it focus no matter what. It should only be called internally by framework 3318 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 3319 * 3320 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 3321 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 3322 * focus moved when requestFocus() is called. It may not always 3323 * apply, in which case use the default View.FOCUS_DOWN. 3324 * @param previouslyFocusedRect The rectangle of the view that had focus 3325 * prior in this View's coordinate system. 3326 */ 3327 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) { 3328 if (DBG) { 3329 System.out.println(this + " requestFocus()"); 3330 } 3331 3332 if ((mPrivateFlags & FOCUSED) == 0) { 3333 mPrivateFlags |= FOCUSED; 3334 3335 if (mParent != null) { 3336 mParent.requestChildFocus(this, this); 3337 } 3338 3339 onFocusChanged(true, direction, previouslyFocusedRect); 3340 refreshDrawableState(); 3341 } 3342 } 3343 3344 /** 3345 * Request that a rectangle of this view be visible on the screen, 3346 * scrolling if necessary just enough. 3347 * 3348 * <p>A View should call this if it maintains some notion of which part 3349 * of its content is interesting. For example, a text editing view 3350 * should call this when its cursor moves. 3351 * 3352 * @param rectangle The rectangle. 3353 * @return Whether any parent scrolled. 3354 */ 3355 public boolean requestRectangleOnScreen(Rect rectangle) { 3356 return requestRectangleOnScreen(rectangle, false); 3357 } 3358 3359 /** 3360 * Request that a rectangle of this view be visible on the screen, 3361 * scrolling if necessary just enough. 3362 * 3363 * <p>A View should call this if it maintains some notion of which part 3364 * of its content is interesting. For example, a text editing view 3365 * should call this when its cursor moves. 3366 * 3367 * <p>When <code>immediate</code> is set to true, scrolling will not be 3368 * animated. 3369 * 3370 * @param rectangle The rectangle. 3371 * @param immediate True to forbid animated scrolling, false otherwise 3372 * @return Whether any parent scrolled. 3373 */ 3374 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 3375 View child = this; 3376 ViewParent parent = mParent; 3377 boolean scrolled = false; 3378 while (parent != null) { 3379 scrolled |= parent.requestChildRectangleOnScreen(child, 3380 rectangle, immediate); 3381 3382 // offset rect so next call has the rectangle in the 3383 // coordinate system of its direct child. 3384 rectangle.offset(child.getLeft(), child.getTop()); 3385 rectangle.offset(-child.getScrollX(), -child.getScrollY()); 3386 3387 if (!(parent instanceof View)) { 3388 break; 3389 } 3390 3391 child = (View) parent; 3392 parent = child.getParent(); 3393 } 3394 return scrolled; 3395 } 3396 3397 /** 3398 * Called when this view wants to give up focus. This will cause 3399 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 3400 */ 3401 public void clearFocus() { 3402 if (DBG) { 3403 System.out.println(this + " clearFocus()"); 3404 } 3405 3406 if ((mPrivateFlags & FOCUSED) != 0) { 3407 mPrivateFlags &= ~FOCUSED; 3408 3409 if (mParent != null) { 3410 mParent.clearChildFocus(this); 3411 } 3412 3413 onFocusChanged(false, 0, null); 3414 refreshDrawableState(); 3415 } 3416 } 3417 3418 /** 3419 * Called to clear the focus of a view that is about to be removed. 3420 * Doesn't call clearChildFocus, which prevents this view from taking 3421 * focus again before it has been removed from the parent 3422 */ 3423 void clearFocusForRemoval() { 3424 if ((mPrivateFlags & FOCUSED) != 0) { 3425 mPrivateFlags &= ~FOCUSED; 3426 3427 onFocusChanged(false, 0, null); 3428 refreshDrawableState(); 3429 } 3430 } 3431 3432 /** 3433 * Called internally by the view system when a new view is getting focus. 3434 * This is what clears the old focus. 3435 */ 3436 void unFocus() { 3437 if (DBG) { 3438 System.out.println(this + " unFocus()"); 3439 } 3440 3441 if ((mPrivateFlags & FOCUSED) != 0) { 3442 mPrivateFlags &= ~FOCUSED; 3443 3444 onFocusChanged(false, 0, null); 3445 refreshDrawableState(); 3446 } 3447 } 3448 3449 /** 3450 * Returns true if this view has focus iteself, or is the ancestor of the 3451 * view that has focus. 3452 * 3453 * @return True if this view has or contains focus, false otherwise. 3454 */ 3455 @ViewDebug.ExportedProperty(category = "focus") 3456 public boolean hasFocus() { 3457 return (mPrivateFlags & FOCUSED) != 0; 3458 } 3459 3460 /** 3461 * Returns true if this view is focusable or if it contains a reachable View 3462 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 3463 * is a View whose parents do not block descendants focus. 3464 * 3465 * Only {@link #VISIBLE} views are considered focusable. 3466 * 3467 * @return True if the view is focusable or if the view contains a focusable 3468 * View, false otherwise. 3469 * 3470 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 3471 */ 3472 public boolean hasFocusable() { 3473 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 3474 } 3475 3476 /** 3477 * Called by the view system when the focus state of this view changes. 3478 * When the focus change event is caused by directional navigation, direction 3479 * and previouslyFocusedRect provide insight into where the focus is coming from. 3480 * When overriding, be sure to call up through to the super class so that 3481 * the standard focus handling will occur. 3482 * 3483 * @param gainFocus True if the View has focus; false otherwise. 3484 * @param direction The direction focus has moved when requestFocus() 3485 * is called to give this view focus. Values are 3486 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 3487 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 3488 * It may not always apply, in which case use the default. 3489 * @param previouslyFocusedRect The rectangle, in this view's coordinate 3490 * system, of the previously focused view. If applicable, this will be 3491 * passed in as finer grained information about where the focus is coming 3492 * from (in addition to direction). Will be <code>null</code> otherwise. 3493 */ 3494 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) { 3495 if (gainFocus) { 3496 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 3497 } 3498 3499 InputMethodManager imm = InputMethodManager.peekInstance(); 3500 if (!gainFocus) { 3501 if (isPressed()) { 3502 setPressed(false); 3503 } 3504 if (imm != null && mAttachInfo != null 3505 && mAttachInfo.mHasWindowFocus) { 3506 imm.focusOut(this); 3507 } 3508 onFocusLost(); 3509 } else if (imm != null && mAttachInfo != null 3510 && mAttachInfo.mHasWindowFocus) { 3511 imm.focusIn(this); 3512 } 3513 3514 invalidate(true); 3515 if (mOnFocusChangeListener != null) { 3516 mOnFocusChangeListener.onFocusChange(this, gainFocus); 3517 } 3518 3519 if (mAttachInfo != null) { 3520 mAttachInfo.mKeyDispatchState.reset(this); 3521 } 3522 } 3523 3524 /** 3525 * Sends an accessibility event of the given type. If accessiiblity is 3526 * not enabled this method has no effect. The default implementation calls 3527 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 3528 * to populate information about the event source (this View), then calls 3529 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 3530 * populate the text content of the event source including its descendants, 3531 * and last calls 3532 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 3533 * on its parent to resuest sending of the event to interested parties. 3534 * 3535 * @param eventType The type of the event to send. 3536 * 3537 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 3538 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 3539 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 3540 */ 3541 public void sendAccessibilityEvent(int eventType) { 3542 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 3543 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 3544 } 3545 } 3546 3547 /** 3548 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 3549 * takes as an argument an empty {@link AccessibilityEvent} and does not 3550 * perfrom a check whether accessibility is enabled. 3551 * 3552 * @param event The event to send. 3553 * 3554 * @see #sendAccessibilityEvent(int) 3555 */ 3556 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 3557 if (!isShown()) { 3558 return; 3559 } 3560 onInitializeAccessibilityEvent(event); 3561 dispatchPopulateAccessibilityEvent(event); 3562 // In the beginning we called #isShown(), so we know that getParent() is not null. 3563 getParent().requestSendAccessibilityEvent(this, event); 3564 } 3565 3566 /** 3567 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 3568 * to its children for adding their text content to the event. Note that the 3569 * event text is populated in a separate dispatch path since we add to the 3570 * event not only the text of the source but also the text of all its descendants. 3571 * </p> 3572 * A typical implementation will call 3573 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 3574 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 3575 * on each child. Override this method if custom population of the event text 3576 * content is required. 3577 * 3578 * @param event The event. 3579 * 3580 * @return True if the event population was completed. 3581 */ 3582 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 3583 onPopulateAccessibilityEvent(event); 3584 return false; 3585 } 3586 3587 /** 3588 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 3589 * giving a chance to this View to populate the accessibility event with its 3590 * text content. While the implementation is free to modify other event 3591 * attributes this should be performed in 3592 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 3593 * <p> 3594 * Example: Adding formatted date string to an accessibility event in addition 3595 * to the text added by the super implementation. 3596 * </p><p><pre><code> 3597 * public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 3598 * super.onPopulateAccessibilityEvent(event); 3599 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 3600 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 3601 * mCurrentDate.getTimeInMillis(), flags); 3602 * event.getText().add(selectedDateUtterance); 3603 * } 3604 * </code></pre></p> 3605 * 3606 * @param event The accessibility event which to populate. 3607 * 3608 * @see #sendAccessibilityEvent(int) 3609 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 3610 */ 3611 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 3612 3613 } 3614 3615 /** 3616 * Initializes an {@link AccessibilityEvent} with information about the 3617 * the type of the event and this View which is the event source. In other 3618 * words, the source of an accessibility event is the view whose state 3619 * change triggered firing the event. 3620 * <p> 3621 * Example: Setting the password property of an event in addition 3622 * to properties set by the super implementation. 3623 * </p><p><pre><code> 3624 * public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 3625 * super.onInitializeAccessibilityEvent(event); 3626 * event.setPassword(true); 3627 * } 3628 * </code></pre></p> 3629 * @param event The event to initialeze. 3630 * 3631 * @see #sendAccessibilityEvent(int) 3632 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 3633 */ 3634 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 3635 event.setClassName(getClass().getName()); 3636 event.setPackageName(getContext().getPackageName()); 3637 event.setEnabled(isEnabled()); 3638 event.setContentDescription(mContentDescription); 3639 3640 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) { 3641 ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList; 3642 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL); 3643 event.setItemCount(focusablesTempList.size()); 3644 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 3645 focusablesTempList.clear(); 3646 } 3647 } 3648 3649 /** 3650 * Gets the {@link View} description. It briefly describes the view and is 3651 * primarily used for accessibility support. Set this property to enable 3652 * better accessibility support for your application. This is especially 3653 * true for views that do not have textual representation (For example, 3654 * ImageButton). 3655 * 3656 * @return The content descriptiopn. 3657 * 3658 * @attr ref android.R.styleable#View_contentDescription 3659 */ 3660 public CharSequence getContentDescription() { 3661 return mContentDescription; 3662 } 3663 3664 /** 3665 * Sets the {@link View} description. It briefly describes the view and is 3666 * primarily used for accessibility support. Set this property to enable 3667 * better accessibility support for your application. This is especially 3668 * true for views that do not have textual representation (For example, 3669 * ImageButton). 3670 * 3671 * @param contentDescription The content description. 3672 * 3673 * @attr ref android.R.styleable#View_contentDescription 3674 */ 3675 public void setContentDescription(CharSequence contentDescription) { 3676 mContentDescription = contentDescription; 3677 } 3678 3679 /** 3680 * Invoked whenever this view loses focus, either by losing window focus or by losing 3681 * focus within its window. This method can be used to clear any state tied to the 3682 * focus. For instance, if a button is held pressed with the trackball and the window 3683 * loses focus, this method can be used to cancel the press. 3684 * 3685 * Subclasses of View overriding this method should always call super.onFocusLost(). 3686 * 3687 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 3688 * @see #onWindowFocusChanged(boolean) 3689 * 3690 * @hide pending API council approval 3691 */ 3692 protected void onFocusLost() { 3693 resetPressedState(); 3694 } 3695 3696 private void resetPressedState() { 3697 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 3698 return; 3699 } 3700 3701 if (isPressed()) { 3702 setPressed(false); 3703 3704 if (!mHasPerformedLongPress) { 3705 removeLongPressCallback(); 3706 } 3707 } 3708 } 3709 3710 /** 3711 * Returns true if this view has focus 3712 * 3713 * @return True if this view has focus, false otherwise. 3714 */ 3715 @ViewDebug.ExportedProperty(category = "focus") 3716 public boolean isFocused() { 3717 return (mPrivateFlags & FOCUSED) != 0; 3718 } 3719 3720 /** 3721 * Find the view in the hierarchy rooted at this view that currently has 3722 * focus. 3723 * 3724 * @return The view that currently has focus, or null if no focused view can 3725 * be found. 3726 */ 3727 public View findFocus() { 3728 return (mPrivateFlags & FOCUSED) != 0 ? this : null; 3729 } 3730 3731 /** 3732 * Change whether this view is one of the set of scrollable containers in 3733 * its window. This will be used to determine whether the window can 3734 * resize or must pan when a soft input area is open -- scrollable 3735 * containers allow the window to use resize mode since the container 3736 * will appropriately shrink. 3737 */ 3738 public void setScrollContainer(boolean isScrollContainer) { 3739 if (isScrollContainer) { 3740 if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) { 3741 mAttachInfo.mScrollContainers.add(this); 3742 mPrivateFlags |= SCROLL_CONTAINER_ADDED; 3743 } 3744 mPrivateFlags |= SCROLL_CONTAINER; 3745 } else { 3746 if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) { 3747 mAttachInfo.mScrollContainers.remove(this); 3748 } 3749 mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED); 3750 } 3751 } 3752 3753 /** 3754 * Returns the quality of the drawing cache. 3755 * 3756 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 3757 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 3758 * 3759 * @see #setDrawingCacheQuality(int) 3760 * @see #setDrawingCacheEnabled(boolean) 3761 * @see #isDrawingCacheEnabled() 3762 * 3763 * @attr ref android.R.styleable#View_drawingCacheQuality 3764 */ 3765 public int getDrawingCacheQuality() { 3766 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 3767 } 3768 3769 /** 3770 * Set the drawing cache quality of this view. This value is used only when the 3771 * drawing cache is enabled 3772 * 3773 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 3774 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 3775 * 3776 * @see #getDrawingCacheQuality() 3777 * @see #setDrawingCacheEnabled(boolean) 3778 * @see #isDrawingCacheEnabled() 3779 * 3780 * @attr ref android.R.styleable#View_drawingCacheQuality 3781 */ 3782 public void setDrawingCacheQuality(int quality) { 3783 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 3784 } 3785 3786 /** 3787 * Returns whether the screen should remain on, corresponding to the current 3788 * value of {@link #KEEP_SCREEN_ON}. 3789 * 3790 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 3791 * 3792 * @see #setKeepScreenOn(boolean) 3793 * 3794 * @attr ref android.R.styleable#View_keepScreenOn 3795 */ 3796 public boolean getKeepScreenOn() { 3797 return (mViewFlags & KEEP_SCREEN_ON) != 0; 3798 } 3799 3800 /** 3801 * Controls whether the screen should remain on, modifying the 3802 * value of {@link #KEEP_SCREEN_ON}. 3803 * 3804 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 3805 * 3806 * @see #getKeepScreenOn() 3807 * 3808 * @attr ref android.R.styleable#View_keepScreenOn 3809 */ 3810 public void setKeepScreenOn(boolean keepScreenOn) { 3811 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 3812 } 3813 3814 /** 3815 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 3816 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 3817 * 3818 * @attr ref android.R.styleable#View_nextFocusLeft 3819 */ 3820 public int getNextFocusLeftId() { 3821 return mNextFocusLeftId; 3822 } 3823 3824 /** 3825 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 3826 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 3827 * decide automatically. 3828 * 3829 * @attr ref android.R.styleable#View_nextFocusLeft 3830 */ 3831 public void setNextFocusLeftId(int nextFocusLeftId) { 3832 mNextFocusLeftId = nextFocusLeftId; 3833 } 3834 3835 /** 3836 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 3837 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 3838 * 3839 * @attr ref android.R.styleable#View_nextFocusRight 3840 */ 3841 public int getNextFocusRightId() { 3842 return mNextFocusRightId; 3843 } 3844 3845 /** 3846 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 3847 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 3848 * decide automatically. 3849 * 3850 * @attr ref android.R.styleable#View_nextFocusRight 3851 */ 3852 public void setNextFocusRightId(int nextFocusRightId) { 3853 mNextFocusRightId = nextFocusRightId; 3854 } 3855 3856 /** 3857 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 3858 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 3859 * 3860 * @attr ref android.R.styleable#View_nextFocusUp 3861 */ 3862 public int getNextFocusUpId() { 3863 return mNextFocusUpId; 3864 } 3865 3866 /** 3867 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 3868 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 3869 * decide automatically. 3870 * 3871 * @attr ref android.R.styleable#View_nextFocusUp 3872 */ 3873 public void setNextFocusUpId(int nextFocusUpId) { 3874 mNextFocusUpId = nextFocusUpId; 3875 } 3876 3877 /** 3878 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 3879 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 3880 * 3881 * @attr ref android.R.styleable#View_nextFocusDown 3882 */ 3883 public int getNextFocusDownId() { 3884 return mNextFocusDownId; 3885 } 3886 3887 /** 3888 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 3889 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 3890 * decide automatically. 3891 * 3892 * @attr ref android.R.styleable#View_nextFocusDown 3893 */ 3894 public void setNextFocusDownId(int nextFocusDownId) { 3895 mNextFocusDownId = nextFocusDownId; 3896 } 3897 3898 /** 3899 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 3900 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 3901 * 3902 * @attr ref android.R.styleable#View_nextFocusForward 3903 */ 3904 public int getNextFocusForwardId() { 3905 return mNextFocusForwardId; 3906 } 3907 3908 /** 3909 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 3910 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 3911 * decide automatically. 3912 * 3913 * @attr ref android.R.styleable#View_nextFocusForward 3914 */ 3915 public void setNextFocusForwardId(int nextFocusForwardId) { 3916 mNextFocusForwardId = nextFocusForwardId; 3917 } 3918 3919 /** 3920 * Returns the visibility of this view and all of its ancestors 3921 * 3922 * @return True if this view and all of its ancestors are {@link #VISIBLE} 3923 */ 3924 public boolean isShown() { 3925 View current = this; 3926 //noinspection ConstantConditions 3927 do { 3928 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 3929 return false; 3930 } 3931 ViewParent parent = current.mParent; 3932 if (parent == null) { 3933 return false; // We are not attached to the view root 3934 } 3935 if (!(parent instanceof View)) { 3936 return true; 3937 } 3938 current = (View) parent; 3939 } while (current != null); 3940 3941 return false; 3942 } 3943 3944 /** 3945 * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag 3946 * is set 3947 * 3948 * @param insets Insets for system windows 3949 * 3950 * @return True if this view applied the insets, false otherwise 3951 */ 3952 protected boolean fitSystemWindows(Rect insets) { 3953 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 3954 mPaddingLeft = insets.left; 3955 mPaddingTop = insets.top; 3956 mPaddingRight = insets.right; 3957 mPaddingBottom = insets.bottom; 3958 requestLayout(); 3959 return true; 3960 } 3961 return false; 3962 } 3963 3964 /** 3965 * Returns the visibility status for this view. 3966 * 3967 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 3968 * @attr ref android.R.styleable#View_visibility 3969 */ 3970 @ViewDebug.ExportedProperty(mapping = { 3971 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 3972 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 3973 @ViewDebug.IntToString(from = GONE, to = "GONE") 3974 }) 3975 public int getVisibility() { 3976 return mViewFlags & VISIBILITY_MASK; 3977 } 3978 3979 /** 3980 * Set the enabled state of this view. 3981 * 3982 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 3983 * @attr ref android.R.styleable#View_visibility 3984 */ 3985 @RemotableViewMethod 3986 public void setVisibility(int visibility) { 3987 setFlags(visibility, VISIBILITY_MASK); 3988 if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false); 3989 } 3990 3991 /** 3992 * Returns the enabled status for this view. The interpretation of the 3993 * enabled state varies by subclass. 3994 * 3995 * @return True if this view is enabled, false otherwise. 3996 */ 3997 @ViewDebug.ExportedProperty 3998 public boolean isEnabled() { 3999 return (mViewFlags & ENABLED_MASK) == ENABLED; 4000 } 4001 4002 /** 4003 * Set the enabled state of this view. The interpretation of the enabled 4004 * state varies by subclass. 4005 * 4006 * @param enabled True if this view is enabled, false otherwise. 4007 */ 4008 @RemotableViewMethod 4009 public void setEnabled(boolean enabled) { 4010 if (enabled == isEnabled()) return; 4011 4012 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 4013 4014 /* 4015 * The View most likely has to change its appearance, so refresh 4016 * the drawable state. 4017 */ 4018 refreshDrawableState(); 4019 4020 // Invalidate too, since the default behavior for views is to be 4021 // be drawn at 50% alpha rather than to change the drawable. 4022 invalidate(true); 4023 } 4024 4025 /** 4026 * Set whether this view can receive the focus. 4027 * 4028 * Setting this to false will also ensure that this view is not focusable 4029 * in touch mode. 4030 * 4031 * @param focusable If true, this view can receive the focus. 4032 * 4033 * @see #setFocusableInTouchMode(boolean) 4034 * @attr ref android.R.styleable#View_focusable 4035 */ 4036 public void setFocusable(boolean focusable) { 4037 if (!focusable) { 4038 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 4039 } 4040 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 4041 } 4042 4043 /** 4044 * Set whether this view can receive focus while in touch mode. 4045 * 4046 * Setting this to true will also ensure that this view is focusable. 4047 * 4048 * @param focusableInTouchMode If true, this view can receive the focus while 4049 * in touch mode. 4050 * 4051 * @see #setFocusable(boolean) 4052 * @attr ref android.R.styleable#View_focusableInTouchMode 4053 */ 4054 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 4055 // Focusable in touch mode should always be set before the focusable flag 4056 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 4057 // which, in touch mode, will not successfully request focus on this view 4058 // because the focusable in touch mode flag is not set 4059 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 4060 if (focusableInTouchMode) { 4061 setFlags(FOCUSABLE, FOCUSABLE_MASK); 4062 } 4063 } 4064 4065 /** 4066 * Set whether this view should have sound effects enabled for events such as 4067 * clicking and touching. 4068 * 4069 * <p>You may wish to disable sound effects for a view if you already play sounds, 4070 * for instance, a dial key that plays dtmf tones. 4071 * 4072 * @param soundEffectsEnabled whether sound effects are enabled for this view. 4073 * @see #isSoundEffectsEnabled() 4074 * @see #playSoundEffect(int) 4075 * @attr ref android.R.styleable#View_soundEffectsEnabled 4076 */ 4077 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 4078 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 4079 } 4080 4081 /** 4082 * @return whether this view should have sound effects enabled for events such as 4083 * clicking and touching. 4084 * 4085 * @see #setSoundEffectsEnabled(boolean) 4086 * @see #playSoundEffect(int) 4087 * @attr ref android.R.styleable#View_soundEffectsEnabled 4088 */ 4089 @ViewDebug.ExportedProperty 4090 public boolean isSoundEffectsEnabled() { 4091 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 4092 } 4093 4094 /** 4095 * Set whether this view should have haptic feedback for events such as 4096 * long presses. 4097 * 4098 * <p>You may wish to disable haptic feedback if your view already controls 4099 * its own haptic feedback. 4100 * 4101 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 4102 * @see #isHapticFeedbackEnabled() 4103 * @see #performHapticFeedback(int) 4104 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 4105 */ 4106 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 4107 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 4108 } 4109 4110 /** 4111 * @return whether this view should have haptic feedback enabled for events 4112 * long presses. 4113 * 4114 * @see #setHapticFeedbackEnabled(boolean) 4115 * @see #performHapticFeedback(int) 4116 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 4117 */ 4118 @ViewDebug.ExportedProperty 4119 public boolean isHapticFeedbackEnabled() { 4120 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 4121 } 4122 4123 /** 4124 * Returns the horizontal direction for this view. 4125 * 4126 * @return One of {@link #HORIZONTAL_DIRECTION_LTR}, 4127 * {@link #HORIZONTAL_DIRECTION_RTL}, 4128 * {@link #HORIZONTAL_DIRECTION_INHERIT} or 4129 * {@link #HORIZONTAL_DIRECTION_LOCALE}. 4130 * @attr ref android.R.styleable#View_horizontalDirection 4131 * @hide 4132 */ 4133 @ViewDebug.ExportedProperty(mapping = { 4134 @ViewDebug.IntToString(from = HORIZONTAL_DIRECTION_LTR, to = "LTR"), 4135 @ViewDebug.IntToString(from = HORIZONTAL_DIRECTION_RTL, to = "RTL"), 4136 @ViewDebug.IntToString(from = HORIZONTAL_DIRECTION_INHERIT, to = "INHERIT"), 4137 @ViewDebug.IntToString(from = HORIZONTAL_DIRECTION_LOCALE, to = "LOCALE") 4138 }) 4139 public int getHorizontalDirection() { 4140 return mViewFlags & HORIZONTAL_DIRECTION_MASK; 4141 } 4142 4143 /** 4144 * Set the horizontal direction for this view. 4145 * 4146 * @param horizontalDirection One of {@link #HORIZONTAL_DIRECTION_LTR}, 4147 * {@link #HORIZONTAL_DIRECTION_RTL}, 4148 * {@link #HORIZONTAL_DIRECTION_INHERIT} or 4149 * {@link #HORIZONTAL_DIRECTION_LOCALE}. 4150 * @attr ref android.R.styleable#View_horizontalDirection 4151 * @hide 4152 */ 4153 @RemotableViewMethod 4154 public void setHorizontalDirection(int horizontalDirection) { 4155 setFlags(horizontalDirection, HORIZONTAL_DIRECTION_MASK); 4156 } 4157 4158 /** 4159 * If this view doesn't do any drawing on its own, set this flag to 4160 * allow further optimizations. By default, this flag is not set on 4161 * View, but could be set on some View subclasses such as ViewGroup. 4162 * 4163 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 4164 * you should clear this flag. 4165 * 4166 * @param willNotDraw whether or not this View draw on its own 4167 */ 4168 public void setWillNotDraw(boolean willNotDraw) { 4169 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 4170 } 4171 4172 /** 4173 * Returns whether or not this View draws on its own. 4174 * 4175 * @return true if this view has nothing to draw, false otherwise 4176 */ 4177 @ViewDebug.ExportedProperty(category = "drawing") 4178 public boolean willNotDraw() { 4179 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 4180 } 4181 4182 /** 4183 * When a View's drawing cache is enabled, drawing is redirected to an 4184 * offscreen bitmap. Some views, like an ImageView, must be able to 4185 * bypass this mechanism if they already draw a single bitmap, to avoid 4186 * unnecessary usage of the memory. 4187 * 4188 * @param willNotCacheDrawing true if this view does not cache its 4189 * drawing, false otherwise 4190 */ 4191 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 4192 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 4193 } 4194 4195 /** 4196 * Returns whether or not this View can cache its drawing or not. 4197 * 4198 * @return true if this view does not cache its drawing, false otherwise 4199 */ 4200 @ViewDebug.ExportedProperty(category = "drawing") 4201 public boolean willNotCacheDrawing() { 4202 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 4203 } 4204 4205 /** 4206 * Indicates whether this view reacts to click events or not. 4207 * 4208 * @return true if the view is clickable, false otherwise 4209 * 4210 * @see #setClickable(boolean) 4211 * @attr ref android.R.styleable#View_clickable 4212 */ 4213 @ViewDebug.ExportedProperty 4214 public boolean isClickable() { 4215 return (mViewFlags & CLICKABLE) == CLICKABLE; 4216 } 4217 4218 /** 4219 * Enables or disables click events for this view. When a view 4220 * is clickable it will change its state to "pressed" on every click. 4221 * Subclasses should set the view clickable to visually react to 4222 * user's clicks. 4223 * 4224 * @param clickable true to make the view clickable, false otherwise 4225 * 4226 * @see #isClickable() 4227 * @attr ref android.R.styleable#View_clickable 4228 */ 4229 public void setClickable(boolean clickable) { 4230 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 4231 } 4232 4233 /** 4234 * Indicates whether this view reacts to long click events or not. 4235 * 4236 * @return true if the view is long clickable, false otherwise 4237 * 4238 * @see #setLongClickable(boolean) 4239 * @attr ref android.R.styleable#View_longClickable 4240 */ 4241 public boolean isLongClickable() { 4242 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 4243 } 4244 4245 /** 4246 * Enables or disables long click events for this view. When a view is long 4247 * clickable it reacts to the user holding down the button for a longer 4248 * duration than a tap. This event can either launch the listener or a 4249 * context menu. 4250 * 4251 * @param longClickable true to make the view long clickable, false otherwise 4252 * @see #isLongClickable() 4253 * @attr ref android.R.styleable#View_longClickable 4254 */ 4255 public void setLongClickable(boolean longClickable) { 4256 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 4257 } 4258 4259 /** 4260 * Sets the pressed state for this view. 4261 * 4262 * @see #isClickable() 4263 * @see #setClickable(boolean) 4264 * 4265 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 4266 * the View's internal state from a previously set "pressed" state. 4267 */ 4268 public void setPressed(boolean pressed) { 4269 if (pressed) { 4270 mPrivateFlags |= PRESSED; 4271 } else { 4272 mPrivateFlags &= ~PRESSED; 4273 } 4274 refreshDrawableState(); 4275 dispatchSetPressed(pressed); 4276 } 4277 4278 /** 4279 * Dispatch setPressed to all of this View's children. 4280 * 4281 * @see #setPressed(boolean) 4282 * 4283 * @param pressed The new pressed state 4284 */ 4285 protected void dispatchSetPressed(boolean pressed) { 4286 } 4287 4288 /** 4289 * Indicates whether the view is currently in pressed state. Unless 4290 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 4291 * the pressed state. 4292 * 4293 * @see #setPressed(boolean) 4294 * @see #isClickable() 4295 * @see #setClickable(boolean) 4296 * 4297 * @return true if the view is currently pressed, false otherwise 4298 */ 4299 public boolean isPressed() { 4300 return (mPrivateFlags & PRESSED) == PRESSED; 4301 } 4302 4303 /** 4304 * Indicates whether this view will save its state (that is, 4305 * whether its {@link #onSaveInstanceState} method will be called). 4306 * 4307 * @return Returns true if the view state saving is enabled, else false. 4308 * 4309 * @see #setSaveEnabled(boolean) 4310 * @attr ref android.R.styleable#View_saveEnabled 4311 */ 4312 public boolean isSaveEnabled() { 4313 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 4314 } 4315 4316 /** 4317 * Controls whether the saving of this view's state is 4318 * enabled (that is, whether its {@link #onSaveInstanceState} method 4319 * will be called). Note that even if freezing is enabled, the 4320 * view still must have an id assigned to it (via {@link #setId(int)}) 4321 * for its state to be saved. This flag can only disable the 4322 * saving of this view; any child views may still have their state saved. 4323 * 4324 * @param enabled Set to false to <em>disable</em> state saving, or true 4325 * (the default) to allow it. 4326 * 4327 * @see #isSaveEnabled() 4328 * @see #setId(int) 4329 * @see #onSaveInstanceState() 4330 * @attr ref android.R.styleable#View_saveEnabled 4331 */ 4332 public void setSaveEnabled(boolean enabled) { 4333 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 4334 } 4335 4336 /** 4337 * Gets whether the framework should discard touches when the view's 4338 * window is obscured by another visible window. 4339 * Refer to the {@link View} security documentation for more details. 4340 * 4341 * @return True if touch filtering is enabled. 4342 * 4343 * @see #setFilterTouchesWhenObscured(boolean) 4344 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 4345 */ 4346 @ViewDebug.ExportedProperty 4347 public boolean getFilterTouchesWhenObscured() { 4348 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 4349 } 4350 4351 /** 4352 * Sets whether the framework should discard touches when the view's 4353 * window is obscured by another visible window. 4354 * Refer to the {@link View} security documentation for more details. 4355 * 4356 * @param enabled True if touch filtering should be enabled. 4357 * 4358 * @see #getFilterTouchesWhenObscured 4359 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 4360 */ 4361 public void setFilterTouchesWhenObscured(boolean enabled) { 4362 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED, 4363 FILTER_TOUCHES_WHEN_OBSCURED); 4364 } 4365 4366 /** 4367 * Indicates whether the entire hierarchy under this view will save its 4368 * state when a state saving traversal occurs from its parent. The default 4369 * is true; if false, these views will not be saved unless 4370 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 4371 * 4372 * @return Returns true if the view state saving from parent is enabled, else false. 4373 * 4374 * @see #setSaveFromParentEnabled(boolean) 4375 */ 4376 public boolean isSaveFromParentEnabled() { 4377 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 4378 } 4379 4380 /** 4381 * Controls whether the entire hierarchy under this view will save its 4382 * state when a state saving traversal occurs from its parent. The default 4383 * is true; if false, these views will not be saved unless 4384 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 4385 * 4386 * @param enabled Set to false to <em>disable</em> state saving, or true 4387 * (the default) to allow it. 4388 * 4389 * @see #isSaveFromParentEnabled() 4390 * @see #setId(int) 4391 * @see #onSaveInstanceState() 4392 */ 4393 public void setSaveFromParentEnabled(boolean enabled) { 4394 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 4395 } 4396 4397 4398 /** 4399 * Returns whether this View is able to take focus. 4400 * 4401 * @return True if this view can take focus, or false otherwise. 4402 * @attr ref android.R.styleable#View_focusable 4403 */ 4404 @ViewDebug.ExportedProperty(category = "focus") 4405 public final boolean isFocusable() { 4406 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 4407 } 4408 4409 /** 4410 * When a view is focusable, it may not want to take focus when in touch mode. 4411 * For example, a button would like focus when the user is navigating via a D-pad 4412 * so that the user can click on it, but once the user starts touching the screen, 4413 * the button shouldn't take focus 4414 * @return Whether the view is focusable in touch mode. 4415 * @attr ref android.R.styleable#View_focusableInTouchMode 4416 */ 4417 @ViewDebug.ExportedProperty 4418 public final boolean isFocusableInTouchMode() { 4419 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 4420 } 4421 4422 /** 4423 * Find the nearest view in the specified direction that can take focus. 4424 * This does not actually give focus to that view. 4425 * 4426 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 4427 * 4428 * @return The nearest focusable in the specified direction, or null if none 4429 * can be found. 4430 */ 4431 public View focusSearch(int direction) { 4432 if (mParent != null) { 4433 return mParent.focusSearch(this, direction); 4434 } else { 4435 return null; 4436 } 4437 } 4438 4439 /** 4440 * This method is the last chance for the focused view and its ancestors to 4441 * respond to an arrow key. This is called when the focused view did not 4442 * consume the key internally, nor could the view system find a new view in 4443 * the requested direction to give focus to. 4444 * 4445 * @param focused The currently focused view. 4446 * @param direction The direction focus wants to move. One of FOCUS_UP, 4447 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 4448 * @return True if the this view consumed this unhandled move. 4449 */ 4450 public boolean dispatchUnhandledMove(View focused, int direction) { 4451 return false; 4452 } 4453 4454 /** 4455 * If a user manually specified the next view id for a particular direction, 4456 * use the root to look up the view. 4457 * @param root The root view of the hierarchy containing this view. 4458 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 4459 * or FOCUS_BACKWARD. 4460 * @return The user specified next view, or null if there is none. 4461 */ 4462 View findUserSetNextFocus(View root, int direction) { 4463 switch (direction) { 4464 case FOCUS_LEFT: 4465 if (mNextFocusLeftId == View.NO_ID) return null; 4466 return findViewShouldExist(root, mNextFocusLeftId); 4467 case FOCUS_RIGHT: 4468 if (mNextFocusRightId == View.NO_ID) return null; 4469 return findViewShouldExist(root, mNextFocusRightId); 4470 case FOCUS_UP: 4471 if (mNextFocusUpId == View.NO_ID) return null; 4472 return findViewShouldExist(root, mNextFocusUpId); 4473 case FOCUS_DOWN: 4474 if (mNextFocusDownId == View.NO_ID) return null; 4475 return findViewShouldExist(root, mNextFocusDownId); 4476 case FOCUS_FORWARD: 4477 if (mNextFocusForwardId == View.NO_ID) return null; 4478 return findViewShouldExist(root, mNextFocusForwardId); 4479 case FOCUS_BACKWARD: { 4480 final int id = mID; 4481 return root.findViewByPredicate(new Predicate<View>() { 4482 @Override 4483 public boolean apply(View t) { 4484 return t.mNextFocusForwardId == id; 4485 } 4486 }); 4487 } 4488 } 4489 return null; 4490 } 4491 4492 private static View findViewShouldExist(View root, int childViewId) { 4493 View result = root.findViewById(childViewId); 4494 if (result == null) { 4495 Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified " 4496 + "by user for id " + childViewId); 4497 } 4498 return result; 4499 } 4500 4501 /** 4502 * Find and return all focusable views that are descendants of this view, 4503 * possibly including this view if it is focusable itself. 4504 * 4505 * @param direction The direction of the focus 4506 * @return A list of focusable views 4507 */ 4508 public ArrayList<View> getFocusables(int direction) { 4509 ArrayList<View> result = new ArrayList<View>(24); 4510 addFocusables(result, direction); 4511 return result; 4512 } 4513 4514 /** 4515 * Add any focusable views that are descendants of this view (possibly 4516 * including this view if it is focusable itself) to views. If we are in touch mode, 4517 * only add views that are also focusable in touch mode. 4518 * 4519 * @param views Focusable views found so far 4520 * @param direction The direction of the focus 4521 */ 4522 public void addFocusables(ArrayList<View> views, int direction) { 4523 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 4524 } 4525 4526 /** 4527 * Adds any focusable views that are descendants of this view (possibly 4528 * including this view if it is focusable itself) to views. This method 4529 * adds all focusable views regardless if we are in touch mode or 4530 * only views focusable in touch mode if we are in touch mode depending on 4531 * the focusable mode paramater. 4532 * 4533 * @param views Focusable views found so far or null if all we are interested is 4534 * the number of focusables. 4535 * @param direction The direction of the focus. 4536 * @param focusableMode The type of focusables to be added. 4537 * 4538 * @see #FOCUSABLES_ALL 4539 * @see #FOCUSABLES_TOUCH_MODE 4540 */ 4541 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { 4542 if (!isFocusable()) { 4543 return; 4544 } 4545 4546 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE && 4547 isInTouchMode() && !isFocusableInTouchMode()) { 4548 return; 4549 } 4550 4551 if (views != null) { 4552 views.add(this); 4553 } 4554 } 4555 4556 /** 4557 * Find and return all touchable views that are descendants of this view, 4558 * possibly including this view if it is touchable itself. 4559 * 4560 * @return A list of touchable views 4561 */ 4562 public ArrayList<View> getTouchables() { 4563 ArrayList<View> result = new ArrayList<View>(); 4564 addTouchables(result); 4565 return result; 4566 } 4567 4568 /** 4569 * Add any touchable views that are descendants of this view (possibly 4570 * including this view if it is touchable itself) to views. 4571 * 4572 * @param views Touchable views found so far 4573 */ 4574 public void addTouchables(ArrayList<View> views) { 4575 final int viewFlags = mViewFlags; 4576 4577 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 4578 && (viewFlags & ENABLED_MASK) == ENABLED) { 4579 views.add(this); 4580 } 4581 } 4582 4583 /** 4584 * Call this to try to give focus to a specific view or to one of its 4585 * descendants. 4586 * 4587 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 4588 * false), or if it is focusable and it is not focusable in touch mode 4589 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 4590 * 4591 * See also {@link #focusSearch(int)}, which is what you call to say that you 4592 * have focus, and you want your parent to look for the next one. 4593 * 4594 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 4595 * {@link #FOCUS_DOWN} and <code>null</code>. 4596 * 4597 * @return Whether this view or one of its descendants actually took focus. 4598 */ 4599 public final boolean requestFocus() { 4600 return requestFocus(View.FOCUS_DOWN); 4601 } 4602 4603 4604 /** 4605 * Call this to try to give focus to a specific view or to one of its 4606 * descendants and give it a hint about what direction focus is heading. 4607 * 4608 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 4609 * false), or if it is focusable and it is not focusable in touch mode 4610 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 4611 * 4612 * See also {@link #focusSearch(int)}, which is what you call to say that you 4613 * have focus, and you want your parent to look for the next one. 4614 * 4615 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 4616 * <code>null</code> set for the previously focused rectangle. 4617 * 4618 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 4619 * @return Whether this view or one of its descendants actually took focus. 4620 */ 4621 public final boolean requestFocus(int direction) { 4622 return requestFocus(direction, null); 4623 } 4624 4625 /** 4626 * Call this to try to give focus to a specific view or to one of its descendants 4627 * and give it hints about the direction and a specific rectangle that the focus 4628 * is coming from. The rectangle can help give larger views a finer grained hint 4629 * about where focus is coming from, and therefore, where to show selection, or 4630 * forward focus change internally. 4631 * 4632 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 4633 * false), or if it is focusable and it is not focusable in touch mode 4634 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 4635 * 4636 * A View will not take focus if it is not visible. 4637 * 4638 * A View will not take focus if one of its parents has 4639 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 4640 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 4641 * 4642 * See also {@link #focusSearch(int)}, which is what you call to say that you 4643 * have focus, and you want your parent to look for the next one. 4644 * 4645 * You may wish to override this method if your custom {@link View} has an internal 4646 * {@link View} that it wishes to forward the request to. 4647 * 4648 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 4649 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 4650 * to give a finer grained hint about where focus is coming from. May be null 4651 * if there is no hint. 4652 * @return Whether this view or one of its descendants actually took focus. 4653 */ 4654 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 4655 // need to be focusable 4656 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 4657 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 4658 return false; 4659 } 4660 4661 // need to be focusable in touch mode if in touch mode 4662 if (isInTouchMode() && 4663 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 4664 return false; 4665 } 4666 4667 // need to not have any parents blocking us 4668 if (hasAncestorThatBlocksDescendantFocus()) { 4669 return false; 4670 } 4671 4672 handleFocusGainInternal(direction, previouslyFocusedRect); 4673 return true; 4674 } 4675 4676 /** Gets the ViewAncestor, or null if not attached. */ 4677 /*package*/ ViewAncestor getViewAncestor() { 4678 View root = getRootView(); 4679 return root != null ? (ViewAncestor)root.getParent() : null; 4680 } 4681 4682 /** 4683 * Call this to try to give focus to a specific view or to one of its descendants. This is a 4684 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 4685 * touch mode to request focus when they are touched. 4686 * 4687 * @return Whether this view or one of its descendants actually took focus. 4688 * 4689 * @see #isInTouchMode() 4690 * 4691 */ 4692 public final boolean requestFocusFromTouch() { 4693 // Leave touch mode if we need to 4694 if (isInTouchMode()) { 4695 ViewAncestor viewRoot = getViewAncestor(); 4696 if (viewRoot != null) { 4697 viewRoot.ensureTouchMode(false); 4698 } 4699 } 4700 return requestFocus(View.FOCUS_DOWN); 4701 } 4702 4703 /** 4704 * @return Whether any ancestor of this view blocks descendant focus. 4705 */ 4706 private boolean hasAncestorThatBlocksDescendantFocus() { 4707 ViewParent ancestor = mParent; 4708 while (ancestor instanceof ViewGroup) { 4709 final ViewGroup vgAncestor = (ViewGroup) ancestor; 4710 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) { 4711 return true; 4712 } else { 4713 ancestor = vgAncestor.getParent(); 4714 } 4715 } 4716 return false; 4717 } 4718 4719 /** 4720 * @hide 4721 */ 4722 public void dispatchStartTemporaryDetach() { 4723 onStartTemporaryDetach(); 4724 } 4725 4726 /** 4727 * This is called when a container is going to temporarily detach a child, with 4728 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 4729 * It will either be followed by {@link #onFinishTemporaryDetach()} or 4730 * {@link #onDetachedFromWindow()} when the container is done. 4731 */ 4732 public void onStartTemporaryDetach() { 4733 removeUnsetPressCallback(); 4734 mPrivateFlags |= CANCEL_NEXT_UP_EVENT; 4735 } 4736 4737 /** 4738 * @hide 4739 */ 4740 public void dispatchFinishTemporaryDetach() { 4741 onFinishTemporaryDetach(); 4742 } 4743 4744 /** 4745 * Called after {@link #onStartTemporaryDetach} when the container is done 4746 * changing the view. 4747 */ 4748 public void onFinishTemporaryDetach() { 4749 } 4750 4751 /** 4752 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 4753 * for this view's window. Returns null if the view is not currently attached 4754 * to the window. Normally you will not need to use this directly, but 4755 * just use the standard high-level event callbacks like 4756 * {@link #onKeyDown(int, KeyEvent)}. 4757 */ 4758 public KeyEvent.DispatcherState getKeyDispatcherState() { 4759 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 4760 } 4761 4762 /** 4763 * Dispatch a key event before it is processed by any input method 4764 * associated with the view hierarchy. This can be used to intercept 4765 * key events in special situations before the IME consumes them; a 4766 * typical example would be handling the BACK key to update the application's 4767 * UI instead of allowing the IME to see it and close itself. 4768 * 4769 * @param event The key event to be dispatched. 4770 * @return True if the event was handled, false otherwise. 4771 */ 4772 public boolean dispatchKeyEventPreIme(KeyEvent event) { 4773 return onKeyPreIme(event.getKeyCode(), event); 4774 } 4775 4776 /** 4777 * Dispatch a key event to the next view on the focus path. This path runs 4778 * from the top of the view tree down to the currently focused view. If this 4779 * view has focus, it will dispatch to itself. Otherwise it will dispatch 4780 * the next node down the focus path. This method also fires any key 4781 * listeners. 4782 * 4783 * @param event The key event to be dispatched. 4784 * @return True if the event was handled, false otherwise. 4785 */ 4786 public boolean dispatchKeyEvent(KeyEvent event) { 4787 if (mInputEventConsistencyVerifier != null) { 4788 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 4789 } 4790 4791 // Give any attached key listener a first crack at the event. 4792 //noinspection SimplifiableIfStatement 4793 if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 4794 && mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 4795 return true; 4796 } 4797 4798 if (event.dispatch(this, mAttachInfo != null 4799 ? mAttachInfo.mKeyDispatchState : null, this)) { 4800 return true; 4801 } 4802 4803 if (mInputEventConsistencyVerifier != null) { 4804 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 4805 } 4806 return false; 4807 } 4808 4809 /** 4810 * Dispatches a key shortcut event. 4811 * 4812 * @param event The key event to be dispatched. 4813 * @return True if the event was handled by the view, false otherwise. 4814 */ 4815 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 4816 return onKeyShortcut(event.getKeyCode(), event); 4817 } 4818 4819 /** 4820 * Pass the touch screen motion event down to the target view, or this 4821 * view if it is the target. 4822 * 4823 * @param event The motion event to be dispatched. 4824 * @return True if the event was handled by the view, false otherwise. 4825 */ 4826 public boolean dispatchTouchEvent(MotionEvent event) { 4827 if (mInputEventConsistencyVerifier != null) { 4828 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 4829 } 4830 4831 if (onFilterTouchEventForSecurity(event)) { 4832 //noinspection SimplifiableIfStatement 4833 if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED && 4834 mOnTouchListener.onTouch(this, event)) { 4835 return true; 4836 } 4837 4838 if (onTouchEvent(event)) { 4839 return true; 4840 } 4841 } 4842 4843 if (mInputEventConsistencyVerifier != null) { 4844 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 4845 } 4846 return false; 4847 } 4848 4849 /** 4850 * Filter the touch event to apply security policies. 4851 * 4852 * @param event The motion event to be filtered. 4853 * @return True if the event should be dispatched, false if the event should be dropped. 4854 * 4855 * @see #getFilterTouchesWhenObscured 4856 */ 4857 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 4858 //noinspection RedundantIfStatement 4859 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 4860 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 4861 // Window is obscured, drop this touch. 4862 return false; 4863 } 4864 return true; 4865 } 4866 4867 /** 4868 * Pass a trackball motion event down to the focused view. 4869 * 4870 * @param event The motion event to be dispatched. 4871 * @return True if the event was handled by the view, false otherwise. 4872 */ 4873 public boolean dispatchTrackballEvent(MotionEvent event) { 4874 if (mInputEventConsistencyVerifier != null) { 4875 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 4876 } 4877 4878 //Log.i("view", "view=" + this + ", " + event.toString()); 4879 if (onTrackballEvent(event)) { 4880 return true; 4881 } 4882 4883 if (mInputEventConsistencyVerifier != null) { 4884 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 4885 } 4886 return false; 4887 } 4888 4889 /** 4890 * Dispatch a generic motion event. 4891 * <p> 4892 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 4893 * are delivered to the view under the pointer. All other generic motion events are 4894 * delivered to the focused view. Hover events are handled specially and are delivered 4895 * to {@link #onHoverEvent(MotionEvent)}. 4896 * </p> 4897 * 4898 * @param event The motion event to be dispatched. 4899 * @return True if the event was handled by the view, false otherwise. 4900 */ 4901 public boolean dispatchGenericMotionEvent(MotionEvent event) { 4902 if (mInputEventConsistencyVerifier != null) { 4903 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 4904 } 4905 4906 final int source = event.getSource(); 4907 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 4908 final int action = event.getAction(); 4909 if (action == MotionEvent.ACTION_HOVER_ENTER 4910 || action == MotionEvent.ACTION_HOVER_MOVE 4911 || action == MotionEvent.ACTION_HOVER_EXIT) { 4912 if (dispatchHoverEvent(event)) { 4913 return true; 4914 } 4915 } else if (dispatchGenericPointerEvent(event)) { 4916 return true; 4917 } 4918 } else if (dispatchGenericFocusedEvent(event)) { 4919 return true; 4920 } 4921 4922 //noinspection SimplifiableIfStatement 4923 if (mOnGenericMotionListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 4924 && mOnGenericMotionListener.onGenericMotion(this, event)) { 4925 return true; 4926 } 4927 4928 if (onGenericMotionEvent(event)) { 4929 return true; 4930 } 4931 4932 if (mInputEventConsistencyVerifier != null) { 4933 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 4934 } 4935 return false; 4936 } 4937 4938 /** 4939 * Dispatch a hover event. 4940 * <p> 4941 * Do not call this method directly. 4942 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 4943 * </p> 4944 * 4945 * @param event The motion event to be dispatched. 4946 * @return True if the event was handled by the view, false otherwise. 4947 * @hide 4948 */ 4949 protected boolean dispatchHoverEvent(MotionEvent event) { 4950 return onHoverEvent(event); 4951 } 4952 4953 /** 4954 * Dispatch a generic motion event to the view under the first pointer. 4955 * <p> 4956 * Do not call this method directly. 4957 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 4958 * </p> 4959 * 4960 * @param event The motion event to be dispatched. 4961 * @return True if the event was handled by the view, false otherwise. 4962 * @hide 4963 */ 4964 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 4965 return false; 4966 } 4967 4968 /** 4969 * Dispatch a generic motion event to the currently focused view. 4970 * <p> 4971 * Do not call this method directly. 4972 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 4973 * </p> 4974 * 4975 * @param event The motion event to be dispatched. 4976 * @return True if the event was handled by the view, false otherwise. 4977 * @hide 4978 */ 4979 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 4980 return false; 4981 } 4982 4983 /** 4984 * Dispatch a pointer event. 4985 * <p> 4986 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 4987 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 4988 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 4989 * and should not be expected to handle other pointing device features. 4990 * </p> 4991 * 4992 * @param event The motion event to be dispatched. 4993 * @return True if the event was handled by the view, false otherwise. 4994 * @hide 4995 */ 4996 public final boolean dispatchPointerEvent(MotionEvent event) { 4997 if (event.isTouchEvent()) { 4998 return dispatchTouchEvent(event); 4999 } else { 5000 return dispatchGenericMotionEvent(event); 5001 } 5002 } 5003 5004 /** 5005 * Called when the window containing this view gains or loses window focus. 5006 * ViewGroups should override to route to their children. 5007 * 5008 * @param hasFocus True if the window containing this view now has focus, 5009 * false otherwise. 5010 */ 5011 public void dispatchWindowFocusChanged(boolean hasFocus) { 5012 onWindowFocusChanged(hasFocus); 5013 } 5014 5015 /** 5016 * Called when the window containing this view gains or loses focus. Note 5017 * that this is separate from view focus: to receive key events, both 5018 * your view and its window must have focus. If a window is displayed 5019 * on top of yours that takes input focus, then your own window will lose 5020 * focus but the view focus will remain unchanged. 5021 * 5022 * @param hasWindowFocus True if the window containing this view now has 5023 * focus, false otherwise. 5024 */ 5025 public void onWindowFocusChanged(boolean hasWindowFocus) { 5026 InputMethodManager imm = InputMethodManager.peekInstance(); 5027 if (!hasWindowFocus) { 5028 if (isPressed()) { 5029 setPressed(false); 5030 } 5031 if (imm != null && (mPrivateFlags & FOCUSED) != 0) { 5032 imm.focusOut(this); 5033 } 5034 removeLongPressCallback(); 5035 removeTapCallback(); 5036 onFocusLost(); 5037 } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) { 5038 imm.focusIn(this); 5039 } 5040 refreshDrawableState(); 5041 } 5042 5043 /** 5044 * Returns true if this view is in a window that currently has window focus. 5045 * Note that this is not the same as the view itself having focus. 5046 * 5047 * @return True if this view is in a window that currently has window focus. 5048 */ 5049 public boolean hasWindowFocus() { 5050 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 5051 } 5052 5053 /** 5054 * Dispatch a view visibility change down the view hierarchy. 5055 * ViewGroups should override to route to their children. 5056 * @param changedView The view whose visibility changed. Could be 'this' or 5057 * an ancestor view. 5058 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 5059 * {@link #INVISIBLE} or {@link #GONE}. 5060 */ 5061 protected void dispatchVisibilityChanged(View changedView, int visibility) { 5062 onVisibilityChanged(changedView, visibility); 5063 } 5064 5065 /** 5066 * Called when the visibility of the view or an ancestor of the view is changed. 5067 * @param changedView The view whose visibility changed. Could be 'this' or 5068 * an ancestor view. 5069 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 5070 * {@link #INVISIBLE} or {@link #GONE}. 5071 */ 5072 protected void onVisibilityChanged(View changedView, int visibility) { 5073 if (visibility == VISIBLE) { 5074 if (mAttachInfo != null) { 5075 initialAwakenScrollBars(); 5076 } else { 5077 mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH; 5078 } 5079 } 5080 } 5081 5082 /** 5083 * Dispatch a hint about whether this view is displayed. For instance, when 5084 * a View moves out of the screen, it might receives a display hint indicating 5085 * the view is not displayed. Applications should not <em>rely</em> on this hint 5086 * as there is no guarantee that they will receive one. 5087 * 5088 * @param hint A hint about whether or not this view is displayed: 5089 * {@link #VISIBLE} or {@link #INVISIBLE}. 5090 */ 5091 public void dispatchDisplayHint(int hint) { 5092 onDisplayHint(hint); 5093 } 5094 5095 /** 5096 * Gives this view a hint about whether is displayed or not. For instance, when 5097 * a View moves out of the screen, it might receives a display hint indicating 5098 * the view is not displayed. Applications should not <em>rely</em> on this hint 5099 * as there is no guarantee that they will receive one. 5100 * 5101 * @param hint A hint about whether or not this view is displayed: 5102 * {@link #VISIBLE} or {@link #INVISIBLE}. 5103 */ 5104 protected void onDisplayHint(int hint) { 5105 } 5106 5107 /** 5108 * Dispatch a window visibility change down the view hierarchy. 5109 * ViewGroups should override to route to their children. 5110 * 5111 * @param visibility The new visibility of the window. 5112 * 5113 * @see #onWindowVisibilityChanged(int) 5114 */ 5115 public void dispatchWindowVisibilityChanged(int visibility) { 5116 onWindowVisibilityChanged(visibility); 5117 } 5118 5119 /** 5120 * Called when the window containing has change its visibility 5121 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 5122 * that this tells you whether or not your window is being made visible 5123 * to the window manager; this does <em>not</em> tell you whether or not 5124 * your window is obscured by other windows on the screen, even if it 5125 * is itself visible. 5126 * 5127 * @param visibility The new visibility of the window. 5128 */ 5129 protected void onWindowVisibilityChanged(int visibility) { 5130 if (visibility == VISIBLE) { 5131 initialAwakenScrollBars(); 5132 } 5133 } 5134 5135 /** 5136 * Returns the current visibility of the window this view is attached to 5137 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 5138 * 5139 * @return Returns the current visibility of the view's window. 5140 */ 5141 public int getWindowVisibility() { 5142 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 5143 } 5144 5145 /** 5146 * Retrieve the overall visible display size in which the window this view is 5147 * attached to has been positioned in. This takes into account screen 5148 * decorations above the window, for both cases where the window itself 5149 * is being position inside of them or the window is being placed under 5150 * then and covered insets are used for the window to position its content 5151 * inside. In effect, this tells you the available area where content can 5152 * be placed and remain visible to users. 5153 * 5154 * <p>This function requires an IPC back to the window manager to retrieve 5155 * the requested information, so should not be used in performance critical 5156 * code like drawing. 5157 * 5158 * @param outRect Filled in with the visible display frame. If the view 5159 * is not attached to a window, this is simply the raw display size. 5160 */ 5161 public void getWindowVisibleDisplayFrame(Rect outRect) { 5162 if (mAttachInfo != null) { 5163 try { 5164 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 5165 } catch (RemoteException e) { 5166 return; 5167 } 5168 // XXX This is really broken, and probably all needs to be done 5169 // in the window manager, and we need to know more about whether 5170 // we want the area behind or in front of the IME. 5171 final Rect insets = mAttachInfo.mVisibleInsets; 5172 outRect.left += insets.left; 5173 outRect.top += insets.top; 5174 outRect.right -= insets.right; 5175 outRect.bottom -= insets.bottom; 5176 return; 5177 } 5178 Display d = WindowManagerImpl.getDefault().getDefaultDisplay(); 5179 d.getRectSize(outRect); 5180 } 5181 5182 /** 5183 * Dispatch a notification about a resource configuration change down 5184 * the view hierarchy. 5185 * ViewGroups should override to route to their children. 5186 * 5187 * @param newConfig The new resource configuration. 5188 * 5189 * @see #onConfigurationChanged(android.content.res.Configuration) 5190 */ 5191 public void dispatchConfigurationChanged(Configuration newConfig) { 5192 onConfigurationChanged(newConfig); 5193 } 5194 5195 /** 5196 * Called when the current configuration of the resources being used 5197 * by the application have changed. You can use this to decide when 5198 * to reload resources that can changed based on orientation and other 5199 * configuration characterstics. You only need to use this if you are 5200 * not relying on the normal {@link android.app.Activity} mechanism of 5201 * recreating the activity instance upon a configuration change. 5202 * 5203 * @param newConfig The new resource configuration. 5204 */ 5205 protected void onConfigurationChanged(Configuration newConfig) { 5206 } 5207 5208 /** 5209 * Private function to aggregate all per-view attributes in to the view 5210 * root. 5211 */ 5212 void dispatchCollectViewAttributes(int visibility) { 5213 performCollectViewAttributes(visibility); 5214 } 5215 5216 void performCollectViewAttributes(int visibility) { 5217 if ((visibility & VISIBILITY_MASK) == VISIBLE && mAttachInfo != null) { 5218 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 5219 mAttachInfo.mKeepScreenOn = true; 5220 } 5221 mAttachInfo.mSystemUiVisibility |= mSystemUiVisibility; 5222 if (mOnSystemUiVisibilityChangeListener != null) { 5223 mAttachInfo.mHasSystemUiListeners = true; 5224 } 5225 } 5226 } 5227 5228 void needGlobalAttributesUpdate(boolean force) { 5229 final AttachInfo ai = mAttachInfo; 5230 if (ai != null) { 5231 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 5232 || ai.mHasSystemUiListeners) { 5233 ai.mRecomputeGlobalAttributes = true; 5234 } 5235 } 5236 } 5237 5238 /** 5239 * Returns whether the device is currently in touch mode. Touch mode is entered 5240 * once the user begins interacting with the device by touch, and affects various 5241 * things like whether focus is always visible to the user. 5242 * 5243 * @return Whether the device is in touch mode. 5244 */ 5245 @ViewDebug.ExportedProperty 5246 public boolean isInTouchMode() { 5247 if (mAttachInfo != null) { 5248 return mAttachInfo.mInTouchMode; 5249 } else { 5250 return ViewAncestor.isInTouchMode(); 5251 } 5252 } 5253 5254 /** 5255 * Returns the context the view is running in, through which it can 5256 * access the current theme, resources, etc. 5257 * 5258 * @return The view's Context. 5259 */ 5260 @ViewDebug.CapturedViewProperty 5261 public final Context getContext() { 5262 return mContext; 5263 } 5264 5265 /** 5266 * Handle a key event before it is processed by any input method 5267 * associated with the view hierarchy. This can be used to intercept 5268 * key events in special situations before the IME consumes them; a 5269 * typical example would be handling the BACK key to update the application's 5270 * UI instead of allowing the IME to see it and close itself. 5271 * 5272 * @param keyCode The value in event.getKeyCode(). 5273 * @param event Description of the key event. 5274 * @return If you handled the event, return true. If you want to allow the 5275 * event to be handled by the next receiver, return false. 5276 */ 5277 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 5278 return false; 5279 } 5280 5281 /** 5282 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 5283 * KeyEvent.Callback.onKeyDown()}: perform press of the view 5284 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 5285 * is released, if the view is enabled and clickable. 5286 * 5287 * @param keyCode A key code that represents the button pressed, from 5288 * {@link android.view.KeyEvent}. 5289 * @param event The KeyEvent object that defines the button action. 5290 */ 5291 public boolean onKeyDown(int keyCode, KeyEvent event) { 5292 boolean result = false; 5293 5294 switch (keyCode) { 5295 case KeyEvent.KEYCODE_DPAD_CENTER: 5296 case KeyEvent.KEYCODE_ENTER: { 5297 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 5298 return true; 5299 } 5300 // Long clickable items don't necessarily have to be clickable 5301 if (((mViewFlags & CLICKABLE) == CLICKABLE || 5302 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 5303 (event.getRepeatCount() == 0)) { 5304 setPressed(true); 5305 checkForLongClick(0); 5306 return true; 5307 } 5308 break; 5309 } 5310 } 5311 return result; 5312 } 5313 5314 /** 5315 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 5316 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 5317 * the event). 5318 */ 5319 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 5320 return false; 5321 } 5322 5323 /** 5324 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 5325 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 5326 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 5327 * {@link KeyEvent#KEYCODE_ENTER} is released. 5328 * 5329 * @param keyCode A key code that represents the button pressed, from 5330 * {@link android.view.KeyEvent}. 5331 * @param event The KeyEvent object that defines the button action. 5332 */ 5333 public boolean onKeyUp(int keyCode, KeyEvent event) { 5334 boolean result = false; 5335 5336 switch (keyCode) { 5337 case KeyEvent.KEYCODE_DPAD_CENTER: 5338 case KeyEvent.KEYCODE_ENTER: { 5339 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 5340 return true; 5341 } 5342 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 5343 setPressed(false); 5344 5345 if (!mHasPerformedLongPress) { 5346 // This is a tap, so remove the longpress check 5347 removeLongPressCallback(); 5348 5349 result = performClick(); 5350 } 5351 } 5352 break; 5353 } 5354 } 5355 return result; 5356 } 5357 5358 /** 5359 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 5360 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 5361 * the event). 5362 * 5363 * @param keyCode A key code that represents the button pressed, from 5364 * {@link android.view.KeyEvent}. 5365 * @param repeatCount The number of times the action was made. 5366 * @param event The KeyEvent object that defines the button action. 5367 */ 5368 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 5369 return false; 5370 } 5371 5372 /** 5373 * Called on the focused view when a key shortcut event is not handled. 5374 * Override this method to implement local key shortcuts for the View. 5375 * Key shortcuts can also be implemented by setting the 5376 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 5377 * 5378 * @param keyCode The value in event.getKeyCode(). 5379 * @param event Description of the key event. 5380 * @return If you handled the event, return true. If you want to allow the 5381 * event to be handled by the next receiver, return false. 5382 */ 5383 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 5384 return false; 5385 } 5386 5387 /** 5388 * Check whether the called view is a text editor, in which case it 5389 * would make sense to automatically display a soft input window for 5390 * it. Subclasses should override this if they implement 5391 * {@link #onCreateInputConnection(EditorInfo)} to return true if 5392 * a call on that method would return a non-null InputConnection, and 5393 * they are really a first-class editor that the user would normally 5394 * start typing on when the go into a window containing your view. 5395 * 5396 * <p>The default implementation always returns false. This does 5397 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 5398 * will not be called or the user can not otherwise perform edits on your 5399 * view; it is just a hint to the system that this is not the primary 5400 * purpose of this view. 5401 * 5402 * @return Returns true if this view is a text editor, else false. 5403 */ 5404 public boolean onCheckIsTextEditor() { 5405 return false; 5406 } 5407 5408 /** 5409 * Create a new InputConnection for an InputMethod to interact 5410 * with the view. The default implementation returns null, since it doesn't 5411 * support input methods. You can override this to implement such support. 5412 * This is only needed for views that take focus and text input. 5413 * 5414 * <p>When implementing this, you probably also want to implement 5415 * {@link #onCheckIsTextEditor()} to indicate you will return a 5416 * non-null InputConnection. 5417 * 5418 * @param outAttrs Fill in with attribute information about the connection. 5419 */ 5420 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 5421 return null; 5422 } 5423 5424 /** 5425 * Called by the {@link android.view.inputmethod.InputMethodManager} 5426 * when a view who is not the current 5427 * input connection target is trying to make a call on the manager. The 5428 * default implementation returns false; you can override this to return 5429 * true for certain views if you are performing InputConnection proxying 5430 * to them. 5431 * @param view The View that is making the InputMethodManager call. 5432 * @return Return true to allow the call, false to reject. 5433 */ 5434 public boolean checkInputConnectionProxy(View view) { 5435 return false; 5436 } 5437 5438 /** 5439 * Show the context menu for this view. It is not safe to hold on to the 5440 * menu after returning from this method. 5441 * 5442 * You should normally not overload this method. Overload 5443 * {@link #onCreateContextMenu(ContextMenu)} or define an 5444 * {@link OnCreateContextMenuListener} to add items to the context menu. 5445 * 5446 * @param menu The context menu to populate 5447 */ 5448 public void createContextMenu(ContextMenu menu) { 5449 ContextMenuInfo menuInfo = getContextMenuInfo(); 5450 5451 // Sets the current menu info so all items added to menu will have 5452 // my extra info set. 5453 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 5454 5455 onCreateContextMenu(menu); 5456 if (mOnCreateContextMenuListener != null) { 5457 mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 5458 } 5459 5460 // Clear the extra information so subsequent items that aren't mine don't 5461 // have my extra info. 5462 ((MenuBuilder)menu).setCurrentMenuInfo(null); 5463 5464 if (mParent != null) { 5465 mParent.createContextMenu(menu); 5466 } 5467 } 5468 5469 /** 5470 * Views should implement this if they have extra information to associate 5471 * with the context menu. The return result is supplied as a parameter to 5472 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 5473 * callback. 5474 * 5475 * @return Extra information about the item for which the context menu 5476 * should be shown. This information will vary across different 5477 * subclasses of View. 5478 */ 5479 protected ContextMenuInfo getContextMenuInfo() { 5480 return null; 5481 } 5482 5483 /** 5484 * Views should implement this if the view itself is going to add items to 5485 * the context menu. 5486 * 5487 * @param menu the context menu to populate 5488 */ 5489 protected void onCreateContextMenu(ContextMenu menu) { 5490 } 5491 5492 /** 5493 * Implement this method to handle trackball motion events. The 5494 * <em>relative</em> movement of the trackball since the last event 5495 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 5496 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 5497 * that a movement of 1 corresponds to the user pressing one DPAD key (so 5498 * they will often be fractional values, representing the more fine-grained 5499 * movement information available from a trackball). 5500 * 5501 * @param event The motion event. 5502 * @return True if the event was handled, false otherwise. 5503 */ 5504 public boolean onTrackballEvent(MotionEvent event) { 5505 return false; 5506 } 5507 5508 /** 5509 * Implement this method to handle generic motion events. 5510 * <p> 5511 * Generic motion events describe joystick movements, mouse hovers, track pad 5512 * touches, scroll wheel movements and other input events. The 5513 * {@link MotionEvent#getSource() source} of the motion event specifies 5514 * the class of input that was received. Implementations of this method 5515 * must examine the bits in the source before processing the event. 5516 * The following code example shows how this is done. 5517 * </p><p> 5518 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 5519 * are delivered to the view under the pointer. All other generic motion events are 5520 * delivered to the focused view. 5521 * </p> 5522 * <code> 5523 * public boolean onGenericMotionEvent(MotionEvent event) { 5524 * if ((event.getSource() & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) { 5525 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 5526 * // process the joystick movement... 5527 * return true; 5528 * } 5529 * } 5530 * if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) { 5531 * switch (event.getAction()) { 5532 * case MotionEvent.ACTION_HOVER_MOVE: 5533 * // process the mouse hover movement... 5534 * return true; 5535 * case MotionEvent.ACTION_SCROLL: 5536 * // process the scroll wheel movement... 5537 * return true; 5538 * } 5539 * } 5540 * return super.onGenericMotionEvent(event); 5541 * } 5542 * </code> 5543 * 5544 * @param event The generic motion event being processed. 5545 * @return True if the event was handled, false otherwise. 5546 */ 5547 public boolean onGenericMotionEvent(MotionEvent event) { 5548 return false; 5549 } 5550 5551 /** 5552 * Implement this method to handle hover events. 5553 * <p> 5554 * Hover events are pointer events with action {@link MotionEvent#ACTION_HOVER_ENTER}, 5555 * {@link MotionEvent#ACTION_HOVER_MOVE}, or {@link MotionEvent#ACTION_HOVER_EXIT}. 5556 * </p><p> 5557 * The view receives hover enter as the pointer enters the bounds of the view and hover 5558 * exit as the pointer exits the bound of the view or just before the pointer goes down 5559 * (which implies that {@link #onTouchEvent(MotionEvent)} will be called soon). 5560 * </p><p> 5561 * If the view would like to handle the hover event itself and prevent its children 5562 * from receiving hover, it should return true from this method. If this method returns 5563 * true and a child has already received a hover enter event, the child will 5564 * automatically receive a hover exit event. 5565 * </p><p> 5566 * The default implementation sets the hovered state of the view if the view is 5567 * clickable. 5568 * </p> 5569 * 5570 * @param event The motion event that describes the hover. 5571 * @return True if this view handled the hover event and does not want its children 5572 * to receive the hover event. 5573 */ 5574 public boolean onHoverEvent(MotionEvent event) { 5575 switch (event.getAction()) { 5576 case MotionEvent.ACTION_HOVER_ENTER: 5577 setHovered(true); 5578 break; 5579 5580 case MotionEvent.ACTION_HOVER_EXIT: 5581 setHovered(false); 5582 break; 5583 } 5584 5585 return false; 5586 } 5587 5588 /** 5589 * Returns true if the view is currently hovered. 5590 * 5591 * @return True if the view is currently hovered. 5592 */ 5593 public boolean isHovered() { 5594 return (mPrivateFlags & HOVERED) != 0; 5595 } 5596 5597 /** 5598 * Sets whether the view is currently hovered. 5599 * 5600 * @param hovered True if the view is hovered. 5601 */ 5602 public void setHovered(boolean hovered) { 5603 if (hovered) { 5604 if ((mPrivateFlags & HOVERED) == 0) { 5605 mPrivateFlags |= HOVERED; 5606 refreshDrawableState(); 5607 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 5608 } 5609 } else { 5610 if ((mPrivateFlags & HOVERED) != 0) { 5611 mPrivateFlags &= ~HOVERED; 5612 refreshDrawableState(); 5613 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 5614 } 5615 } 5616 } 5617 5618 /** 5619 * Implement this method to handle touch screen motion events. 5620 * 5621 * @param event The motion event. 5622 * @return True if the event was handled, false otherwise. 5623 */ 5624 public boolean onTouchEvent(MotionEvent event) { 5625 final int viewFlags = mViewFlags; 5626 5627 if ((viewFlags & ENABLED_MASK) == DISABLED) { 5628 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) { 5629 mPrivateFlags &= ~PRESSED; 5630 refreshDrawableState(); 5631 } 5632 // A disabled view that is clickable still consumes the touch 5633 // events, it just doesn't respond to them. 5634 return (((viewFlags & CLICKABLE) == CLICKABLE || 5635 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 5636 } 5637 5638 if (mTouchDelegate != null) { 5639 if (mTouchDelegate.onTouchEvent(event)) { 5640 return true; 5641 } 5642 } 5643 5644 if (((viewFlags & CLICKABLE) == CLICKABLE || 5645 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 5646 switch (event.getAction()) { 5647 case MotionEvent.ACTION_UP: 5648 boolean prepressed = (mPrivateFlags & PREPRESSED) != 0; 5649 if ((mPrivateFlags & PRESSED) != 0 || prepressed) { 5650 // take focus if we don't have it already and we should in 5651 // touch mode. 5652 boolean focusTaken = false; 5653 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 5654 focusTaken = requestFocus(); 5655 } 5656 5657 if (prepressed) { 5658 // The button is being released before we actually 5659 // showed it as pressed. Make it show the pressed 5660 // state now (before scheduling the click) to ensure 5661 // the user sees it. 5662 mPrivateFlags |= PRESSED; 5663 refreshDrawableState(); 5664 } 5665 5666 if (!mHasPerformedLongPress) { 5667 // This is a tap, so remove the longpress check 5668 removeLongPressCallback(); 5669 5670 // Only perform take click actions if we were in the pressed state 5671 if (!focusTaken) { 5672 // Use a Runnable and post this rather than calling 5673 // performClick directly. This lets other visual state 5674 // of the view update before click actions start. 5675 if (mPerformClick == null) { 5676 mPerformClick = new PerformClick(); 5677 } 5678 if (!post(mPerformClick)) { 5679 performClick(); 5680 } 5681 } 5682 } 5683 5684 if (mUnsetPressedState == null) { 5685 mUnsetPressedState = new UnsetPressedState(); 5686 } 5687 5688 if (prepressed) { 5689 postDelayed(mUnsetPressedState, 5690 ViewConfiguration.getPressedStateDuration()); 5691 } else if (!post(mUnsetPressedState)) { 5692 // If the post failed, unpress right now 5693 mUnsetPressedState.run(); 5694 } 5695 removeTapCallback(); 5696 } 5697 break; 5698 5699 case MotionEvent.ACTION_DOWN: 5700 mHasPerformedLongPress = false; 5701 5702 if (performButtonActionOnTouchDown(event)) { 5703 break; 5704 } 5705 5706 // Walk up the hierarchy to determine if we're inside a scrolling container. 5707 boolean isInScrollingContainer = false; 5708 ViewParent p = getParent(); 5709 while (p != null && p instanceof ViewGroup) { 5710 if (((ViewGroup) p).shouldDelayChildPressedState()) { 5711 isInScrollingContainer = true; 5712 break; 5713 } 5714 p = p.getParent(); 5715 } 5716 5717 // For views inside a scrolling container, delay the pressed feedback for 5718 // a short period in case this is a scroll. 5719 if (isInScrollingContainer) { 5720 mPrivateFlags |= PREPRESSED; 5721 if (mPendingCheckForTap == null) { 5722 mPendingCheckForTap = new CheckForTap(); 5723 } 5724 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 5725 } else { 5726 // Not inside a scrolling container, so show the feedback right away 5727 mPrivateFlags |= PRESSED; 5728 refreshDrawableState(); 5729 checkForLongClick(0); 5730 } 5731 break; 5732 5733 case MotionEvent.ACTION_CANCEL: 5734 mPrivateFlags &= ~PRESSED; 5735 refreshDrawableState(); 5736 removeTapCallback(); 5737 break; 5738 5739 case MotionEvent.ACTION_MOVE: 5740 final int x = (int) event.getX(); 5741 final int y = (int) event.getY(); 5742 5743 // Be lenient about moving outside of buttons 5744 if (!pointInView(x, y, mTouchSlop)) { 5745 // Outside button 5746 removeTapCallback(); 5747 if ((mPrivateFlags & PRESSED) != 0) { 5748 // Remove any future long press/tap checks 5749 removeLongPressCallback(); 5750 5751 // Need to switch from pressed to not pressed 5752 mPrivateFlags &= ~PRESSED; 5753 refreshDrawableState(); 5754 } 5755 } 5756 break; 5757 } 5758 return true; 5759 } 5760 5761 return false; 5762 } 5763 5764 /** 5765 * Remove the longpress detection timer. 5766 */ 5767 private void removeLongPressCallback() { 5768 if (mPendingCheckForLongPress != null) { 5769 removeCallbacks(mPendingCheckForLongPress); 5770 } 5771 } 5772 5773 /** 5774 * Remove the pending click action 5775 */ 5776 private void removePerformClickCallback() { 5777 if (mPerformClick != null) { 5778 removeCallbacks(mPerformClick); 5779 } 5780 } 5781 5782 /** 5783 * Remove the prepress detection timer. 5784 */ 5785 private void removeUnsetPressCallback() { 5786 if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) { 5787 setPressed(false); 5788 removeCallbacks(mUnsetPressedState); 5789 } 5790 } 5791 5792 /** 5793 * Remove the tap detection timer. 5794 */ 5795 private void removeTapCallback() { 5796 if (mPendingCheckForTap != null) { 5797 mPrivateFlags &= ~PREPRESSED; 5798 removeCallbacks(mPendingCheckForTap); 5799 } 5800 } 5801 5802 /** 5803 * Cancels a pending long press. Your subclass can use this if you 5804 * want the context menu to come up if the user presses and holds 5805 * at the same place, but you don't want it to come up if they press 5806 * and then move around enough to cause scrolling. 5807 */ 5808 public void cancelLongPress() { 5809 removeLongPressCallback(); 5810 5811 /* 5812 * The prepressed state handled by the tap callback is a display 5813 * construct, but the tap callback will post a long press callback 5814 * less its own timeout. Remove it here. 5815 */ 5816 removeTapCallback(); 5817 } 5818 5819 /** 5820 * Sets the TouchDelegate for this View. 5821 */ 5822 public void setTouchDelegate(TouchDelegate delegate) { 5823 mTouchDelegate = delegate; 5824 } 5825 5826 /** 5827 * Gets the TouchDelegate for this View. 5828 */ 5829 public TouchDelegate getTouchDelegate() { 5830 return mTouchDelegate; 5831 } 5832 5833 /** 5834 * Set flags controlling behavior of this view. 5835 * 5836 * @param flags Constant indicating the value which should be set 5837 * @param mask Constant indicating the bit range that should be changed 5838 */ 5839 void setFlags(int flags, int mask) { 5840 int old = mViewFlags; 5841 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 5842 5843 int changed = mViewFlags ^ old; 5844 if (changed == 0) { 5845 return; 5846 } 5847 int privateFlags = mPrivateFlags; 5848 5849 /* Check if the FOCUSABLE bit has changed */ 5850 if (((changed & FOCUSABLE_MASK) != 0) && 5851 ((privateFlags & HAS_BOUNDS) !=0)) { 5852 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 5853 && ((privateFlags & FOCUSED) != 0)) { 5854 /* Give up focus if we are no longer focusable */ 5855 clearFocus(); 5856 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 5857 && ((privateFlags & FOCUSED) == 0)) { 5858 /* 5859 * Tell the view system that we are now available to take focus 5860 * if no one else already has it. 5861 */ 5862 if (mParent != null) mParent.focusableViewAvailable(this); 5863 } 5864 } 5865 5866 if ((flags & VISIBILITY_MASK) == VISIBLE) { 5867 if ((changed & VISIBILITY_MASK) != 0) { 5868 /* 5869 * If this view is becoming visible, set the DRAWN flag so that 5870 * the next invalidate() will not be skipped. 5871 */ 5872 mPrivateFlags |= DRAWN; 5873 5874 needGlobalAttributesUpdate(true); 5875 5876 // a view becoming visible is worth notifying the parent 5877 // about in case nothing has focus. even if this specific view 5878 // isn't focusable, it may contain something that is, so let 5879 // the root view try to give this focus if nothing else does. 5880 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 5881 mParent.focusableViewAvailable(this); 5882 } 5883 } 5884 } 5885 5886 /* Check if the GONE bit has changed */ 5887 if ((changed & GONE) != 0) { 5888 needGlobalAttributesUpdate(false); 5889 requestLayout(); 5890 invalidate(true); 5891 5892 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 5893 if (hasFocus()) clearFocus(); 5894 destroyDrawingCache(); 5895 } 5896 if (mAttachInfo != null) { 5897 mAttachInfo.mViewVisibilityChanged = true; 5898 } 5899 } 5900 5901 /* Check if the VISIBLE bit has changed */ 5902 if ((changed & INVISIBLE) != 0) { 5903 needGlobalAttributesUpdate(false); 5904 invalidate(true); 5905 5906 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) { 5907 // root view becoming invisible shouldn't clear focus 5908 if (getRootView() != this) { 5909 clearFocus(); 5910 } 5911 } 5912 if (mAttachInfo != null) { 5913 mAttachInfo.mViewVisibilityChanged = true; 5914 } 5915 } 5916 5917 if ((changed & VISIBILITY_MASK) != 0) { 5918 if (mParent instanceof ViewGroup) { 5919 ((ViewGroup) mParent).onChildVisibilityChanged(this, (flags & VISIBILITY_MASK)); 5920 ((View) mParent).invalidate(true); 5921 } 5922 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK)); 5923 } 5924 5925 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 5926 destroyDrawingCache(); 5927 } 5928 5929 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 5930 destroyDrawingCache(); 5931 mPrivateFlags &= ~DRAWING_CACHE_VALID; 5932 invalidateParentCaches(); 5933 } 5934 5935 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 5936 destroyDrawingCache(); 5937 mPrivateFlags &= ~DRAWING_CACHE_VALID; 5938 } 5939 5940 if ((changed & DRAW_MASK) != 0) { 5941 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 5942 if (mBGDrawable != null) { 5943 mPrivateFlags &= ~SKIP_DRAW; 5944 mPrivateFlags |= ONLY_DRAWS_BACKGROUND; 5945 } else { 5946 mPrivateFlags |= SKIP_DRAW; 5947 } 5948 } else { 5949 mPrivateFlags &= ~SKIP_DRAW; 5950 } 5951 requestLayout(); 5952 invalidate(true); 5953 } 5954 5955 if ((changed & KEEP_SCREEN_ON) != 0) { 5956 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 5957 mParent.recomputeViewAttributes(this); 5958 } 5959 } 5960 5961 if ((changed & HORIZONTAL_DIRECTION_MASK) != 0) { 5962 requestLayout(); 5963 } 5964 } 5965 5966 /** 5967 * Change the view's z order in the tree, so it's on top of other sibling 5968 * views 5969 */ 5970 public void bringToFront() { 5971 if (mParent != null) { 5972 mParent.bringChildToFront(this); 5973 } 5974 } 5975 5976 /** 5977 * This is called in response to an internal scroll in this view (i.e., the 5978 * view scrolled its own contents). This is typically as a result of 5979 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 5980 * called. 5981 * 5982 * @param l Current horizontal scroll origin. 5983 * @param t Current vertical scroll origin. 5984 * @param oldl Previous horizontal scroll origin. 5985 * @param oldt Previous vertical scroll origin. 5986 */ 5987 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 5988 mBackgroundSizeChanged = true; 5989 5990 final AttachInfo ai = mAttachInfo; 5991 if (ai != null) { 5992 ai.mViewScrollChanged = true; 5993 } 5994 } 5995 5996 /** 5997 * Interface definition for a callback to be invoked when the layout bounds of a view 5998 * changes due to layout processing. 5999 */ 6000 public interface OnLayoutChangeListener { 6001 /** 6002 * Called when the focus state of a view has changed. 6003 * 6004 * @param v The view whose state has changed. 6005 * @param left The new value of the view's left property. 6006 * @param top The new value of the view's top property. 6007 * @param right The new value of the view's right property. 6008 * @param bottom The new value of the view's bottom property. 6009 * @param oldLeft The previous value of the view's left property. 6010 * @param oldTop The previous value of the view's top property. 6011 * @param oldRight The previous value of the view's right property. 6012 * @param oldBottom The previous value of the view's bottom property. 6013 */ 6014 void onLayoutChange(View v, int left, int top, int right, int bottom, 6015 int oldLeft, int oldTop, int oldRight, int oldBottom); 6016 } 6017 6018 /** 6019 * This is called during layout when the size of this view has changed. If 6020 * you were just added to the view hierarchy, you're called with the old 6021 * values of 0. 6022 * 6023 * @param w Current width of this view. 6024 * @param h Current height of this view. 6025 * @param oldw Old width of this view. 6026 * @param oldh Old height of this view. 6027 */ 6028 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 6029 } 6030 6031 /** 6032 * Called by draw to draw the child views. This may be overridden 6033 * by derived classes to gain control just before its children are drawn 6034 * (but after its own view has been drawn). 6035 * @param canvas the canvas on which to draw the view 6036 */ 6037 protected void dispatchDraw(Canvas canvas) { 6038 } 6039 6040 /** 6041 * Gets the parent of this view. Note that the parent is a 6042 * ViewParent and not necessarily a View. 6043 * 6044 * @return Parent of this view. 6045 */ 6046 public final ViewParent getParent() { 6047 return mParent; 6048 } 6049 6050 /** 6051 * Return the scrolled left position of this view. This is the left edge of 6052 * the displayed part of your view. You do not need to draw any pixels 6053 * farther left, since those are outside of the frame of your view on 6054 * screen. 6055 * 6056 * @return The left edge of the displayed part of your view, in pixels. 6057 */ 6058 public final int getScrollX() { 6059 return mScrollX; 6060 } 6061 6062 /** 6063 * Return the scrolled top position of this view. This is the top edge of 6064 * the displayed part of your view. You do not need to draw any pixels above 6065 * it, since those are outside of the frame of your view on screen. 6066 * 6067 * @return The top edge of the displayed part of your view, in pixels. 6068 */ 6069 public final int getScrollY() { 6070 return mScrollY; 6071 } 6072 6073 /** 6074 * Return the width of the your view. 6075 * 6076 * @return The width of your view, in pixels. 6077 */ 6078 @ViewDebug.ExportedProperty(category = "layout") 6079 public final int getWidth() { 6080 return mRight - mLeft; 6081 } 6082 6083 /** 6084 * Return the height of your view. 6085 * 6086 * @return The height of your view, in pixels. 6087 */ 6088 @ViewDebug.ExportedProperty(category = "layout") 6089 public final int getHeight() { 6090 return mBottom - mTop; 6091 } 6092 6093 /** 6094 * Return the visible drawing bounds of your view. Fills in the output 6095 * rectangle with the values from getScrollX(), getScrollY(), 6096 * getWidth(), and getHeight(). 6097 * 6098 * @param outRect The (scrolled) drawing bounds of the view. 6099 */ 6100 public void getDrawingRect(Rect outRect) { 6101 outRect.left = mScrollX; 6102 outRect.top = mScrollY; 6103 outRect.right = mScrollX + (mRight - mLeft); 6104 outRect.bottom = mScrollY + (mBottom - mTop); 6105 } 6106 6107 /** 6108 * Like {@link #getMeasuredWidthAndState()}, but only returns the 6109 * raw width component (that is the result is masked by 6110 * {@link #MEASURED_SIZE_MASK}). 6111 * 6112 * @return The raw measured width of this view. 6113 */ 6114 public final int getMeasuredWidth() { 6115 return mMeasuredWidth & MEASURED_SIZE_MASK; 6116 } 6117 6118 /** 6119 * Return the full width measurement information for this view as computed 6120 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 6121 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 6122 * This should be used during measurement and layout calculations only. Use 6123 * {@link #getWidth()} to see how wide a view is after layout. 6124 * 6125 * @return The measured width of this view as a bit mask. 6126 */ 6127 public final int getMeasuredWidthAndState() { 6128 return mMeasuredWidth; 6129 } 6130 6131 /** 6132 * Like {@link #getMeasuredHeightAndState()}, but only returns the 6133 * raw width component (that is the result is masked by 6134 * {@link #MEASURED_SIZE_MASK}). 6135 * 6136 * @return The raw measured height of this view. 6137 */ 6138 public final int getMeasuredHeight() { 6139 return mMeasuredHeight & MEASURED_SIZE_MASK; 6140 } 6141 6142 /** 6143 * Return the full height measurement information for this view as computed 6144 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 6145 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 6146 * This should be used during measurement and layout calculations only. Use 6147 * {@link #getHeight()} to see how wide a view is after layout. 6148 * 6149 * @return The measured width of this view as a bit mask. 6150 */ 6151 public final int getMeasuredHeightAndState() { 6152 return mMeasuredHeight; 6153 } 6154 6155 /** 6156 * Return only the state bits of {@link #getMeasuredWidthAndState()} 6157 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 6158 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 6159 * and the height component is at the shifted bits 6160 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 6161 */ 6162 public final int getMeasuredState() { 6163 return (mMeasuredWidth&MEASURED_STATE_MASK) 6164 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 6165 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 6166 } 6167 6168 /** 6169 * The transform matrix of this view, which is calculated based on the current 6170 * roation, scale, and pivot properties. 6171 * 6172 * @see #getRotation() 6173 * @see #getScaleX() 6174 * @see #getScaleY() 6175 * @see #getPivotX() 6176 * @see #getPivotY() 6177 * @return The current transform matrix for the view 6178 */ 6179 public Matrix getMatrix() { 6180 updateMatrix(); 6181 return mMatrix; 6182 } 6183 6184 /** 6185 * Utility function to determine if the value is far enough away from zero to be 6186 * considered non-zero. 6187 * @param value A floating point value to check for zero-ness 6188 * @return whether the passed-in value is far enough away from zero to be considered non-zero 6189 */ 6190 private static boolean nonzero(float value) { 6191 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON); 6192 } 6193 6194 /** 6195 * Returns true if the transform matrix is the identity matrix. 6196 * Recomputes the matrix if necessary. 6197 * 6198 * @return True if the transform matrix is the identity matrix, false otherwise. 6199 */ 6200 final boolean hasIdentityMatrix() { 6201 updateMatrix(); 6202 return mMatrixIsIdentity; 6203 } 6204 6205 /** 6206 * Recomputes the transform matrix if necessary. 6207 */ 6208 private void updateMatrix() { 6209 if (mMatrixDirty) { 6210 // transform-related properties have changed since the last time someone 6211 // asked for the matrix; recalculate it with the current values 6212 6213 // Figure out if we need to update the pivot point 6214 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 6215 if ((mRight - mLeft) != mPrevWidth || (mBottom - mTop) != mPrevHeight) { 6216 mPrevWidth = mRight - mLeft; 6217 mPrevHeight = mBottom - mTop; 6218 mPivotX = mPrevWidth / 2f; 6219 mPivotY = mPrevHeight / 2f; 6220 } 6221 } 6222 mMatrix.reset(); 6223 if (!nonzero(mRotationX) && !nonzero(mRotationY)) { 6224 mMatrix.setTranslate(mTranslationX, mTranslationY); 6225 mMatrix.preRotate(mRotation, mPivotX, mPivotY); 6226 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY); 6227 } else { 6228 if (mCamera == null) { 6229 mCamera = new Camera(); 6230 matrix3D = new Matrix(); 6231 } 6232 mCamera.save(); 6233 mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY); 6234 mCamera.rotate(mRotationX, mRotationY, -mRotation); 6235 mCamera.getMatrix(matrix3D); 6236 matrix3D.preTranslate(-mPivotX, -mPivotY); 6237 matrix3D.postTranslate(mPivotX + mTranslationX, mPivotY + mTranslationY); 6238 mMatrix.postConcat(matrix3D); 6239 mCamera.restore(); 6240 } 6241 mMatrixDirty = false; 6242 mMatrixIsIdentity = mMatrix.isIdentity(); 6243 mInverseMatrixDirty = true; 6244 } 6245 } 6246 6247 /** 6248 * Utility method to retrieve the inverse of the current mMatrix property. 6249 * We cache the matrix to avoid recalculating it when transform properties 6250 * have not changed. 6251 * 6252 * @return The inverse of the current matrix of this view. 6253 */ 6254 final Matrix getInverseMatrix() { 6255 updateMatrix(); 6256 if (mInverseMatrixDirty) { 6257 if (mInverseMatrix == null) { 6258 mInverseMatrix = new Matrix(); 6259 } 6260 mMatrix.invert(mInverseMatrix); 6261 mInverseMatrixDirty = false; 6262 } 6263 return mInverseMatrix; 6264 } 6265 6266 /** 6267 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 6268 * views are drawn) from the camera to this view. The camera's distance 6269 * affects 3D transformations, for instance rotations around the X and Y 6270 * axis. If the rotationX or rotationY properties are changed and this view is 6271 * large (more than half the size of the screen), it is recommended to always 6272 * use a camera distance that's greater than the height (X axis rotation) or 6273 * the width (Y axis rotation) of this view.</p> 6274 * 6275 * <p>The distance of the camera from the view plane can have an affect on the 6276 * perspective distortion of the view when it is rotated around the x or y axis. 6277 * For example, a large distance will result in a large viewing angle, and there 6278 * will not be much perspective distortion of the view as it rotates. A short 6279 * distance may cause much more perspective distortion upon rotation, and can 6280 * also result in some drawing artifacts if the rotated view ends up partially 6281 * behind the camera (which is why the recommendation is to use a distance at 6282 * least as far as the size of the view, if the view is to be rotated.)</p> 6283 * 6284 * <p>The distance is expressed in "depth pixels." The default distance depends 6285 * on the screen density. For instance, on a medium density display, the 6286 * default distance is 1280. On a high density display, the default distance 6287 * is 1920.</p> 6288 * 6289 * <p>If you want to specify a distance that leads to visually consistent 6290 * results across various densities, use the following formula:</p> 6291 * <pre> 6292 * float scale = context.getResources().getDisplayMetrics().density; 6293 * view.setCameraDistance(distance * scale); 6294 * </pre> 6295 * 6296 * <p>The density scale factor of a high density display is 1.5, 6297 * and 1920 = 1280 * 1.5.</p> 6298 * 6299 * @param distance The distance in "depth pixels", if negative the opposite 6300 * value is used 6301 * 6302 * @see #setRotationX(float) 6303 * @see #setRotationY(float) 6304 */ 6305 public void setCameraDistance(float distance) { 6306 invalidateParentCaches(); 6307 invalidate(false); 6308 6309 final float dpi = mResources.getDisplayMetrics().densityDpi; 6310 if (mCamera == null) { 6311 mCamera = new Camera(); 6312 matrix3D = new Matrix(); 6313 } 6314 6315 mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi); 6316 mMatrixDirty = true; 6317 6318 invalidate(false); 6319 } 6320 6321 /** 6322 * The degrees that the view is rotated around the pivot point. 6323 * 6324 * @see #setRotation(float) 6325 * @see #getPivotX() 6326 * @see #getPivotY() 6327 * 6328 * @return The degrees of rotation. 6329 */ 6330 public float getRotation() { 6331 return mRotation; 6332 } 6333 6334 /** 6335 * Sets the degrees that the view is rotated around the pivot point. Increasing values 6336 * result in clockwise rotation. 6337 * 6338 * @param rotation The degrees of rotation. 6339 * 6340 * @see #getRotation() 6341 * @see #getPivotX() 6342 * @see #getPivotY() 6343 * @see #setRotationX(float) 6344 * @see #setRotationY(float) 6345 * 6346 * @attr ref android.R.styleable#View_rotation 6347 */ 6348 public void setRotation(float rotation) { 6349 if (mRotation != rotation) { 6350 invalidateParentCaches(); 6351 // Double-invalidation is necessary to capture view's old and new areas 6352 invalidate(false); 6353 mRotation = rotation; 6354 mMatrixDirty = true; 6355 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6356 invalidate(false); 6357 } 6358 } 6359 6360 /** 6361 * The degrees that the view is rotated around the vertical axis through the pivot point. 6362 * 6363 * @see #getPivotX() 6364 * @see #getPivotY() 6365 * @see #setRotationY(float) 6366 * 6367 * @return The degrees of Y rotation. 6368 */ 6369 public float getRotationY() { 6370 return mRotationY; 6371 } 6372 6373 /** 6374 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 6375 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 6376 * down the y axis. 6377 * 6378 * When rotating large views, it is recommended to adjust the camera distance 6379 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 6380 * 6381 * @param rotationY The degrees of Y rotation. 6382 * 6383 * @see #getRotationY() 6384 * @see #getPivotX() 6385 * @see #getPivotY() 6386 * @see #setRotation(float) 6387 * @see #setRotationX(float) 6388 * @see #setCameraDistance(float) 6389 * 6390 * @attr ref android.R.styleable#View_rotationY 6391 */ 6392 public void setRotationY(float rotationY) { 6393 if (mRotationY != rotationY) { 6394 invalidateParentCaches(); 6395 // Double-invalidation is necessary to capture view's old and new areas 6396 invalidate(false); 6397 mRotationY = rotationY; 6398 mMatrixDirty = true; 6399 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6400 invalidate(false); 6401 } 6402 } 6403 6404 /** 6405 * The degrees that the view is rotated around the horizontal axis through the pivot point. 6406 * 6407 * @see #getPivotX() 6408 * @see #getPivotY() 6409 * @see #setRotationX(float) 6410 * 6411 * @return The degrees of X rotation. 6412 */ 6413 public float getRotationX() { 6414 return mRotationX; 6415 } 6416 6417 /** 6418 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 6419 * Increasing values result in clockwise rotation from the viewpoint of looking down the 6420 * x axis. 6421 * 6422 * When rotating large views, it is recommended to adjust the camera distance 6423 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 6424 * 6425 * @param rotationX The degrees of X rotation. 6426 * 6427 * @see #getRotationX() 6428 * @see #getPivotX() 6429 * @see #getPivotY() 6430 * @see #setRotation(float) 6431 * @see #setRotationY(float) 6432 * @see #setCameraDistance(float) 6433 * 6434 * @attr ref android.R.styleable#View_rotationX 6435 */ 6436 public void setRotationX(float rotationX) { 6437 if (mRotationX != rotationX) { 6438 invalidateParentCaches(); 6439 // Double-invalidation is necessary to capture view's old and new areas 6440 invalidate(false); 6441 mRotationX = rotationX; 6442 mMatrixDirty = true; 6443 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6444 invalidate(false); 6445 } 6446 } 6447 6448 /** 6449 * The amount that the view is scaled in x around the pivot point, as a proportion of 6450 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 6451 * 6452 * <p>By default, this is 1.0f. 6453 * 6454 * @see #getPivotX() 6455 * @see #getPivotY() 6456 * @return The scaling factor. 6457 */ 6458 public float getScaleX() { 6459 return mScaleX; 6460 } 6461 6462 /** 6463 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 6464 * the view's unscaled width. A value of 1 means that no scaling is applied. 6465 * 6466 * @param scaleX The scaling factor. 6467 * @see #getPivotX() 6468 * @see #getPivotY() 6469 * 6470 * @attr ref android.R.styleable#View_scaleX 6471 */ 6472 public void setScaleX(float scaleX) { 6473 if (mScaleX != scaleX) { 6474 invalidateParentCaches(); 6475 // Double-invalidation is necessary to capture view's old and new areas 6476 invalidate(false); 6477 mScaleX = scaleX; 6478 mMatrixDirty = true; 6479 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6480 invalidate(false); 6481 } 6482 } 6483 6484 /** 6485 * The amount that the view is scaled in y around the pivot point, as a proportion of 6486 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 6487 * 6488 * <p>By default, this is 1.0f. 6489 * 6490 * @see #getPivotX() 6491 * @see #getPivotY() 6492 * @return The scaling factor. 6493 */ 6494 public float getScaleY() { 6495 return mScaleY; 6496 } 6497 6498 /** 6499 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 6500 * the view's unscaled width. A value of 1 means that no scaling is applied. 6501 * 6502 * @param scaleY The scaling factor. 6503 * @see #getPivotX() 6504 * @see #getPivotY() 6505 * 6506 * @attr ref android.R.styleable#View_scaleY 6507 */ 6508 public void setScaleY(float scaleY) { 6509 if (mScaleY != scaleY) { 6510 invalidateParentCaches(); 6511 // Double-invalidation is necessary to capture view's old and new areas 6512 invalidate(false); 6513 mScaleY = scaleY; 6514 mMatrixDirty = true; 6515 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6516 invalidate(false); 6517 } 6518 } 6519 6520 /** 6521 * The x location of the point around which the view is {@link #setRotation(float) rotated} 6522 * and {@link #setScaleX(float) scaled}. 6523 * 6524 * @see #getRotation() 6525 * @see #getScaleX() 6526 * @see #getScaleY() 6527 * @see #getPivotY() 6528 * @return The x location of the pivot point. 6529 */ 6530 public float getPivotX() { 6531 return mPivotX; 6532 } 6533 6534 /** 6535 * Sets the x location of the point around which the view is 6536 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 6537 * By default, the pivot point is centered on the object. 6538 * Setting this property disables this behavior and causes the view to use only the 6539 * explicitly set pivotX and pivotY values. 6540 * 6541 * @param pivotX The x location of the pivot point. 6542 * @see #getRotation() 6543 * @see #getScaleX() 6544 * @see #getScaleY() 6545 * @see #getPivotY() 6546 * 6547 * @attr ref android.R.styleable#View_transformPivotX 6548 */ 6549 public void setPivotX(float pivotX) { 6550 mPrivateFlags |= PIVOT_EXPLICITLY_SET; 6551 if (mPivotX != pivotX) { 6552 invalidateParentCaches(); 6553 // Double-invalidation is necessary to capture view's old and new areas 6554 invalidate(false); 6555 mPivotX = pivotX; 6556 mMatrixDirty = true; 6557 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6558 invalidate(false); 6559 } 6560 } 6561 6562 /** 6563 * The y location of the point around which the view is {@link #setRotation(float) rotated} 6564 * and {@link #setScaleY(float) scaled}. 6565 * 6566 * @see #getRotation() 6567 * @see #getScaleX() 6568 * @see #getScaleY() 6569 * @see #getPivotY() 6570 * @return The y location of the pivot point. 6571 */ 6572 public float getPivotY() { 6573 return mPivotY; 6574 } 6575 6576 /** 6577 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 6578 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 6579 * Setting this property disables this behavior and causes the view to use only the 6580 * explicitly set pivotX and pivotY values. 6581 * 6582 * @param pivotY The y location of the pivot point. 6583 * @see #getRotation() 6584 * @see #getScaleX() 6585 * @see #getScaleY() 6586 * @see #getPivotY() 6587 * 6588 * @attr ref android.R.styleable#View_transformPivotY 6589 */ 6590 public void setPivotY(float pivotY) { 6591 mPrivateFlags |= PIVOT_EXPLICITLY_SET; 6592 if (mPivotY != pivotY) { 6593 invalidateParentCaches(); 6594 // Double-invalidation is necessary to capture view's old and new areas 6595 invalidate(false); 6596 mPivotY = pivotY; 6597 mMatrixDirty = true; 6598 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6599 invalidate(false); 6600 } 6601 } 6602 6603 /** 6604 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 6605 * completely transparent and 1 means the view is completely opaque. 6606 * 6607 * <p>By default this is 1.0f. 6608 * @return The opacity of the view. 6609 */ 6610 public float getAlpha() { 6611 return mAlpha; 6612 } 6613 6614 /** 6615 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 6616 * completely transparent and 1 means the view is completely opaque.</p> 6617 * 6618 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 6619 * responsible for applying the opacity itself. Otherwise, calling this method is 6620 * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and 6621 * setting a hardware layer.</p> 6622 * 6623 * @param alpha The opacity of the view. 6624 * 6625 * @see #setLayerType(int, android.graphics.Paint) 6626 * 6627 * @attr ref android.R.styleable#View_alpha 6628 */ 6629 public void setAlpha(float alpha) { 6630 mAlpha = alpha; 6631 invalidateParentCaches(); 6632 if (onSetAlpha((int) (alpha * 255))) { 6633 mPrivateFlags |= ALPHA_SET; 6634 // subclass is handling alpha - don't optimize rendering cache invalidation 6635 invalidate(true); 6636 } else { 6637 mPrivateFlags &= ~ALPHA_SET; 6638 invalidate(false); 6639 } 6640 } 6641 6642 /** 6643 * Faster version of setAlpha() which performs the same steps except there are 6644 * no calls to invalidate(). The caller of this function should perform proper invalidation 6645 * on the parent and this object. The return value indicates whether the subclass handles 6646 * alpha (the return value for onSetAlpha()). 6647 * 6648 * @param alpha The new value for the alpha property 6649 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) 6650 */ 6651 boolean setAlphaNoInvalidation(float alpha) { 6652 mAlpha = alpha; 6653 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 6654 if (subclassHandlesAlpha) { 6655 mPrivateFlags |= ALPHA_SET; 6656 } else { 6657 mPrivateFlags &= ~ALPHA_SET; 6658 } 6659 return subclassHandlesAlpha; 6660 } 6661 6662 /** 6663 * Top position of this view relative to its parent. 6664 * 6665 * @return The top of this view, in pixels. 6666 */ 6667 @ViewDebug.CapturedViewProperty 6668 public final int getTop() { 6669 return mTop; 6670 } 6671 6672 /** 6673 * Sets the top position of this view relative to its parent. This method is meant to be called 6674 * by the layout system and should not generally be called otherwise, because the property 6675 * may be changed at any time by the layout. 6676 * 6677 * @param top The top of this view, in pixels. 6678 */ 6679 public final void setTop(int top) { 6680 if (top != mTop) { 6681 updateMatrix(); 6682 if (mMatrixIsIdentity) { 6683 if (mAttachInfo != null) { 6684 int minTop; 6685 int yLoc; 6686 if (top < mTop) { 6687 minTop = top; 6688 yLoc = top - mTop; 6689 } else { 6690 minTop = mTop; 6691 yLoc = 0; 6692 } 6693 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 6694 } 6695 } else { 6696 // Double-invalidation is necessary to capture view's old and new areas 6697 invalidate(true); 6698 } 6699 6700 int width = mRight - mLeft; 6701 int oldHeight = mBottom - mTop; 6702 6703 mTop = top; 6704 6705 onSizeChanged(width, mBottom - mTop, width, oldHeight); 6706 6707 if (!mMatrixIsIdentity) { 6708 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 6709 // A change in dimension means an auto-centered pivot point changes, too 6710 mMatrixDirty = true; 6711 } 6712 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6713 invalidate(true); 6714 } 6715 mBackgroundSizeChanged = true; 6716 invalidateParentIfNeeded(); 6717 } 6718 } 6719 6720 /** 6721 * Bottom position of this view relative to its parent. 6722 * 6723 * @return The bottom of this view, in pixels. 6724 */ 6725 @ViewDebug.CapturedViewProperty 6726 public final int getBottom() { 6727 return mBottom; 6728 } 6729 6730 /** 6731 * True if this view has changed since the last time being drawn. 6732 * 6733 * @return The dirty state of this view. 6734 */ 6735 public boolean isDirty() { 6736 return (mPrivateFlags & DIRTY_MASK) != 0; 6737 } 6738 6739 /** 6740 * Sets the bottom position of this view relative to its parent. This method is meant to be 6741 * called by the layout system and should not generally be called otherwise, because the 6742 * property may be changed at any time by the layout. 6743 * 6744 * @param bottom The bottom of this view, in pixels. 6745 */ 6746 public final void setBottom(int bottom) { 6747 if (bottom != mBottom) { 6748 updateMatrix(); 6749 if (mMatrixIsIdentity) { 6750 if (mAttachInfo != null) { 6751 int maxBottom; 6752 if (bottom < mBottom) { 6753 maxBottom = mBottom; 6754 } else { 6755 maxBottom = bottom; 6756 } 6757 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 6758 } 6759 } else { 6760 // Double-invalidation is necessary to capture view's old and new areas 6761 invalidate(true); 6762 } 6763 6764 int width = mRight - mLeft; 6765 int oldHeight = mBottom - mTop; 6766 6767 mBottom = bottom; 6768 6769 onSizeChanged(width, mBottom - mTop, width, oldHeight); 6770 6771 if (!mMatrixIsIdentity) { 6772 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 6773 // A change in dimension means an auto-centered pivot point changes, too 6774 mMatrixDirty = true; 6775 } 6776 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6777 invalidate(true); 6778 } 6779 mBackgroundSizeChanged = true; 6780 invalidateParentIfNeeded(); 6781 } 6782 } 6783 6784 /** 6785 * Left position of this view relative to its parent. 6786 * 6787 * @return The left edge of this view, in pixels. 6788 */ 6789 @ViewDebug.CapturedViewProperty 6790 public final int getLeft() { 6791 return mLeft; 6792 } 6793 6794 /** 6795 * Sets the left position of this view relative to its parent. This method is meant to be called 6796 * by the layout system and should not generally be called otherwise, because the property 6797 * may be changed at any time by the layout. 6798 * 6799 * @param left The bottom of this view, in pixels. 6800 */ 6801 public final void setLeft(int left) { 6802 if (left != mLeft) { 6803 updateMatrix(); 6804 if (mMatrixIsIdentity) { 6805 if (mAttachInfo != null) { 6806 int minLeft; 6807 int xLoc; 6808 if (left < mLeft) { 6809 minLeft = left; 6810 xLoc = left - mLeft; 6811 } else { 6812 minLeft = mLeft; 6813 xLoc = 0; 6814 } 6815 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 6816 } 6817 } else { 6818 // Double-invalidation is necessary to capture view's old and new areas 6819 invalidate(true); 6820 } 6821 6822 int oldWidth = mRight - mLeft; 6823 int height = mBottom - mTop; 6824 6825 mLeft = left; 6826 6827 onSizeChanged(mRight - mLeft, height, oldWidth, height); 6828 6829 if (!mMatrixIsIdentity) { 6830 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 6831 // A change in dimension means an auto-centered pivot point changes, too 6832 mMatrixDirty = true; 6833 } 6834 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6835 invalidate(true); 6836 } 6837 mBackgroundSizeChanged = true; 6838 invalidateParentIfNeeded(); 6839 } 6840 } 6841 6842 /** 6843 * Right position of this view relative to its parent. 6844 * 6845 * @return The right edge of this view, in pixels. 6846 */ 6847 @ViewDebug.CapturedViewProperty 6848 public final int getRight() { 6849 return mRight; 6850 } 6851 6852 /** 6853 * Sets the right position of this view relative to its parent. This method is meant to be called 6854 * by the layout system and should not generally be called otherwise, because the property 6855 * may be changed at any time by the layout. 6856 * 6857 * @param right The bottom of this view, in pixels. 6858 */ 6859 public final void setRight(int right) { 6860 if (right != mRight) { 6861 updateMatrix(); 6862 if (mMatrixIsIdentity) { 6863 if (mAttachInfo != null) { 6864 int maxRight; 6865 if (right < mRight) { 6866 maxRight = mRight; 6867 } else { 6868 maxRight = right; 6869 } 6870 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 6871 } 6872 } else { 6873 // Double-invalidation is necessary to capture view's old and new areas 6874 invalidate(true); 6875 } 6876 6877 int oldWidth = mRight - mLeft; 6878 int height = mBottom - mTop; 6879 6880 mRight = right; 6881 6882 onSizeChanged(mRight - mLeft, height, oldWidth, height); 6883 6884 if (!mMatrixIsIdentity) { 6885 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 6886 // A change in dimension means an auto-centered pivot point changes, too 6887 mMatrixDirty = true; 6888 } 6889 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6890 invalidate(true); 6891 } 6892 mBackgroundSizeChanged = true; 6893 invalidateParentIfNeeded(); 6894 } 6895 } 6896 6897 /** 6898 * The visual x position of this view, in pixels. This is equivalent to the 6899 * {@link #setTranslationX(float) translationX} property plus the current 6900 * {@link #getLeft() left} property. 6901 * 6902 * @return The visual x position of this view, in pixels. 6903 */ 6904 public float getX() { 6905 return mLeft + mTranslationX; 6906 } 6907 6908 /** 6909 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 6910 * {@link #setTranslationX(float) translationX} property to be the difference between 6911 * the x value passed in and the current {@link #getLeft() left} property. 6912 * 6913 * @param x The visual x position of this view, in pixels. 6914 */ 6915 public void setX(float x) { 6916 setTranslationX(x - mLeft); 6917 } 6918 6919 /** 6920 * The visual y position of this view, in pixels. This is equivalent to the 6921 * {@link #setTranslationY(float) translationY} property plus the current 6922 * {@link #getTop() top} property. 6923 * 6924 * @return The visual y position of this view, in pixels. 6925 */ 6926 public float getY() { 6927 return mTop + mTranslationY; 6928 } 6929 6930 /** 6931 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 6932 * {@link #setTranslationY(float) translationY} property to be the difference between 6933 * the y value passed in and the current {@link #getTop() top} property. 6934 * 6935 * @param y The visual y position of this view, in pixels. 6936 */ 6937 public void setY(float y) { 6938 setTranslationY(y - mTop); 6939 } 6940 6941 6942 /** 6943 * The horizontal location of this view relative to its {@link #getLeft() left} position. 6944 * This position is post-layout, in addition to wherever the object's 6945 * layout placed it. 6946 * 6947 * @return The horizontal position of this view relative to its left position, in pixels. 6948 */ 6949 public float getTranslationX() { 6950 return mTranslationX; 6951 } 6952 6953 /** 6954 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 6955 * This effectively positions the object post-layout, in addition to wherever the object's 6956 * layout placed it. 6957 * 6958 * @param translationX The horizontal position of this view relative to its left position, 6959 * in pixels. 6960 * 6961 * @attr ref android.R.styleable#View_translationX 6962 */ 6963 public void setTranslationX(float translationX) { 6964 if (mTranslationX != translationX) { 6965 invalidateParentCaches(); 6966 // Double-invalidation is necessary to capture view's old and new areas 6967 invalidate(false); 6968 mTranslationX = translationX; 6969 mMatrixDirty = true; 6970 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 6971 invalidate(false); 6972 } 6973 } 6974 6975 /** 6976 * The horizontal location of this view relative to its {@link #getTop() top} position. 6977 * This position is post-layout, in addition to wherever the object's 6978 * layout placed it. 6979 * 6980 * @return The vertical position of this view relative to its top position, 6981 * in pixels. 6982 */ 6983 public float getTranslationY() { 6984 return mTranslationY; 6985 } 6986 6987 /** 6988 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 6989 * This effectively positions the object post-layout, in addition to wherever the object's 6990 * layout placed it. 6991 * 6992 * @param translationY The vertical position of this view relative to its top position, 6993 * in pixels. 6994 * 6995 * @attr ref android.R.styleable#View_translationY 6996 */ 6997 public void setTranslationY(float translationY) { 6998 if (mTranslationY != translationY) { 6999 invalidateParentCaches(); 7000 // Double-invalidation is necessary to capture view's old and new areas 7001 invalidate(false); 7002 mTranslationY = translationY; 7003 mMatrixDirty = true; 7004 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7005 invalidate(false); 7006 } 7007 } 7008 7009 /** 7010 * @hide 7011 */ 7012 public void setFastTranslationX(float x) { 7013 mTranslationX = x; 7014 mMatrixDirty = true; 7015 } 7016 7017 /** 7018 * @hide 7019 */ 7020 public void setFastTranslationY(float y) { 7021 mTranslationY = y; 7022 mMatrixDirty = true; 7023 } 7024 7025 /** 7026 * @hide 7027 */ 7028 public void setFastX(float x) { 7029 mTranslationX = x - mLeft; 7030 mMatrixDirty = true; 7031 } 7032 7033 /** 7034 * @hide 7035 */ 7036 public void setFastY(float y) { 7037 mTranslationY = y - mTop; 7038 mMatrixDirty = true; 7039 } 7040 7041 /** 7042 * @hide 7043 */ 7044 public void setFastScaleX(float x) { 7045 mScaleX = x; 7046 mMatrixDirty = true; 7047 } 7048 7049 /** 7050 * @hide 7051 */ 7052 public void setFastScaleY(float y) { 7053 mScaleY = y; 7054 mMatrixDirty = true; 7055 } 7056 7057 /** 7058 * @hide 7059 */ 7060 public void setFastAlpha(float alpha) { 7061 mAlpha = alpha; 7062 } 7063 7064 /** 7065 * @hide 7066 */ 7067 public void setFastRotationY(float y) { 7068 mRotationY = y; 7069 mMatrixDirty = true; 7070 } 7071 7072 /** 7073 * Hit rectangle in parent's coordinates 7074 * 7075 * @param outRect The hit rectangle of the view. 7076 */ 7077 public void getHitRect(Rect outRect) { 7078 updateMatrix(); 7079 if (mMatrixIsIdentity || mAttachInfo == null) { 7080 outRect.set(mLeft, mTop, mRight, mBottom); 7081 } else { 7082 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 7083 tmpRect.set(-mPivotX, -mPivotY, getWidth() - mPivotX, getHeight() - mPivotY); 7084 mMatrix.mapRect(tmpRect); 7085 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 7086 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 7087 } 7088 } 7089 7090 /** 7091 * Determines whether the given point, in local coordinates is inside the view. 7092 */ 7093 /*package*/ final boolean pointInView(float localX, float localY) { 7094 return localX >= 0 && localX < (mRight - mLeft) 7095 && localY >= 0 && localY < (mBottom - mTop); 7096 } 7097 7098 /** 7099 * Utility method to determine whether the given point, in local coordinates, 7100 * is inside the view, where the area of the view is expanded by the slop factor. 7101 * This method is called while processing touch-move events to determine if the event 7102 * is still within the view. 7103 */ 7104 private boolean pointInView(float localX, float localY, float slop) { 7105 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 7106 localY < ((mBottom - mTop) + slop); 7107 } 7108 7109 /** 7110 * When a view has focus and the user navigates away from it, the next view is searched for 7111 * starting from the rectangle filled in by this method. 7112 * 7113 * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)}) 7114 * of the view. However, if your view maintains some idea of internal selection, 7115 * such as a cursor, or a selected row or column, you should override this method and 7116 * fill in a more specific rectangle. 7117 * 7118 * @param r The rectangle to fill in, in this view's coordinates. 7119 */ 7120 public void getFocusedRect(Rect r) { 7121 getDrawingRect(r); 7122 } 7123 7124 /** 7125 * If some part of this view is not clipped by any of its parents, then 7126 * return that area in r in global (root) coordinates. To convert r to local 7127 * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x, 7128 * -globalOffset.y)) If the view is completely clipped or translated out, 7129 * return false. 7130 * 7131 * @param r If true is returned, r holds the global coordinates of the 7132 * visible portion of this view. 7133 * @param globalOffset If true is returned, globalOffset holds the dx,dy 7134 * between this view and its root. globalOffet may be null. 7135 * @return true if r is non-empty (i.e. part of the view is visible at the 7136 * root level. 7137 */ 7138 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 7139 int width = mRight - mLeft; 7140 int height = mBottom - mTop; 7141 if (width > 0 && height > 0) { 7142 r.set(0, 0, width, height); 7143 if (globalOffset != null) { 7144 globalOffset.set(-mScrollX, -mScrollY); 7145 } 7146 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 7147 } 7148 return false; 7149 } 7150 7151 public final boolean getGlobalVisibleRect(Rect r) { 7152 return getGlobalVisibleRect(r, null); 7153 } 7154 7155 public final boolean getLocalVisibleRect(Rect r) { 7156 Point offset = new Point(); 7157 if (getGlobalVisibleRect(r, offset)) { 7158 r.offset(-offset.x, -offset.y); // make r local 7159 return true; 7160 } 7161 return false; 7162 } 7163 7164 /** 7165 * Offset this view's vertical location by the specified number of pixels. 7166 * 7167 * @param offset the number of pixels to offset the view by 7168 */ 7169 public void offsetTopAndBottom(int offset) { 7170 if (offset != 0) { 7171 updateMatrix(); 7172 if (mMatrixIsIdentity) { 7173 final ViewParent p = mParent; 7174 if (p != null && mAttachInfo != null) { 7175 final Rect r = mAttachInfo.mTmpInvalRect; 7176 int minTop; 7177 int maxBottom; 7178 int yLoc; 7179 if (offset < 0) { 7180 minTop = mTop + offset; 7181 maxBottom = mBottom; 7182 yLoc = offset; 7183 } else { 7184 minTop = mTop; 7185 maxBottom = mBottom + offset; 7186 yLoc = 0; 7187 } 7188 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 7189 p.invalidateChild(this, r); 7190 } 7191 } else { 7192 invalidate(false); 7193 } 7194 7195 mTop += offset; 7196 mBottom += offset; 7197 7198 if (!mMatrixIsIdentity) { 7199 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7200 invalidate(false); 7201 } 7202 invalidateParentIfNeeded(); 7203 } 7204 } 7205 7206 /** 7207 * Offset this view's horizontal location by the specified amount of pixels. 7208 * 7209 * @param offset the numer of pixels to offset the view by 7210 */ 7211 public void offsetLeftAndRight(int offset) { 7212 if (offset != 0) { 7213 updateMatrix(); 7214 if (mMatrixIsIdentity) { 7215 final ViewParent p = mParent; 7216 if (p != null && mAttachInfo != null) { 7217 final Rect r = mAttachInfo.mTmpInvalRect; 7218 int minLeft; 7219 int maxRight; 7220 if (offset < 0) { 7221 minLeft = mLeft + offset; 7222 maxRight = mRight; 7223 } else { 7224 minLeft = mLeft; 7225 maxRight = mRight + offset; 7226 } 7227 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 7228 p.invalidateChild(this, r); 7229 } 7230 } else { 7231 invalidate(false); 7232 } 7233 7234 mLeft += offset; 7235 mRight += offset; 7236 7237 if (!mMatrixIsIdentity) { 7238 mPrivateFlags |= DRAWN; // force another invalidation with the new orientation 7239 invalidate(false); 7240 } 7241 invalidateParentIfNeeded(); 7242 } 7243 } 7244 7245 /** 7246 * Get the LayoutParams associated with this view. All views should have 7247 * layout parameters. These supply parameters to the <i>parent</i> of this 7248 * view specifying how it should be arranged. There are many subclasses of 7249 * ViewGroup.LayoutParams, and these correspond to the different subclasses 7250 * of ViewGroup that are responsible for arranging their children. 7251 * 7252 * This method may return null if this View is not attached to a parent 7253 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 7254 * was not invoked successfully. When a View is attached to a parent 7255 * ViewGroup, this method must not return null. 7256 * 7257 * @return The LayoutParams associated with this view, or null if no 7258 * parameters have been set yet 7259 */ 7260 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 7261 public ViewGroup.LayoutParams getLayoutParams() { 7262 return mLayoutParams; 7263 } 7264 7265 /** 7266 * Set the layout parameters associated with this view. These supply 7267 * parameters to the <i>parent</i> of this view specifying how it should be 7268 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 7269 * correspond to the different subclasses of ViewGroup that are responsible 7270 * for arranging their children. 7271 * 7272 * @param params The layout parameters for this view, cannot be null 7273 */ 7274 public void setLayoutParams(ViewGroup.LayoutParams params) { 7275 if (params == null) { 7276 throw new NullPointerException("Layout parameters cannot be null"); 7277 } 7278 mLayoutParams = params; 7279 requestLayout(); 7280 } 7281 7282 /** 7283 * Set the scrolled position of your view. This will cause a call to 7284 * {@link #onScrollChanged(int, int, int, int)} and the view will be 7285 * invalidated. 7286 * @param x the x position to scroll to 7287 * @param y the y position to scroll to 7288 */ 7289 public void scrollTo(int x, int y) { 7290 if (mScrollX != x || mScrollY != y) { 7291 int oldX = mScrollX; 7292 int oldY = mScrollY; 7293 mScrollX = x; 7294 mScrollY = y; 7295 invalidateParentCaches(); 7296 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 7297 if (!awakenScrollBars()) { 7298 invalidate(true); 7299 } 7300 } 7301 } 7302 7303 /** 7304 * Move the scrolled position of your view. This will cause a call to 7305 * {@link #onScrollChanged(int, int, int, int)} and the view will be 7306 * invalidated. 7307 * @param x the amount of pixels to scroll by horizontally 7308 * @param y the amount of pixels to scroll by vertically 7309 */ 7310 public void scrollBy(int x, int y) { 7311 scrollTo(mScrollX + x, mScrollY + y); 7312 } 7313 7314 /** 7315 * <p>Trigger the scrollbars to draw. When invoked this method starts an 7316 * animation to fade the scrollbars out after a default delay. If a subclass 7317 * provides animated scrolling, the start delay should equal the duration 7318 * of the scrolling animation.</p> 7319 * 7320 * <p>The animation starts only if at least one of the scrollbars is 7321 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 7322 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 7323 * this method returns true, and false otherwise. If the animation is 7324 * started, this method calls {@link #invalidate()}; in that case the 7325 * caller should not call {@link #invalidate()}.</p> 7326 * 7327 * <p>This method should be invoked every time a subclass directly updates 7328 * the scroll parameters.</p> 7329 * 7330 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 7331 * and {@link #scrollTo(int, int)}.</p> 7332 * 7333 * @return true if the animation is played, false otherwise 7334 * 7335 * @see #awakenScrollBars(int) 7336 * @see #scrollBy(int, int) 7337 * @see #scrollTo(int, int) 7338 * @see #isHorizontalScrollBarEnabled() 7339 * @see #isVerticalScrollBarEnabled() 7340 * @see #setHorizontalScrollBarEnabled(boolean) 7341 * @see #setVerticalScrollBarEnabled(boolean) 7342 */ 7343 protected boolean awakenScrollBars() { 7344 return mScrollCache != null && 7345 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 7346 } 7347 7348 /** 7349 * Trigger the scrollbars to draw. 7350 * This method differs from awakenScrollBars() only in its default duration. 7351 * initialAwakenScrollBars() will show the scroll bars for longer than 7352 * usual to give the user more of a chance to notice them. 7353 * 7354 * @return true if the animation is played, false otherwise. 7355 */ 7356 private boolean initialAwakenScrollBars() { 7357 return mScrollCache != null && 7358 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 7359 } 7360 7361 /** 7362 * <p> 7363 * Trigger the scrollbars to draw. When invoked this method starts an 7364 * animation to fade the scrollbars out after a fixed delay. If a subclass 7365 * provides animated scrolling, the start delay should equal the duration of 7366 * the scrolling animation. 7367 * </p> 7368 * 7369 * <p> 7370 * The animation starts only if at least one of the scrollbars is enabled, 7371 * as specified by {@link #isHorizontalScrollBarEnabled()} and 7372 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 7373 * this method returns true, and false otherwise. If the animation is 7374 * started, this method calls {@link #invalidate()}; in that case the caller 7375 * should not call {@link #invalidate()}. 7376 * </p> 7377 * 7378 * <p> 7379 * This method should be invoked everytime a subclass directly updates the 7380 * scroll parameters. 7381 * </p> 7382 * 7383 * @param startDelay the delay, in milliseconds, after which the animation 7384 * should start; when the delay is 0, the animation starts 7385 * immediately 7386 * @return true if the animation is played, false otherwise 7387 * 7388 * @see #scrollBy(int, int) 7389 * @see #scrollTo(int, int) 7390 * @see #isHorizontalScrollBarEnabled() 7391 * @see #isVerticalScrollBarEnabled() 7392 * @see #setHorizontalScrollBarEnabled(boolean) 7393 * @see #setVerticalScrollBarEnabled(boolean) 7394 */ 7395 protected boolean awakenScrollBars(int startDelay) { 7396 return awakenScrollBars(startDelay, true); 7397 } 7398 7399 /** 7400 * <p> 7401 * Trigger the scrollbars to draw. When invoked this method starts an 7402 * animation to fade the scrollbars out after a fixed delay. If a subclass 7403 * provides animated scrolling, the start delay should equal the duration of 7404 * the scrolling animation. 7405 * </p> 7406 * 7407 * <p> 7408 * The animation starts only if at least one of the scrollbars is enabled, 7409 * as specified by {@link #isHorizontalScrollBarEnabled()} and 7410 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 7411 * this method returns true, and false otherwise. If the animation is 7412 * started, this method calls {@link #invalidate()} if the invalidate parameter 7413 * is set to true; in that case the caller 7414 * should not call {@link #invalidate()}. 7415 * </p> 7416 * 7417 * <p> 7418 * This method should be invoked everytime a subclass directly updates the 7419 * scroll parameters. 7420 * </p> 7421 * 7422 * @param startDelay the delay, in milliseconds, after which the animation 7423 * should start; when the delay is 0, the animation starts 7424 * immediately 7425 * 7426 * @param invalidate Wheter this method should call invalidate 7427 * 7428 * @return true if the animation is played, false otherwise 7429 * 7430 * @see #scrollBy(int, int) 7431 * @see #scrollTo(int, int) 7432 * @see #isHorizontalScrollBarEnabled() 7433 * @see #isVerticalScrollBarEnabled() 7434 * @see #setHorizontalScrollBarEnabled(boolean) 7435 * @see #setVerticalScrollBarEnabled(boolean) 7436 */ 7437 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 7438 final ScrollabilityCache scrollCache = mScrollCache; 7439 7440 if (scrollCache == null || !scrollCache.fadeScrollBars) { 7441 return false; 7442 } 7443 7444 if (scrollCache.scrollBar == null) { 7445 scrollCache.scrollBar = new ScrollBarDrawable(); 7446 } 7447 7448 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 7449 7450 if (invalidate) { 7451 // Invalidate to show the scrollbars 7452 invalidate(true); 7453 } 7454 7455 if (scrollCache.state == ScrollabilityCache.OFF) { 7456 // FIXME: this is copied from WindowManagerService. 7457 // We should get this value from the system when it 7458 // is possible to do so. 7459 final int KEY_REPEAT_FIRST_DELAY = 750; 7460 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 7461 } 7462 7463 // Tell mScrollCache when we should start fading. This may 7464 // extend the fade start time if one was already scheduled 7465 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 7466 scrollCache.fadeStartTime = fadeStartTime; 7467 scrollCache.state = ScrollabilityCache.ON; 7468 7469 // Schedule our fader to run, unscheduling any old ones first 7470 if (mAttachInfo != null) { 7471 mAttachInfo.mHandler.removeCallbacks(scrollCache); 7472 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 7473 } 7474 7475 return true; 7476 } 7477 7478 return false; 7479 } 7480 7481 /** 7482 * Mark the the area defined by dirty as needing to be drawn. If the view is 7483 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point 7484 * in the future. This must be called from a UI thread. To call from a non-UI 7485 * thread, call {@link #postInvalidate()}. 7486 * 7487 * WARNING: This method is destructive to dirty. 7488 * @param dirty the rectangle representing the bounds of the dirty region 7489 */ 7490 public void invalidate(Rect dirty) { 7491 if (ViewDebug.TRACE_HIERARCHY) { 7492 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 7493 } 7494 7495 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 7496 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID || 7497 (mPrivateFlags & INVALIDATED) != INVALIDATED) { 7498 mPrivateFlags &= ~DRAWING_CACHE_VALID; 7499 mPrivateFlags |= INVALIDATED; 7500 final ViewParent p = mParent; 7501 final AttachInfo ai = mAttachInfo; 7502 //noinspection PointlessBooleanExpression,ConstantConditions 7503 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 7504 if (p != null && ai != null && ai.mHardwareAccelerated) { 7505 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 7506 // with a null dirty rect, which tells the ViewAncestor to redraw everything 7507 p.invalidateChild(this, null); 7508 return; 7509 } 7510 } 7511 if (p != null && ai != null) { 7512 final int scrollX = mScrollX; 7513 final int scrollY = mScrollY; 7514 final Rect r = ai.mTmpInvalRect; 7515 r.set(dirty.left - scrollX, dirty.top - scrollY, 7516 dirty.right - scrollX, dirty.bottom - scrollY); 7517 mParent.invalidateChild(this, r); 7518 } 7519 } 7520 } 7521 7522 /** 7523 * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn. 7524 * The coordinates of the dirty rect are relative to the view. 7525 * If the view is visible, {@link #onDraw(android.graphics.Canvas)} 7526 * will be called at some point in the future. This must be called from 7527 * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}. 7528 * @param l the left position of the dirty region 7529 * @param t the top position of the dirty region 7530 * @param r the right position of the dirty region 7531 * @param b the bottom position of the dirty region 7532 */ 7533 public void invalidate(int l, int t, int r, int b) { 7534 if (ViewDebug.TRACE_HIERARCHY) { 7535 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 7536 } 7537 7538 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 7539 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID || 7540 (mPrivateFlags & INVALIDATED) != INVALIDATED) { 7541 mPrivateFlags &= ~DRAWING_CACHE_VALID; 7542 mPrivateFlags |= INVALIDATED; 7543 final ViewParent p = mParent; 7544 final AttachInfo ai = mAttachInfo; 7545 //noinspection PointlessBooleanExpression,ConstantConditions 7546 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 7547 if (p != null && ai != null && ai.mHardwareAccelerated) { 7548 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 7549 // with a null dirty rect, which tells the ViewAncestor to redraw everything 7550 p.invalidateChild(this, null); 7551 return; 7552 } 7553 } 7554 if (p != null && ai != null && l < r && t < b) { 7555 final int scrollX = mScrollX; 7556 final int scrollY = mScrollY; 7557 final Rect tmpr = ai.mTmpInvalRect; 7558 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY); 7559 p.invalidateChild(this, tmpr); 7560 } 7561 } 7562 } 7563 7564 /** 7565 * Invalidate the whole view. If the view is visible, 7566 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 7567 * the future. This must be called from a UI thread. To call from a non-UI thread, 7568 * call {@link #postInvalidate()}. 7569 */ 7570 public void invalidate() { 7571 invalidate(true); 7572 } 7573 7574 /** 7575 * This is where the invalidate() work actually happens. A full invalidate() 7576 * causes the drawing cache to be invalidated, but this function can be called with 7577 * invalidateCache set to false to skip that invalidation step for cases that do not 7578 * need it (for example, a component that remains at the same dimensions with the same 7579 * content). 7580 * 7581 * @param invalidateCache Whether the drawing cache for this view should be invalidated as 7582 * well. This is usually true for a full invalidate, but may be set to false if the 7583 * View's contents or dimensions have not changed. 7584 */ 7585 void invalidate(boolean invalidateCache) { 7586 if (ViewDebug.TRACE_HIERARCHY) { 7587 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE); 7588 } 7589 7590 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 7591 (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) || 7592 (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) { 7593 mLastIsOpaque = isOpaque(); 7594 mPrivateFlags &= ~DRAWN; 7595 if (invalidateCache) { 7596 mPrivateFlags |= INVALIDATED; 7597 mPrivateFlags &= ~DRAWING_CACHE_VALID; 7598 } 7599 final AttachInfo ai = mAttachInfo; 7600 final ViewParent p = mParent; 7601 //noinspection PointlessBooleanExpression,ConstantConditions 7602 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 7603 if (p != null && ai != null && ai.mHardwareAccelerated) { 7604 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 7605 // with a null dirty rect, which tells the ViewAncestor to redraw everything 7606 p.invalidateChild(this, null); 7607 return; 7608 } 7609 } 7610 7611 if (p != null && ai != null) { 7612 final Rect r = ai.mTmpInvalRect; 7613 r.set(0, 0, mRight - mLeft, mBottom - mTop); 7614 // Don't call invalidate -- we don't want to internally scroll 7615 // our own bounds 7616 p.invalidateChild(this, r); 7617 } 7618 } 7619 } 7620 7621 /** 7622 * @hide 7623 */ 7624 public void fastInvalidate() { 7625 if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) || 7626 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID || 7627 (mPrivateFlags & INVALIDATED) != INVALIDATED) { 7628 if (mParent instanceof View) { 7629 ((View) mParent).mPrivateFlags |= INVALIDATED; 7630 } 7631 mPrivateFlags &= ~DRAWN; 7632 mPrivateFlags |= INVALIDATED; 7633 mPrivateFlags &= ~DRAWING_CACHE_VALID; 7634 if (mParent != null && mAttachInfo != null) { 7635 if (mAttachInfo.mHardwareAccelerated) { 7636 mParent.invalidateChild(this, null); 7637 } else { 7638 final Rect r = mAttachInfo.mTmpInvalRect; 7639 r.set(0, 0, mRight - mLeft, mBottom - mTop); 7640 // Don't call invalidate -- we don't want to internally scroll 7641 // our own bounds 7642 mParent.invalidateChild(this, r); 7643 } 7644 } 7645 } 7646 } 7647 7648 /** 7649 * Used to indicate that the parent of this view should clear its caches. This functionality 7650 * is used to force the parent to rebuild its display list (when hardware-accelerated), 7651 * which is necessary when various parent-managed properties of the view change, such as 7652 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 7653 * clears the parent caches and does not causes an invalidate event. 7654 * 7655 * @hide 7656 */ 7657 protected void invalidateParentCaches() { 7658 if (mParent instanceof View) { 7659 ((View) mParent).mPrivateFlags |= INVALIDATED; 7660 } 7661 } 7662 7663 /** 7664 * Used to indicate that the parent of this view should be invalidated. This functionality 7665 * is used to force the parent to rebuild its display list (when hardware-accelerated), 7666 * which is necessary when various parent-managed properties of the view change, such as 7667 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 7668 * an invalidation event to the parent. 7669 * 7670 * @hide 7671 */ 7672 protected void invalidateParentIfNeeded() { 7673 if (isHardwareAccelerated() && mParent instanceof View) { 7674 ((View) mParent).invalidate(true); 7675 } 7676 } 7677 7678 /** 7679 * Indicates whether this View is opaque. An opaque View guarantees that it will 7680 * draw all the pixels overlapping its bounds using a fully opaque color. 7681 * 7682 * Subclasses of View should override this method whenever possible to indicate 7683 * whether an instance is opaque. Opaque Views are treated in a special way by 7684 * the View hierarchy, possibly allowing it to perform optimizations during 7685 * invalidate/draw passes. 7686 * 7687 * @return True if this View is guaranteed to be fully opaque, false otherwise. 7688 */ 7689 @ViewDebug.ExportedProperty(category = "drawing") 7690 public boolean isOpaque() { 7691 return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK && 7692 (mAlpha >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD); 7693 } 7694 7695 /** 7696 * @hide 7697 */ 7698 protected void computeOpaqueFlags() { 7699 // Opaque if: 7700 // - Has a background 7701 // - Background is opaque 7702 // - Doesn't have scrollbars or scrollbars are inside overlay 7703 7704 if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) { 7705 mPrivateFlags |= OPAQUE_BACKGROUND; 7706 } else { 7707 mPrivateFlags &= ~OPAQUE_BACKGROUND; 7708 } 7709 7710 final int flags = mViewFlags; 7711 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 7712 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) { 7713 mPrivateFlags |= OPAQUE_SCROLLBARS; 7714 } else { 7715 mPrivateFlags &= ~OPAQUE_SCROLLBARS; 7716 } 7717 } 7718 7719 /** 7720 * @hide 7721 */ 7722 protected boolean hasOpaqueScrollbars() { 7723 return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS; 7724 } 7725 7726 /** 7727 * @return A handler associated with the thread running the View. This 7728 * handler can be used to pump events in the UI events queue. 7729 */ 7730 public Handler getHandler() { 7731 if (mAttachInfo != null) { 7732 return mAttachInfo.mHandler; 7733 } 7734 return null; 7735 } 7736 7737 /** 7738 * Causes the Runnable to be added to the message queue. 7739 * The runnable will be run on the user interface thread. 7740 * 7741 * @param action The Runnable that will be executed. 7742 * 7743 * @return Returns true if the Runnable was successfully placed in to the 7744 * message queue. Returns false on failure, usually because the 7745 * looper processing the message queue is exiting. 7746 */ 7747 public boolean post(Runnable action) { 7748 Handler handler; 7749 AttachInfo attachInfo = mAttachInfo; 7750 if (attachInfo != null) { 7751 handler = attachInfo.mHandler; 7752 } else { 7753 // Assume that post will succeed later 7754 ViewAncestor.getRunQueue().post(action); 7755 return true; 7756 } 7757 7758 return handler.post(action); 7759 } 7760 7761 /** 7762 * Causes the Runnable to be added to the message queue, to be run 7763 * after the specified amount of time elapses. 7764 * The runnable will be run on the user interface thread. 7765 * 7766 * @param action The Runnable that will be executed. 7767 * @param delayMillis The delay (in milliseconds) until the Runnable 7768 * will be executed. 7769 * 7770 * @return true if the Runnable was successfully placed in to the 7771 * message queue. Returns false on failure, usually because the 7772 * looper processing the message queue is exiting. Note that a 7773 * result of true does not mean the Runnable will be processed -- 7774 * if the looper is quit before the delivery time of the message 7775 * occurs then the message will be dropped. 7776 */ 7777 public boolean postDelayed(Runnable action, long delayMillis) { 7778 Handler handler; 7779 AttachInfo attachInfo = mAttachInfo; 7780 if (attachInfo != null) { 7781 handler = attachInfo.mHandler; 7782 } else { 7783 // Assume that post will succeed later 7784 ViewAncestor.getRunQueue().postDelayed(action, delayMillis); 7785 return true; 7786 } 7787 7788 return handler.postDelayed(action, delayMillis); 7789 } 7790 7791 /** 7792 * Removes the specified Runnable from the message queue. 7793 * 7794 * @param action The Runnable to remove from the message handling queue 7795 * 7796 * @return true if this view could ask the Handler to remove the Runnable, 7797 * false otherwise. When the returned value is true, the Runnable 7798 * may or may not have been actually removed from the message queue 7799 * (for instance, if the Runnable was not in the queue already.) 7800 */ 7801 public boolean removeCallbacks(Runnable action) { 7802 Handler handler; 7803 AttachInfo attachInfo = mAttachInfo; 7804 if (attachInfo != null) { 7805 handler = attachInfo.mHandler; 7806 } else { 7807 // Assume that post will succeed later 7808 ViewAncestor.getRunQueue().removeCallbacks(action); 7809 return true; 7810 } 7811 7812 handler.removeCallbacks(action); 7813 return true; 7814 } 7815 7816 /** 7817 * Cause an invalidate to happen on a subsequent cycle through the event loop. 7818 * Use this to invalidate the View from a non-UI thread. 7819 * 7820 * @see #invalidate() 7821 */ 7822 public void postInvalidate() { 7823 postInvalidateDelayed(0); 7824 } 7825 7826 /** 7827 * Cause an invalidate of the specified area to happen on a subsequent cycle 7828 * through the event loop. Use this to invalidate the View from a non-UI thread. 7829 * 7830 * @param left The left coordinate of the rectangle to invalidate. 7831 * @param top The top coordinate of the rectangle to invalidate. 7832 * @param right The right coordinate of the rectangle to invalidate. 7833 * @param bottom The bottom coordinate of the rectangle to invalidate. 7834 * 7835 * @see #invalidate(int, int, int, int) 7836 * @see #invalidate(Rect) 7837 */ 7838 public void postInvalidate(int left, int top, int right, int bottom) { 7839 postInvalidateDelayed(0, left, top, right, bottom); 7840 } 7841 7842 /** 7843 * Cause an invalidate to happen on a subsequent cycle through the event 7844 * loop. Waits for the specified amount of time. 7845 * 7846 * @param delayMilliseconds the duration in milliseconds to delay the 7847 * invalidation by 7848 */ 7849 public void postInvalidateDelayed(long delayMilliseconds) { 7850 // We try only with the AttachInfo because there's no point in invalidating 7851 // if we are not attached to our window 7852 AttachInfo attachInfo = mAttachInfo; 7853 if (attachInfo != null) { 7854 Message msg = Message.obtain(); 7855 msg.what = AttachInfo.INVALIDATE_MSG; 7856 msg.obj = this; 7857 attachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds); 7858 } 7859 } 7860 7861 /** 7862 * Cause an invalidate of the specified area to happen on a subsequent cycle 7863 * through the event loop. Waits for the specified amount of time. 7864 * 7865 * @param delayMilliseconds the duration in milliseconds to delay the 7866 * invalidation by 7867 * @param left The left coordinate of the rectangle to invalidate. 7868 * @param top The top coordinate of the rectangle to invalidate. 7869 * @param right The right coordinate of the rectangle to invalidate. 7870 * @param bottom The bottom coordinate of the rectangle to invalidate. 7871 */ 7872 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 7873 int right, int bottom) { 7874 7875 // We try only with the AttachInfo because there's no point in invalidating 7876 // if we are not attached to our window 7877 AttachInfo attachInfo = mAttachInfo; 7878 if (attachInfo != null) { 7879 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire(); 7880 info.target = this; 7881 info.left = left; 7882 info.top = top; 7883 info.right = right; 7884 info.bottom = bottom; 7885 7886 final Message msg = Message.obtain(); 7887 msg.what = AttachInfo.INVALIDATE_RECT_MSG; 7888 msg.obj = info; 7889 attachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds); 7890 } 7891 } 7892 7893 /** 7894 * Called by a parent to request that a child update its values for mScrollX 7895 * and mScrollY if necessary. This will typically be done if the child is 7896 * animating a scroll using a {@link android.widget.Scroller Scroller} 7897 * object. 7898 */ 7899 public void computeScroll() { 7900 } 7901 7902 /** 7903 * <p>Indicate whether the horizontal edges are faded when the view is 7904 * scrolled horizontally.</p> 7905 * 7906 * @return true if the horizontal edges should are faded on scroll, false 7907 * otherwise 7908 * 7909 * @see #setHorizontalFadingEdgeEnabled(boolean) 7910 * @attr ref android.R.styleable#View_fadingEdge 7911 */ 7912 public boolean isHorizontalFadingEdgeEnabled() { 7913 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 7914 } 7915 7916 /** 7917 * <p>Define whether the horizontal edges should be faded when this view 7918 * is scrolled horizontally.</p> 7919 * 7920 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 7921 * be faded when the view is scrolled 7922 * horizontally 7923 * 7924 * @see #isHorizontalFadingEdgeEnabled() 7925 * @attr ref android.R.styleable#View_fadingEdge 7926 */ 7927 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 7928 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 7929 if (horizontalFadingEdgeEnabled) { 7930 initScrollCache(); 7931 } 7932 7933 mViewFlags ^= FADING_EDGE_HORIZONTAL; 7934 } 7935 } 7936 7937 /** 7938 * <p>Indicate whether the vertical edges are faded when the view is 7939 * scrolled horizontally.</p> 7940 * 7941 * @return true if the vertical edges should are faded on scroll, false 7942 * otherwise 7943 * 7944 * @see #setVerticalFadingEdgeEnabled(boolean) 7945 * @attr ref android.R.styleable#View_fadingEdge 7946 */ 7947 public boolean isVerticalFadingEdgeEnabled() { 7948 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 7949 } 7950 7951 /** 7952 * <p>Define whether the vertical edges should be faded when this view 7953 * is scrolled vertically.</p> 7954 * 7955 * @param verticalFadingEdgeEnabled true if the vertical edges should 7956 * be faded when the view is scrolled 7957 * vertically 7958 * 7959 * @see #isVerticalFadingEdgeEnabled() 7960 * @attr ref android.R.styleable#View_fadingEdge 7961 */ 7962 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 7963 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 7964 if (verticalFadingEdgeEnabled) { 7965 initScrollCache(); 7966 } 7967 7968 mViewFlags ^= FADING_EDGE_VERTICAL; 7969 } 7970 } 7971 7972 /** 7973 * Returns the strength, or intensity, of the top faded edge. The strength is 7974 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 7975 * returns 0.0 or 1.0 but no value in between. 7976 * 7977 * Subclasses should override this method to provide a smoother fade transition 7978 * when scrolling occurs. 7979 * 7980 * @return the intensity of the top fade as a float between 0.0f and 1.0f 7981 */ 7982 protected float getTopFadingEdgeStrength() { 7983 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 7984 } 7985 7986 /** 7987 * Returns the strength, or intensity, of the bottom faded edge. The strength is 7988 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 7989 * returns 0.0 or 1.0 but no value in between. 7990 * 7991 * Subclasses should override this method to provide a smoother fade transition 7992 * when scrolling occurs. 7993 * 7994 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 7995 */ 7996 protected float getBottomFadingEdgeStrength() { 7997 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 7998 computeVerticalScrollRange() ? 1.0f : 0.0f; 7999 } 8000 8001 /** 8002 * Returns the strength, or intensity, of the left faded edge. The strength is 8003 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 8004 * returns 0.0 or 1.0 but no value in between. 8005 * 8006 * Subclasses should override this method to provide a smoother fade transition 8007 * when scrolling occurs. 8008 * 8009 * @return the intensity of the left fade as a float between 0.0f and 1.0f 8010 */ 8011 protected float getLeftFadingEdgeStrength() { 8012 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 8013 } 8014 8015 /** 8016 * Returns the strength, or intensity, of the right faded edge. The strength is 8017 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 8018 * returns 0.0 or 1.0 but no value in between. 8019 * 8020 * Subclasses should override this method to provide a smoother fade transition 8021 * when scrolling occurs. 8022 * 8023 * @return the intensity of the right fade as a float between 0.0f and 1.0f 8024 */ 8025 protected float getRightFadingEdgeStrength() { 8026 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 8027 computeHorizontalScrollRange() ? 1.0f : 0.0f; 8028 } 8029 8030 /** 8031 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 8032 * scrollbar is not drawn by default.</p> 8033 * 8034 * @return true if the horizontal scrollbar should be painted, false 8035 * otherwise 8036 * 8037 * @see #setHorizontalScrollBarEnabled(boolean) 8038 */ 8039 public boolean isHorizontalScrollBarEnabled() { 8040 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 8041 } 8042 8043 /** 8044 * <p>Define whether the horizontal scrollbar should be drawn or not. The 8045 * scrollbar is not drawn by default.</p> 8046 * 8047 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 8048 * be painted 8049 * 8050 * @see #isHorizontalScrollBarEnabled() 8051 */ 8052 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 8053 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 8054 mViewFlags ^= SCROLLBARS_HORIZONTAL; 8055 computeOpaqueFlags(); 8056 recomputePadding(); 8057 } 8058 } 8059 8060 /** 8061 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 8062 * scrollbar is not drawn by default.</p> 8063 * 8064 * @return true if the vertical scrollbar should be painted, false 8065 * otherwise 8066 * 8067 * @see #setVerticalScrollBarEnabled(boolean) 8068 */ 8069 public boolean isVerticalScrollBarEnabled() { 8070 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 8071 } 8072 8073 /** 8074 * <p>Define whether the vertical scrollbar should be drawn or not. The 8075 * scrollbar is not drawn by default.</p> 8076 * 8077 * @param verticalScrollBarEnabled true if the vertical scrollbar should 8078 * be painted 8079 * 8080 * @see #isVerticalScrollBarEnabled() 8081 */ 8082 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 8083 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 8084 mViewFlags ^= SCROLLBARS_VERTICAL; 8085 computeOpaqueFlags(); 8086 recomputePadding(); 8087 } 8088 } 8089 8090 /** 8091 * @hide 8092 */ 8093 protected void recomputePadding() { 8094 setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 8095 } 8096 8097 /** 8098 * Define whether scrollbars will fade when the view is not scrolling. 8099 * 8100 * @param fadeScrollbars wheter to enable fading 8101 * 8102 */ 8103 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 8104 initScrollCache(); 8105 final ScrollabilityCache scrollabilityCache = mScrollCache; 8106 scrollabilityCache.fadeScrollBars = fadeScrollbars; 8107 if (fadeScrollbars) { 8108 scrollabilityCache.state = ScrollabilityCache.OFF; 8109 } else { 8110 scrollabilityCache.state = ScrollabilityCache.ON; 8111 } 8112 } 8113 8114 /** 8115 * 8116 * Returns true if scrollbars will fade when this view is not scrolling 8117 * 8118 * @return true if scrollbar fading is enabled 8119 */ 8120 public boolean isScrollbarFadingEnabled() { 8121 return mScrollCache != null && mScrollCache.fadeScrollBars; 8122 } 8123 8124 /** 8125 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 8126 * inset. When inset, they add to the padding of the view. And the scrollbars 8127 * can be drawn inside the padding area or on the edge of the view. For example, 8128 * if a view has a background drawable and you want to draw the scrollbars 8129 * inside the padding specified by the drawable, you can use 8130 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 8131 * appear at the edge of the view, ignoring the padding, then you can use 8132 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 8133 * @param style the style of the scrollbars. Should be one of 8134 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 8135 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 8136 * @see #SCROLLBARS_INSIDE_OVERLAY 8137 * @see #SCROLLBARS_INSIDE_INSET 8138 * @see #SCROLLBARS_OUTSIDE_OVERLAY 8139 * @see #SCROLLBARS_OUTSIDE_INSET 8140 */ 8141 public void setScrollBarStyle(int style) { 8142 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 8143 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 8144 computeOpaqueFlags(); 8145 recomputePadding(); 8146 } 8147 } 8148 8149 /** 8150 * <p>Returns the current scrollbar style.</p> 8151 * @return the current scrollbar style 8152 * @see #SCROLLBARS_INSIDE_OVERLAY 8153 * @see #SCROLLBARS_INSIDE_INSET 8154 * @see #SCROLLBARS_OUTSIDE_OVERLAY 8155 * @see #SCROLLBARS_OUTSIDE_INSET 8156 */ 8157 public int getScrollBarStyle() { 8158 return mViewFlags & SCROLLBARS_STYLE_MASK; 8159 } 8160 8161 /** 8162 * <p>Compute the horizontal range that the horizontal scrollbar 8163 * represents.</p> 8164 * 8165 * <p>The range is expressed in arbitrary units that must be the same as the 8166 * units used by {@link #computeHorizontalScrollExtent()} and 8167 * {@link #computeHorizontalScrollOffset()}.</p> 8168 * 8169 * <p>The default range is the drawing width of this view.</p> 8170 * 8171 * @return the total horizontal range represented by the horizontal 8172 * scrollbar 8173 * 8174 * @see #computeHorizontalScrollExtent() 8175 * @see #computeHorizontalScrollOffset() 8176 * @see android.widget.ScrollBarDrawable 8177 */ 8178 protected int computeHorizontalScrollRange() { 8179 return getWidth(); 8180 } 8181 8182 /** 8183 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 8184 * within the horizontal range. This value is used to compute the position 8185 * of the thumb within the scrollbar's track.</p> 8186 * 8187 * <p>The range is expressed in arbitrary units that must be the same as the 8188 * units used by {@link #computeHorizontalScrollRange()} and 8189 * {@link #computeHorizontalScrollExtent()}.</p> 8190 * 8191 * <p>The default offset is the scroll offset of this view.</p> 8192 * 8193 * @return the horizontal offset of the scrollbar's thumb 8194 * 8195 * @see #computeHorizontalScrollRange() 8196 * @see #computeHorizontalScrollExtent() 8197 * @see android.widget.ScrollBarDrawable 8198 */ 8199 protected int computeHorizontalScrollOffset() { 8200 return mScrollX; 8201 } 8202 8203 /** 8204 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 8205 * within the horizontal range. This value is used to compute the length 8206 * of the thumb within the scrollbar's track.</p> 8207 * 8208 * <p>The range is expressed in arbitrary units that must be the same as the 8209 * units used by {@link #computeHorizontalScrollRange()} and 8210 * {@link #computeHorizontalScrollOffset()}.</p> 8211 * 8212 * <p>The default extent is the drawing width of this view.</p> 8213 * 8214 * @return the horizontal extent of the scrollbar's thumb 8215 * 8216 * @see #computeHorizontalScrollRange() 8217 * @see #computeHorizontalScrollOffset() 8218 * @see android.widget.ScrollBarDrawable 8219 */ 8220 protected int computeHorizontalScrollExtent() { 8221 return getWidth(); 8222 } 8223 8224 /** 8225 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 8226 * 8227 * <p>The range is expressed in arbitrary units that must be the same as the 8228 * units used by {@link #computeVerticalScrollExtent()} and 8229 * {@link #computeVerticalScrollOffset()}.</p> 8230 * 8231 * @return the total vertical range represented by the vertical scrollbar 8232 * 8233 * <p>The default range is the drawing height of this view.</p> 8234 * 8235 * @see #computeVerticalScrollExtent() 8236 * @see #computeVerticalScrollOffset() 8237 * @see android.widget.ScrollBarDrawable 8238 */ 8239 protected int computeVerticalScrollRange() { 8240 return getHeight(); 8241 } 8242 8243 /** 8244 * <p>Compute the vertical offset of the vertical scrollbar's thumb 8245 * within the horizontal range. This value is used to compute the position 8246 * of the thumb within the scrollbar's track.</p> 8247 * 8248 * <p>The range is expressed in arbitrary units that must be the same as the 8249 * units used by {@link #computeVerticalScrollRange()} and 8250 * {@link #computeVerticalScrollExtent()}.</p> 8251 * 8252 * <p>The default offset is the scroll offset of this view.</p> 8253 * 8254 * @return the vertical offset of the scrollbar's thumb 8255 * 8256 * @see #computeVerticalScrollRange() 8257 * @see #computeVerticalScrollExtent() 8258 * @see android.widget.ScrollBarDrawable 8259 */ 8260 protected int computeVerticalScrollOffset() { 8261 return mScrollY; 8262 } 8263 8264 /** 8265 * <p>Compute the vertical extent of the horizontal scrollbar's thumb 8266 * within the vertical range. This value is used to compute the length 8267 * of the thumb within the scrollbar's track.</p> 8268 * 8269 * <p>The range is expressed in arbitrary units that must be the same as the 8270 * units used by {@link #computeVerticalScrollRange()} and 8271 * {@link #computeVerticalScrollOffset()}.</p> 8272 * 8273 * <p>The default extent is the drawing height of this view.</p> 8274 * 8275 * @return the vertical extent of the scrollbar's thumb 8276 * 8277 * @see #computeVerticalScrollRange() 8278 * @see #computeVerticalScrollOffset() 8279 * @see android.widget.ScrollBarDrawable 8280 */ 8281 protected int computeVerticalScrollExtent() { 8282 return getHeight(); 8283 } 8284 8285 /** 8286 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 8287 * scrollbars are painted only if they have been awakened first.</p> 8288 * 8289 * @param canvas the canvas on which to draw the scrollbars 8290 * 8291 * @see #awakenScrollBars(int) 8292 */ 8293 protected final void onDrawScrollBars(Canvas canvas) { 8294 // scrollbars are drawn only when the animation is running 8295 final ScrollabilityCache cache = mScrollCache; 8296 if (cache != null) { 8297 8298 int state = cache.state; 8299 8300 if (state == ScrollabilityCache.OFF) { 8301 return; 8302 } 8303 8304 boolean invalidate = false; 8305 8306 if (state == ScrollabilityCache.FADING) { 8307 // We're fading -- get our fade interpolation 8308 if (cache.interpolatorValues == null) { 8309 cache.interpolatorValues = new float[1]; 8310 } 8311 8312 float[] values = cache.interpolatorValues; 8313 8314 // Stops the animation if we're done 8315 if (cache.scrollBarInterpolator.timeToValues(values) == 8316 Interpolator.Result.FREEZE_END) { 8317 cache.state = ScrollabilityCache.OFF; 8318 } else { 8319 cache.scrollBar.setAlpha(Math.round(values[0])); 8320 } 8321 8322 // This will make the scroll bars inval themselves after 8323 // drawing. We only want this when we're fading so that 8324 // we prevent excessive redraws 8325 invalidate = true; 8326 } else { 8327 // We're just on -- but we may have been fading before so 8328 // reset alpha 8329 cache.scrollBar.setAlpha(255); 8330 } 8331 8332 8333 final int viewFlags = mViewFlags; 8334 8335 final boolean drawHorizontalScrollBar = 8336 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 8337 final boolean drawVerticalScrollBar = 8338 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 8339 && !isVerticalScrollBarHidden(); 8340 8341 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 8342 final int width = mRight - mLeft; 8343 final int height = mBottom - mTop; 8344 8345 final ScrollBarDrawable scrollBar = cache.scrollBar; 8346 8347 final int scrollX = mScrollX; 8348 final int scrollY = mScrollY; 8349 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 8350 8351 int left, top, right, bottom; 8352 8353 if (drawHorizontalScrollBar) { 8354 int size = scrollBar.getSize(false); 8355 if (size <= 0) { 8356 size = cache.scrollBarSize; 8357 } 8358 8359 scrollBar.setParameters(computeHorizontalScrollRange(), 8360 computeHorizontalScrollOffset(), 8361 computeHorizontalScrollExtent(), false); 8362 final int verticalScrollBarGap = drawVerticalScrollBar ? 8363 getVerticalScrollbarWidth() : 0; 8364 top = scrollY + height - size - (mUserPaddingBottom & inside); 8365 left = scrollX + (mPaddingLeft & inside); 8366 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 8367 bottom = top + size; 8368 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 8369 if (invalidate) { 8370 invalidate(left, top, right, bottom); 8371 } 8372 } 8373 8374 if (drawVerticalScrollBar) { 8375 int size = scrollBar.getSize(true); 8376 if (size <= 0) { 8377 size = cache.scrollBarSize; 8378 } 8379 8380 scrollBar.setParameters(computeVerticalScrollRange(), 8381 computeVerticalScrollOffset(), 8382 computeVerticalScrollExtent(), true); 8383 switch (mVerticalScrollbarPosition) { 8384 default: 8385 case SCROLLBAR_POSITION_DEFAULT: 8386 case SCROLLBAR_POSITION_RIGHT: 8387 left = scrollX + width - size - (mUserPaddingRight & inside); 8388 break; 8389 case SCROLLBAR_POSITION_LEFT: 8390 left = scrollX + (mUserPaddingLeft & inside); 8391 break; 8392 } 8393 top = scrollY + (mPaddingTop & inside); 8394 right = left + size; 8395 bottom = scrollY + height - (mUserPaddingBottom & inside); 8396 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 8397 if (invalidate) { 8398 invalidate(left, top, right, bottom); 8399 } 8400 } 8401 } 8402 } 8403 } 8404 8405 /** 8406 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 8407 * FastScroller is visible. 8408 * @return whether to temporarily hide the vertical scrollbar 8409 * @hide 8410 */ 8411 protected boolean isVerticalScrollBarHidden() { 8412 return false; 8413 } 8414 8415 /** 8416 * <p>Draw the horizontal scrollbar if 8417 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 8418 * 8419 * @param canvas the canvas on which to draw the scrollbar 8420 * @param scrollBar the scrollbar's drawable 8421 * 8422 * @see #isHorizontalScrollBarEnabled() 8423 * @see #computeHorizontalScrollRange() 8424 * @see #computeHorizontalScrollExtent() 8425 * @see #computeHorizontalScrollOffset() 8426 * @see android.widget.ScrollBarDrawable 8427 * @hide 8428 */ 8429 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 8430 int l, int t, int r, int b) { 8431 scrollBar.setBounds(l, t, r, b); 8432 scrollBar.draw(canvas); 8433 } 8434 8435 /** 8436 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 8437 * returns true.</p> 8438 * 8439 * @param canvas the canvas on which to draw the scrollbar 8440 * @param scrollBar the scrollbar's drawable 8441 * 8442 * @see #isVerticalScrollBarEnabled() 8443 * @see #computeVerticalScrollRange() 8444 * @see #computeVerticalScrollExtent() 8445 * @see #computeVerticalScrollOffset() 8446 * @see android.widget.ScrollBarDrawable 8447 * @hide 8448 */ 8449 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 8450 int l, int t, int r, int b) { 8451 scrollBar.setBounds(l, t, r, b); 8452 scrollBar.draw(canvas); 8453 } 8454 8455 /** 8456 * Implement this to do your drawing. 8457 * 8458 * @param canvas the canvas on which the background will be drawn 8459 */ 8460 protected void onDraw(Canvas canvas) { 8461 } 8462 8463 /* 8464 * Caller is responsible for calling requestLayout if necessary. 8465 * (This allows addViewInLayout to not request a new layout.) 8466 */ 8467 void assignParent(ViewParent parent) { 8468 if (mParent == null) { 8469 mParent = parent; 8470 } else if (parent == null) { 8471 mParent = null; 8472 } else { 8473 throw new RuntimeException("view " + this + " being added, but" 8474 + " it already has a parent"); 8475 } 8476 } 8477 8478 /** 8479 * This is called when the view is attached to a window. At this point it 8480 * has a Surface and will start drawing. Note that this function is 8481 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 8482 * however it may be called any time before the first onDraw -- including 8483 * before or after {@link #onMeasure(int, int)}. 8484 * 8485 * @see #onDetachedFromWindow() 8486 */ 8487 protected void onAttachedToWindow() { 8488 if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) { 8489 mParent.requestTransparentRegion(this); 8490 } 8491 if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 8492 initialAwakenScrollBars(); 8493 mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH; 8494 } 8495 jumpDrawablesToCurrentState(); 8496 8497 // We are supposing here that the parent directionality will be resolved before its children 8498 // View horizontalDirection public attribute resolution to an internal var. 8499 // Resolving the layout direction. LTR is set initially. 8500 mPrivateFlags2 &= ~RESOLVED_LAYOUT_RTL; 8501 switch (getHorizontalDirection()) { 8502 case HORIZONTAL_DIRECTION_INHERIT: 8503 // If this is root view, no need to look at parent's layout dir. 8504 if (mParent != null && mParent instanceof ViewGroup && 8505 ((ViewGroup) mParent).isLayoutRtl()) { 8506 mPrivateFlags2 |= RESOLVED_LAYOUT_RTL; 8507 } 8508 break; 8509 case HORIZONTAL_DIRECTION_RTL: 8510 mPrivateFlags2 |= RESOLVED_LAYOUT_RTL; 8511 break; 8512 } 8513 } 8514 8515 /** 8516 * This is called when the view is detached from a window. At this point it 8517 * no longer has a surface for drawing. 8518 * 8519 * @see #onAttachedToWindow() 8520 */ 8521 protected void onDetachedFromWindow() { 8522 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT; 8523 8524 removeUnsetPressCallback(); 8525 removeLongPressCallback(); 8526 removePerformClickCallback(); 8527 8528 destroyDrawingCache(); 8529 8530 if (mHardwareLayer != null) { 8531 mHardwareLayer.destroy(); 8532 mHardwareLayer = null; 8533 } 8534 8535 if (mDisplayList != null) { 8536 mDisplayList.invalidate(); 8537 } 8538 8539 if (mAttachInfo != null) { 8540 mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_MSG, this); 8541 mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_RECT_MSG, this); 8542 } 8543 8544 mCurrentAnimation = null; 8545 } 8546 8547 /** 8548 * @return The number of times this view has been attached to a window 8549 */ 8550 protected int getWindowAttachCount() { 8551 return mWindowAttachCount; 8552 } 8553 8554 /** 8555 * Retrieve a unique token identifying the window this view is attached to. 8556 * @return Return the window's token for use in 8557 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 8558 */ 8559 public IBinder getWindowToken() { 8560 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 8561 } 8562 8563 /** 8564 * Retrieve a unique token identifying the top-level "real" window of 8565 * the window that this view is attached to. That is, this is like 8566 * {@link #getWindowToken}, except if the window this view in is a panel 8567 * window (attached to another containing window), then the token of 8568 * the containing window is returned instead. 8569 * 8570 * @return Returns the associated window token, either 8571 * {@link #getWindowToken()} or the containing window's token. 8572 */ 8573 public IBinder getApplicationWindowToken() { 8574 AttachInfo ai = mAttachInfo; 8575 if (ai != null) { 8576 IBinder appWindowToken = ai.mPanelParentWindowToken; 8577 if (appWindowToken == null) { 8578 appWindowToken = ai.mWindowToken; 8579 } 8580 return appWindowToken; 8581 } 8582 return null; 8583 } 8584 8585 /** 8586 * Retrieve private session object this view hierarchy is using to 8587 * communicate with the window manager. 8588 * @return the session object to communicate with the window manager 8589 */ 8590 /*package*/ IWindowSession getWindowSession() { 8591 return mAttachInfo != null ? mAttachInfo.mSession : null; 8592 } 8593 8594 /** 8595 * @param info the {@link android.view.View.AttachInfo} to associated with 8596 * this view 8597 */ 8598 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 8599 //System.out.println("Attached! " + this); 8600 mAttachInfo = info; 8601 mWindowAttachCount++; 8602 // We will need to evaluate the drawable state at least once. 8603 mPrivateFlags |= DRAWABLE_STATE_DIRTY; 8604 if (mFloatingTreeObserver != null) { 8605 info.mTreeObserver.merge(mFloatingTreeObserver); 8606 mFloatingTreeObserver = null; 8607 } 8608 if ((mPrivateFlags&SCROLL_CONTAINER) != 0) { 8609 mAttachInfo.mScrollContainers.add(this); 8610 mPrivateFlags |= SCROLL_CONTAINER_ADDED; 8611 } 8612 performCollectViewAttributes(visibility); 8613 onAttachedToWindow(); 8614 8615 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 8616 mOnAttachStateChangeListeners; 8617 if (listeners != null && listeners.size() > 0) { 8618 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 8619 // perform the dispatching. The iterator is a safe guard against listeners that 8620 // could mutate the list by calling the various add/remove methods. This prevents 8621 // the array from being modified while we iterate it. 8622 for (OnAttachStateChangeListener listener : listeners) { 8623 listener.onViewAttachedToWindow(this); 8624 } 8625 } 8626 8627 int vis = info.mWindowVisibility; 8628 if (vis != GONE) { 8629 onWindowVisibilityChanged(vis); 8630 } 8631 if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) { 8632 // If nobody has evaluated the drawable state yet, then do it now. 8633 refreshDrawableState(); 8634 } 8635 } 8636 8637 void dispatchDetachedFromWindow() { 8638 AttachInfo info = mAttachInfo; 8639 if (info != null) { 8640 int vis = info.mWindowVisibility; 8641 if (vis != GONE) { 8642 onWindowVisibilityChanged(GONE); 8643 } 8644 } 8645 8646 onDetachedFromWindow(); 8647 8648 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 8649 mOnAttachStateChangeListeners; 8650 if (listeners != null && listeners.size() > 0) { 8651 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 8652 // perform the dispatching. The iterator is a safe guard against listeners that 8653 // could mutate the list by calling the various add/remove methods. This prevents 8654 // the array from being modified while we iterate it. 8655 for (OnAttachStateChangeListener listener : listeners) { 8656 listener.onViewDetachedFromWindow(this); 8657 } 8658 } 8659 8660 if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) { 8661 mAttachInfo.mScrollContainers.remove(this); 8662 mPrivateFlags &= ~SCROLL_CONTAINER_ADDED; 8663 } 8664 8665 mAttachInfo = null; 8666 } 8667 8668 /** 8669 * Store this view hierarchy's frozen state into the given container. 8670 * 8671 * @param container The SparseArray in which to save the view's state. 8672 * 8673 * @see #restoreHierarchyState(android.util.SparseArray) 8674 * @see #dispatchSaveInstanceState(android.util.SparseArray) 8675 * @see #onSaveInstanceState() 8676 */ 8677 public void saveHierarchyState(SparseArray<Parcelable> container) { 8678 dispatchSaveInstanceState(container); 8679 } 8680 8681 /** 8682 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 8683 * this view and its children. May be overridden to modify how freezing happens to a 8684 * view's children; for example, some views may want to not store state for their children. 8685 * 8686 * @param container The SparseArray in which to save the view's state. 8687 * 8688 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 8689 * @see #saveHierarchyState(android.util.SparseArray) 8690 * @see #onSaveInstanceState() 8691 */ 8692 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 8693 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 8694 mPrivateFlags &= ~SAVE_STATE_CALLED; 8695 Parcelable state = onSaveInstanceState(); 8696 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) { 8697 throw new IllegalStateException( 8698 "Derived class did not call super.onSaveInstanceState()"); 8699 } 8700 if (state != null) { 8701 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 8702 // + ": " + state); 8703 container.put(mID, state); 8704 } 8705 } 8706 } 8707 8708 /** 8709 * Hook allowing a view to generate a representation of its internal state 8710 * that can later be used to create a new instance with that same state. 8711 * This state should only contain information that is not persistent or can 8712 * not be reconstructed later. For example, you will never store your 8713 * current position on screen because that will be computed again when a 8714 * new instance of the view is placed in its view hierarchy. 8715 * <p> 8716 * Some examples of things you may store here: the current cursor position 8717 * in a text view (but usually not the text itself since that is stored in a 8718 * content provider or other persistent storage), the currently selected 8719 * item in a list view. 8720 * 8721 * @return Returns a Parcelable object containing the view's current dynamic 8722 * state, or null if there is nothing interesting to save. The 8723 * default implementation returns null. 8724 * @see #onRestoreInstanceState(android.os.Parcelable) 8725 * @see #saveHierarchyState(android.util.SparseArray) 8726 * @see #dispatchSaveInstanceState(android.util.SparseArray) 8727 * @see #setSaveEnabled(boolean) 8728 */ 8729 protected Parcelable onSaveInstanceState() { 8730 mPrivateFlags |= SAVE_STATE_CALLED; 8731 return BaseSavedState.EMPTY_STATE; 8732 } 8733 8734 /** 8735 * Restore this view hierarchy's frozen state from the given container. 8736 * 8737 * @param container The SparseArray which holds previously frozen states. 8738 * 8739 * @see #saveHierarchyState(android.util.SparseArray) 8740 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 8741 * @see #onRestoreInstanceState(android.os.Parcelable) 8742 */ 8743 public void restoreHierarchyState(SparseArray<Parcelable> container) { 8744 dispatchRestoreInstanceState(container); 8745 } 8746 8747 /** 8748 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 8749 * state for this view and its children. May be overridden to modify how restoring 8750 * happens to a view's children; for example, some views may want to not store state 8751 * for their children. 8752 * 8753 * @param container The SparseArray which holds previously saved state. 8754 * 8755 * @see #dispatchSaveInstanceState(android.util.SparseArray) 8756 * @see #restoreHierarchyState(android.util.SparseArray) 8757 * @see #onRestoreInstanceState(android.os.Parcelable) 8758 */ 8759 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 8760 if (mID != NO_ID) { 8761 Parcelable state = container.get(mID); 8762 if (state != null) { 8763 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 8764 // + ": " + state); 8765 mPrivateFlags &= ~SAVE_STATE_CALLED; 8766 onRestoreInstanceState(state); 8767 if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) { 8768 throw new IllegalStateException( 8769 "Derived class did not call super.onRestoreInstanceState()"); 8770 } 8771 } 8772 } 8773 } 8774 8775 /** 8776 * Hook allowing a view to re-apply a representation of its internal state that had previously 8777 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 8778 * null state. 8779 * 8780 * @param state The frozen state that had previously been returned by 8781 * {@link #onSaveInstanceState}. 8782 * 8783 * @see #onSaveInstanceState() 8784 * @see #restoreHierarchyState(android.util.SparseArray) 8785 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 8786 */ 8787 protected void onRestoreInstanceState(Parcelable state) { 8788 mPrivateFlags |= SAVE_STATE_CALLED; 8789 if (state != BaseSavedState.EMPTY_STATE && state != null) { 8790 throw new IllegalArgumentException("Wrong state class, expecting View State but " 8791 + "received " + state.getClass().toString() + " instead. This usually happens " 8792 + "when two views of different type have the same id in the same hierarchy. " 8793 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 8794 + "other views do not use the same id."); 8795 } 8796 } 8797 8798 /** 8799 * <p>Return the time at which the drawing of the view hierarchy started.</p> 8800 * 8801 * @return the drawing start time in milliseconds 8802 */ 8803 public long getDrawingTime() { 8804 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 8805 } 8806 8807 /** 8808 * <p>Enables or disables the duplication of the parent's state into this view. When 8809 * duplication is enabled, this view gets its drawable state from its parent rather 8810 * than from its own internal properties.</p> 8811 * 8812 * <p>Note: in the current implementation, setting this property to true after the 8813 * view was added to a ViewGroup might have no effect at all. This property should 8814 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 8815 * 8816 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 8817 * property is enabled, an exception will be thrown.</p> 8818 * 8819 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 8820 * parent, these states should not be affected by this method.</p> 8821 * 8822 * @param enabled True to enable duplication of the parent's drawable state, false 8823 * to disable it. 8824 * 8825 * @see #getDrawableState() 8826 * @see #isDuplicateParentStateEnabled() 8827 */ 8828 public void setDuplicateParentStateEnabled(boolean enabled) { 8829 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 8830 } 8831 8832 /** 8833 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 8834 * 8835 * @return True if this view's drawable state is duplicated from the parent, 8836 * false otherwise 8837 * 8838 * @see #getDrawableState() 8839 * @see #setDuplicateParentStateEnabled(boolean) 8840 */ 8841 public boolean isDuplicateParentStateEnabled() { 8842 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 8843 } 8844 8845 /** 8846 * <p>Specifies the type of layer backing this view. The layer can be 8847 * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or 8848 * {@link #LAYER_TYPE_HARDWARE hardware}.</p> 8849 * 8850 * <p>A layer is associated with an optional {@link android.graphics.Paint} 8851 * instance that controls how the layer is composed on screen. The following 8852 * properties of the paint are taken into account when composing the layer:</p> 8853 * <ul> 8854 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 8855 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 8856 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 8857 * </ul> 8858 * 8859 * <p>If this view has an alpha value set to < 1.0 by calling 8860 * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by 8861 * this view's alpha value. Calling {@link #setAlpha(float)} is therefore 8862 * equivalent to setting a hardware layer on this view and providing a paint with 8863 * the desired alpha value.<p> 8864 * 8865 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled}, 8866 * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware} 8867 * for more information on when and how to use layers.</p> 8868 * 8869 * @param layerType The ype of layer to use with this view, must be one of 8870 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 8871 * {@link #LAYER_TYPE_HARDWARE} 8872 * @param paint The paint used to compose the layer. This argument is optional 8873 * and can be null. It is ignored when the layer type is 8874 * {@link #LAYER_TYPE_NONE} 8875 * 8876 * @see #getLayerType() 8877 * @see #LAYER_TYPE_NONE 8878 * @see #LAYER_TYPE_SOFTWARE 8879 * @see #LAYER_TYPE_HARDWARE 8880 * @see #setAlpha(float) 8881 * 8882 * @attr ref android.R.styleable#View_layerType 8883 */ 8884 public void setLayerType(int layerType, Paint paint) { 8885 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 8886 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 8887 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 8888 } 8889 8890 if (layerType == mLayerType) { 8891 if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) { 8892 mLayerPaint = paint == null ? new Paint() : paint; 8893 invalidateParentCaches(); 8894 invalidate(true); 8895 } 8896 return; 8897 } 8898 8899 // Destroy any previous software drawing cache if needed 8900 switch (mLayerType) { 8901 case LAYER_TYPE_HARDWARE: 8902 if (mHardwareLayer != null) { 8903 mHardwareLayer.destroy(); 8904 mHardwareLayer = null; 8905 } 8906 // fall through - unaccelerated views may use software layer mechanism instead 8907 case LAYER_TYPE_SOFTWARE: 8908 if (mDrawingCache != null) { 8909 mDrawingCache.recycle(); 8910 mDrawingCache = null; 8911 } 8912 8913 if (mUnscaledDrawingCache != null) { 8914 mUnscaledDrawingCache.recycle(); 8915 mUnscaledDrawingCache = null; 8916 } 8917 break; 8918 default: 8919 break; 8920 } 8921 8922 mLayerType = layerType; 8923 final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE; 8924 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 8925 mLocalDirtyRect = layerDisabled ? null : new Rect(); 8926 8927 invalidateParentCaches(); 8928 invalidate(true); 8929 } 8930 8931 /** 8932 * Indicates what type of layer is currently associated with this view. By default 8933 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 8934 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 8935 * for more information on the different types of layers. 8936 * 8937 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 8938 * {@link #LAYER_TYPE_HARDWARE} 8939 * 8940 * @see #setLayerType(int, android.graphics.Paint) 8941 * @see #buildLayer() 8942 * @see #LAYER_TYPE_NONE 8943 * @see #LAYER_TYPE_SOFTWARE 8944 * @see #LAYER_TYPE_HARDWARE 8945 */ 8946 public int getLayerType() { 8947 return mLayerType; 8948 } 8949 8950 /** 8951 * Forces this view's layer to be created and this view to be rendered 8952 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 8953 * invoking this method will have no effect. 8954 * 8955 * This method can for instance be used to render a view into its layer before 8956 * starting an animation. If this view is complex, rendering into the layer 8957 * before starting the animation will avoid skipping frames. 8958 * 8959 * @throws IllegalStateException If this view is not attached to a window 8960 * 8961 * @see #setLayerType(int, android.graphics.Paint) 8962 */ 8963 public void buildLayer() { 8964 if (mLayerType == LAYER_TYPE_NONE) return; 8965 8966 if (mAttachInfo == null) { 8967 throw new IllegalStateException("This view must be attached to a window first"); 8968 } 8969 8970 switch (mLayerType) { 8971 case LAYER_TYPE_HARDWARE: 8972 getHardwareLayer(); 8973 break; 8974 case LAYER_TYPE_SOFTWARE: 8975 buildDrawingCache(true); 8976 break; 8977 } 8978 } 8979 8980 /** 8981 * <p>Returns a hardware layer that can be used to draw this view again 8982 * without executing its draw method.</p> 8983 * 8984 * @return A HardwareLayer ready to render, or null if an error occurred. 8985 */ 8986 HardwareLayer getHardwareLayer() { 8987 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null) { 8988 return null; 8989 } 8990 8991 final int width = mRight - mLeft; 8992 final int height = mBottom - mTop; 8993 8994 if (width == 0 || height == 0) { 8995 return null; 8996 } 8997 8998 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) { 8999 if (mHardwareLayer == null) { 9000 mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer( 9001 width, height, isOpaque()); 9002 mLocalDirtyRect.setEmpty(); 9003 } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) { 9004 mHardwareLayer.resize(width, height); 9005 mLocalDirtyRect.setEmpty(); 9006 } 9007 9008 Canvas currentCanvas = mAttachInfo.mHardwareCanvas; 9009 final HardwareCanvas canvas = mHardwareLayer.start(currentCanvas); 9010 mAttachInfo.mHardwareCanvas = canvas; 9011 try { 9012 canvas.setViewport(width, height); 9013 canvas.onPreDraw(mLocalDirtyRect); 9014 mLocalDirtyRect.setEmpty(); 9015 9016 final int restoreCount = canvas.save(); 9017 9018 computeScroll(); 9019 canvas.translate(-mScrollX, -mScrollY); 9020 9021 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 9022 9023 // Fast path for layouts with no backgrounds 9024 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 9025 mPrivateFlags &= ~DIRTY_MASK; 9026 dispatchDraw(canvas); 9027 } else { 9028 draw(canvas); 9029 } 9030 9031 canvas.restoreToCount(restoreCount); 9032 } finally { 9033 canvas.onPostDraw(); 9034 mHardwareLayer.end(currentCanvas); 9035 mAttachInfo.mHardwareCanvas = currentCanvas; 9036 } 9037 } 9038 9039 return mHardwareLayer; 9040 } 9041 9042 /** 9043 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 9044 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 9045 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 9046 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 9047 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 9048 * null.</p> 9049 * 9050 * <p>Enabling the drawing cache is similar to 9051 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 9052 * acceleration is turned off. When hardware acceleration is turned on, enabling the 9053 * drawing cache has no effect on rendering because the system uses a different mechanism 9054 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 9055 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 9056 * for information on how to enable software and hardware layers.</p> 9057 * 9058 * <p>This API can be used to manually generate 9059 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 9060 * {@link #getDrawingCache()}.</p> 9061 * 9062 * @param enabled true to enable the drawing cache, false otherwise 9063 * 9064 * @see #isDrawingCacheEnabled() 9065 * @see #getDrawingCache() 9066 * @see #buildDrawingCache() 9067 * @see #setLayerType(int, android.graphics.Paint) 9068 */ 9069 public void setDrawingCacheEnabled(boolean enabled) { 9070 mCachingFailed = false; 9071 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 9072 } 9073 9074 /** 9075 * <p>Indicates whether the drawing cache is enabled for this view.</p> 9076 * 9077 * @return true if the drawing cache is enabled 9078 * 9079 * @see #setDrawingCacheEnabled(boolean) 9080 * @see #getDrawingCache() 9081 */ 9082 @ViewDebug.ExportedProperty(category = "drawing") 9083 public boolean isDrawingCacheEnabled() { 9084 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 9085 } 9086 9087 /** 9088 * Debugging utility which recursively outputs the dirty state of a view and its 9089 * descendants. 9090 * 9091 * @hide 9092 */ 9093 @SuppressWarnings({"UnusedDeclaration"}) 9094 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 9095 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) + 9096 ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" + 9097 (mPrivateFlags & View.DRAWING_CACHE_VALID) + 9098 ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")"); 9099 if (clear) { 9100 mPrivateFlags &= clearMask; 9101 } 9102 if (this instanceof ViewGroup) { 9103 ViewGroup parent = (ViewGroup) this; 9104 final int count = parent.getChildCount(); 9105 for (int i = 0; i < count; i++) { 9106 final View child = parent.getChildAt(i); 9107 child.outputDirtyFlags(indent + " ", clear, clearMask); 9108 } 9109 } 9110 } 9111 9112 /** 9113 * This method is used by ViewGroup to cause its children to restore or recreate their 9114 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 9115 * to recreate its own display list, which would happen if it went through the normal 9116 * draw/dispatchDraw mechanisms. 9117 * 9118 * @hide 9119 */ 9120 protected void dispatchGetDisplayList() {} 9121 9122 /** 9123 * A view that is not attached or hardware accelerated cannot create a display list. 9124 * This method checks these conditions and returns the appropriate result. 9125 * 9126 * @return true if view has the ability to create a display list, false otherwise. 9127 * 9128 * @hide 9129 */ 9130 public boolean canHaveDisplayList() { 9131 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 9132 } 9133 9134 /** 9135 * <p>Returns a display list that can be used to draw this view again 9136 * without executing its draw method.</p> 9137 * 9138 * @return A DisplayList ready to replay, or null if caching is not enabled. 9139 * 9140 * @hide 9141 */ 9142 public DisplayList getDisplayList() { 9143 if (!canHaveDisplayList()) { 9144 return null; 9145 } 9146 9147 if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || 9148 mDisplayList == null || !mDisplayList.isValid() || 9149 mRecreateDisplayList)) { 9150 // Don't need to recreate the display list, just need to tell our 9151 // children to restore/recreate theirs 9152 if (mDisplayList != null && mDisplayList.isValid() && 9153 !mRecreateDisplayList) { 9154 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 9155 mPrivateFlags &= ~DIRTY_MASK; 9156 dispatchGetDisplayList(); 9157 9158 return mDisplayList; 9159 } 9160 9161 // If we got here, we're recreating it. Mark it as such to ensure that 9162 // we copy in child display lists into ours in drawChild() 9163 mRecreateDisplayList = true; 9164 if (mDisplayList == null) { 9165 mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList(this); 9166 // If we're creating a new display list, make sure our parent gets invalidated 9167 // since they will need to recreate their display list to account for this 9168 // new child display list. 9169 invalidateParentCaches(); 9170 } 9171 9172 final HardwareCanvas canvas = mDisplayList.start(); 9173 try { 9174 int width = mRight - mLeft; 9175 int height = mBottom - mTop; 9176 9177 canvas.setViewport(width, height); 9178 // The dirty rect should always be null for a display list 9179 canvas.onPreDraw(null); 9180 9181 final int restoreCount = canvas.save(); 9182 9183 computeScroll(); 9184 canvas.translate(-mScrollX, -mScrollY); 9185 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 9186 9187 // Fast path for layouts with no backgrounds 9188 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 9189 mPrivateFlags &= ~DIRTY_MASK; 9190 dispatchDraw(canvas); 9191 } else { 9192 draw(canvas); 9193 } 9194 9195 canvas.restoreToCount(restoreCount); 9196 } finally { 9197 canvas.onPostDraw(); 9198 9199 mDisplayList.end(); 9200 } 9201 } else { 9202 mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID; 9203 mPrivateFlags &= ~DIRTY_MASK; 9204 } 9205 9206 return mDisplayList; 9207 } 9208 9209 /** 9210 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 9211 * 9212 * @return A non-scaled bitmap representing this view or null if cache is disabled. 9213 * 9214 * @see #getDrawingCache(boolean) 9215 */ 9216 public Bitmap getDrawingCache() { 9217 return getDrawingCache(false); 9218 } 9219 9220 /** 9221 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 9222 * is null when caching is disabled. If caching is enabled and the cache is not ready, 9223 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 9224 * draw from the cache when the cache is enabled. To benefit from the cache, you must 9225 * request the drawing cache by calling this method and draw it on screen if the 9226 * returned bitmap is not null.</p> 9227 * 9228 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 9229 * this method will create a bitmap of the same size as this view. Because this bitmap 9230 * will be drawn scaled by the parent ViewGroup, the result on screen might show 9231 * scaling artifacts. To avoid such artifacts, you should call this method by setting 9232 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 9233 * size than the view. This implies that your application must be able to handle this 9234 * size.</p> 9235 * 9236 * @param autoScale Indicates whether the generated bitmap should be scaled based on 9237 * the current density of the screen when the application is in compatibility 9238 * mode. 9239 * 9240 * @return A bitmap representing this view or null if cache is disabled. 9241 * 9242 * @see #setDrawingCacheEnabled(boolean) 9243 * @see #isDrawingCacheEnabled() 9244 * @see #buildDrawingCache(boolean) 9245 * @see #destroyDrawingCache() 9246 */ 9247 public Bitmap getDrawingCache(boolean autoScale) { 9248 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 9249 return null; 9250 } 9251 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 9252 buildDrawingCache(autoScale); 9253 } 9254 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 9255 } 9256 9257 /** 9258 * <p>Frees the resources used by the drawing cache. If you call 9259 * {@link #buildDrawingCache()} manually without calling 9260 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 9261 * should cleanup the cache with this method afterwards.</p> 9262 * 9263 * @see #setDrawingCacheEnabled(boolean) 9264 * @see #buildDrawingCache() 9265 * @see #getDrawingCache() 9266 */ 9267 public void destroyDrawingCache() { 9268 if (mDrawingCache != null) { 9269 mDrawingCache.recycle(); 9270 mDrawingCache = null; 9271 } 9272 if (mUnscaledDrawingCache != null) { 9273 mUnscaledDrawingCache.recycle(); 9274 mUnscaledDrawingCache = null; 9275 } 9276 } 9277 9278 /** 9279 * Setting a solid background color for the drawing cache's bitmaps will improve 9280 * perfromance and memory usage. Note, though that this should only be used if this 9281 * view will always be drawn on top of a solid color. 9282 * 9283 * @param color The background color to use for the drawing cache's bitmap 9284 * 9285 * @see #setDrawingCacheEnabled(boolean) 9286 * @see #buildDrawingCache() 9287 * @see #getDrawingCache() 9288 */ 9289 public void setDrawingCacheBackgroundColor(int color) { 9290 if (color != mDrawingCacheBackgroundColor) { 9291 mDrawingCacheBackgroundColor = color; 9292 mPrivateFlags &= ~DRAWING_CACHE_VALID; 9293 } 9294 } 9295 9296 /** 9297 * @see #setDrawingCacheBackgroundColor(int) 9298 * 9299 * @return The background color to used for the drawing cache's bitmap 9300 */ 9301 public int getDrawingCacheBackgroundColor() { 9302 return mDrawingCacheBackgroundColor; 9303 } 9304 9305 /** 9306 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 9307 * 9308 * @see #buildDrawingCache(boolean) 9309 */ 9310 public void buildDrawingCache() { 9311 buildDrawingCache(false); 9312 } 9313 9314 /** 9315 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 9316 * 9317 * <p>If you call {@link #buildDrawingCache()} manually without calling 9318 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 9319 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 9320 * 9321 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 9322 * this method will create a bitmap of the same size as this view. Because this bitmap 9323 * will be drawn scaled by the parent ViewGroup, the result on screen might show 9324 * scaling artifacts. To avoid such artifacts, you should call this method by setting 9325 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 9326 * size than the view. This implies that your application must be able to handle this 9327 * size.</p> 9328 * 9329 * <p>You should avoid calling this method when hardware acceleration is enabled. If 9330 * you do not need the drawing cache bitmap, calling this method will increase memory 9331 * usage and cause the view to be rendered in software once, thus negatively impacting 9332 * performance.</p> 9333 * 9334 * @see #getDrawingCache() 9335 * @see #destroyDrawingCache() 9336 */ 9337 public void buildDrawingCache(boolean autoScale) { 9338 if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ? 9339 mDrawingCache == null : mUnscaledDrawingCache == null)) { 9340 mCachingFailed = false; 9341 9342 if (ViewDebug.TRACE_HIERARCHY) { 9343 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE); 9344 } 9345 9346 int width = mRight - mLeft; 9347 int height = mBottom - mTop; 9348 9349 final AttachInfo attachInfo = mAttachInfo; 9350 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 9351 9352 if (autoScale && scalingRequired) { 9353 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 9354 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 9355 } 9356 9357 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 9358 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 9359 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 9360 9361 if (width <= 0 || height <= 0 || 9362 // Projected bitmap size in bytes 9363 (width * height * (opaque && !use32BitCache ? 2 : 4) > 9364 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) { 9365 destroyDrawingCache(); 9366 mCachingFailed = true; 9367 return; 9368 } 9369 9370 boolean clear = true; 9371 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 9372 9373 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 9374 Bitmap.Config quality; 9375 if (!opaque) { 9376 // Never pick ARGB_4444 because it looks awful 9377 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 9378 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 9379 case DRAWING_CACHE_QUALITY_AUTO: 9380 quality = Bitmap.Config.ARGB_8888; 9381 break; 9382 case DRAWING_CACHE_QUALITY_LOW: 9383 quality = Bitmap.Config.ARGB_8888; 9384 break; 9385 case DRAWING_CACHE_QUALITY_HIGH: 9386 quality = Bitmap.Config.ARGB_8888; 9387 break; 9388 default: 9389 quality = Bitmap.Config.ARGB_8888; 9390 break; 9391 } 9392 } else { 9393 // Optimization for translucent windows 9394 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 9395 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 9396 } 9397 9398 // Try to cleanup memory 9399 if (bitmap != null) bitmap.recycle(); 9400 9401 try { 9402 bitmap = Bitmap.createBitmap(width, height, quality); 9403 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 9404 if (autoScale) { 9405 mDrawingCache = bitmap; 9406 } else { 9407 mUnscaledDrawingCache = bitmap; 9408 } 9409 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 9410 } catch (OutOfMemoryError e) { 9411 // If there is not enough memory to create the bitmap cache, just 9412 // ignore the issue as bitmap caches are not required to draw the 9413 // view hierarchy 9414 if (autoScale) { 9415 mDrawingCache = null; 9416 } else { 9417 mUnscaledDrawingCache = null; 9418 } 9419 mCachingFailed = true; 9420 return; 9421 } 9422 9423 clear = drawingCacheBackgroundColor != 0; 9424 } 9425 9426 Canvas canvas; 9427 if (attachInfo != null) { 9428 canvas = attachInfo.mCanvas; 9429 if (canvas == null) { 9430 canvas = new Canvas(); 9431 } 9432 canvas.setBitmap(bitmap); 9433 // Temporarily clobber the cached Canvas in case one of our children 9434 // is also using a drawing cache. Without this, the children would 9435 // steal the canvas by attaching their own bitmap to it and bad, bad 9436 // thing would happen (invisible views, corrupted drawings, etc.) 9437 attachInfo.mCanvas = null; 9438 } else { 9439 // This case should hopefully never or seldom happen 9440 canvas = new Canvas(bitmap); 9441 } 9442 9443 if (clear) { 9444 bitmap.eraseColor(drawingCacheBackgroundColor); 9445 } 9446 9447 computeScroll(); 9448 final int restoreCount = canvas.save(); 9449 9450 if (autoScale && scalingRequired) { 9451 final float scale = attachInfo.mApplicationScale; 9452 canvas.scale(scale, scale); 9453 } 9454 9455 canvas.translate(-mScrollX, -mScrollY); 9456 9457 mPrivateFlags |= DRAWN; 9458 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 9459 mLayerType != LAYER_TYPE_NONE) { 9460 mPrivateFlags |= DRAWING_CACHE_VALID; 9461 } 9462 9463 // Fast path for layouts with no backgrounds 9464 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 9465 if (ViewDebug.TRACE_HIERARCHY) { 9466 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); 9467 } 9468 mPrivateFlags &= ~DIRTY_MASK; 9469 dispatchDraw(canvas); 9470 } else { 9471 draw(canvas); 9472 } 9473 9474 canvas.restoreToCount(restoreCount); 9475 9476 if (attachInfo != null) { 9477 // Restore the cached Canvas for our siblings 9478 attachInfo.mCanvas = canvas; 9479 } 9480 } 9481 } 9482 9483 /** 9484 * Create a snapshot of the view into a bitmap. We should probably make 9485 * some form of this public, but should think about the API. 9486 */ 9487 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 9488 int width = mRight - mLeft; 9489 int height = mBottom - mTop; 9490 9491 final AttachInfo attachInfo = mAttachInfo; 9492 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 9493 width = (int) ((width * scale) + 0.5f); 9494 height = (int) ((height * scale) + 0.5f); 9495 9496 Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality); 9497 if (bitmap == null) { 9498 throw new OutOfMemoryError(); 9499 } 9500 9501 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 9502 9503 Canvas canvas; 9504 if (attachInfo != null) { 9505 canvas = attachInfo.mCanvas; 9506 if (canvas == null) { 9507 canvas = new Canvas(); 9508 } 9509 canvas.setBitmap(bitmap); 9510 // Temporarily clobber the cached Canvas in case one of our children 9511 // is also using a drawing cache. Without this, the children would 9512 // steal the canvas by attaching their own bitmap to it and bad, bad 9513 // things would happen (invisible views, corrupted drawings, etc.) 9514 attachInfo.mCanvas = null; 9515 } else { 9516 // This case should hopefully never or seldom happen 9517 canvas = new Canvas(bitmap); 9518 } 9519 9520 if ((backgroundColor & 0xff000000) != 0) { 9521 bitmap.eraseColor(backgroundColor); 9522 } 9523 9524 computeScroll(); 9525 final int restoreCount = canvas.save(); 9526 canvas.scale(scale, scale); 9527 canvas.translate(-mScrollX, -mScrollY); 9528 9529 // Temporarily remove the dirty mask 9530 int flags = mPrivateFlags; 9531 mPrivateFlags &= ~DIRTY_MASK; 9532 9533 // Fast path for layouts with no backgrounds 9534 if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 9535 dispatchDraw(canvas); 9536 } else { 9537 draw(canvas); 9538 } 9539 9540 mPrivateFlags = flags; 9541 9542 canvas.restoreToCount(restoreCount); 9543 9544 if (attachInfo != null) { 9545 // Restore the cached Canvas for our siblings 9546 attachInfo.mCanvas = canvas; 9547 } 9548 9549 return bitmap; 9550 } 9551 9552 /** 9553 * Indicates whether this View is currently in edit mode. A View is usually 9554 * in edit mode when displayed within a developer tool. For instance, if 9555 * this View is being drawn by a visual user interface builder, this method 9556 * should return true. 9557 * 9558 * Subclasses should check the return value of this method to provide 9559 * different behaviors if their normal behavior might interfere with the 9560 * host environment. For instance: the class spawns a thread in its 9561 * constructor, the drawing code relies on device-specific features, etc. 9562 * 9563 * This method is usually checked in the drawing code of custom widgets. 9564 * 9565 * @return True if this View is in edit mode, false otherwise. 9566 */ 9567 public boolean isInEditMode() { 9568 return false; 9569 } 9570 9571 /** 9572 * If the View draws content inside its padding and enables fading edges, 9573 * it needs to support padding offsets. Padding offsets are added to the 9574 * fading edges to extend the length of the fade so that it covers pixels 9575 * drawn inside the padding. 9576 * 9577 * Subclasses of this class should override this method if they need 9578 * to draw content inside the padding. 9579 * 9580 * @return True if padding offset must be applied, false otherwise. 9581 * 9582 * @see #getLeftPaddingOffset() 9583 * @see #getRightPaddingOffset() 9584 * @see #getTopPaddingOffset() 9585 * @see #getBottomPaddingOffset() 9586 * 9587 * @since CURRENT 9588 */ 9589 protected boolean isPaddingOffsetRequired() { 9590 return false; 9591 } 9592 9593 /** 9594 * Amount by which to extend the left fading region. Called only when 9595 * {@link #isPaddingOffsetRequired()} returns true. 9596 * 9597 * @return The left padding offset in pixels. 9598 * 9599 * @see #isPaddingOffsetRequired() 9600 * 9601 * @since CURRENT 9602 */ 9603 protected int getLeftPaddingOffset() { 9604 return 0; 9605 } 9606 9607 /** 9608 * Amount by which to extend the right fading region. Called only when 9609 * {@link #isPaddingOffsetRequired()} returns true. 9610 * 9611 * @return The right padding offset in pixels. 9612 * 9613 * @see #isPaddingOffsetRequired() 9614 * 9615 * @since CURRENT 9616 */ 9617 protected int getRightPaddingOffset() { 9618 return 0; 9619 } 9620 9621 /** 9622 * Amount by which to extend the top fading region. Called only when 9623 * {@link #isPaddingOffsetRequired()} returns true. 9624 * 9625 * @return The top padding offset in pixels. 9626 * 9627 * @see #isPaddingOffsetRequired() 9628 * 9629 * @since CURRENT 9630 */ 9631 protected int getTopPaddingOffset() { 9632 return 0; 9633 } 9634 9635 /** 9636 * Amount by which to extend the bottom fading region. Called only when 9637 * {@link #isPaddingOffsetRequired()} returns true. 9638 * 9639 * @return The bottom padding offset in pixels. 9640 * 9641 * @see #isPaddingOffsetRequired() 9642 * 9643 * @since CURRENT 9644 */ 9645 protected int getBottomPaddingOffset() { 9646 return 0; 9647 } 9648 9649 /** 9650 * <p>Indicates whether this view is attached to an hardware accelerated 9651 * window or not.</p> 9652 * 9653 * <p>Even if this method returns true, it does not mean that every call 9654 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 9655 * accelerated {@link android.graphics.Canvas}. For instance, if this view 9656 * is drawn onto an offscren {@link android.graphics.Bitmap} and its 9657 * window is hardware accelerated, 9658 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 9659 * return false, and this method will return true.</p> 9660 * 9661 * @return True if the view is attached to a window and the window is 9662 * hardware accelerated; false in any other case. 9663 */ 9664 public boolean isHardwareAccelerated() { 9665 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 9666 } 9667 9668 /** 9669 * Manually render this view (and all of its children) to the given Canvas. 9670 * The view must have already done a full layout before this function is 9671 * called. When implementing a view, implement 9672 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 9673 * If you do need to override this method, call the superclass version. 9674 * 9675 * @param canvas The Canvas to which the View is rendered. 9676 */ 9677 public void draw(Canvas canvas) { 9678 if (ViewDebug.TRACE_HIERARCHY) { 9679 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); 9680 } 9681 9682 final int privateFlags = mPrivateFlags; 9683 final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE && 9684 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 9685 mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN; 9686 9687 /* 9688 * Draw traversal performs several drawing steps which must be executed 9689 * in the appropriate order: 9690 * 9691 * 1. Draw the background 9692 * 2. If necessary, save the canvas' layers to prepare for fading 9693 * 3. Draw view's content 9694 * 4. Draw children 9695 * 5. If necessary, draw the fading edges and restore layers 9696 * 6. Draw decorations (scrollbars for instance) 9697 */ 9698 9699 // Step 1, draw the background, if needed 9700 int saveCount; 9701 9702 if (!dirtyOpaque) { 9703 final Drawable background = mBGDrawable; 9704 if (background != null) { 9705 final int scrollX = mScrollX; 9706 final int scrollY = mScrollY; 9707 9708 if (mBackgroundSizeChanged) { 9709 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 9710 mBackgroundSizeChanged = false; 9711 } 9712 9713 if ((scrollX | scrollY) == 0) { 9714 background.draw(canvas); 9715 } else { 9716 canvas.translate(scrollX, scrollY); 9717 background.draw(canvas); 9718 canvas.translate(-scrollX, -scrollY); 9719 } 9720 } 9721 } 9722 9723 // skip step 2 & 5 if possible (common case) 9724 final int viewFlags = mViewFlags; 9725 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 9726 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 9727 if (!verticalEdges && !horizontalEdges) { 9728 // Step 3, draw the content 9729 if (!dirtyOpaque) onDraw(canvas); 9730 9731 // Step 4, draw the children 9732 dispatchDraw(canvas); 9733 9734 // Step 6, draw decorations (scrollbars) 9735 onDrawScrollBars(canvas); 9736 9737 // we're done... 9738 return; 9739 } 9740 9741 /* 9742 * Here we do the full fledged routine... 9743 * (this is an uncommon case where speed matters less, 9744 * this is why we repeat some of the tests that have been 9745 * done above) 9746 */ 9747 9748 boolean drawTop = false; 9749 boolean drawBottom = false; 9750 boolean drawLeft = false; 9751 boolean drawRight = false; 9752 9753 float topFadeStrength = 0.0f; 9754 float bottomFadeStrength = 0.0f; 9755 float leftFadeStrength = 0.0f; 9756 float rightFadeStrength = 0.0f; 9757 9758 // Step 2, save the canvas' layers 9759 int paddingLeft = mPaddingLeft; 9760 int paddingTop = mPaddingTop; 9761 9762 final boolean offsetRequired = isPaddingOffsetRequired(); 9763 if (offsetRequired) { 9764 paddingLeft += getLeftPaddingOffset(); 9765 paddingTop += getTopPaddingOffset(); 9766 } 9767 9768 int left = mScrollX + paddingLeft; 9769 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 9770 int top = mScrollY + paddingTop; 9771 int bottom = top + mBottom - mTop - mPaddingBottom - paddingTop; 9772 9773 if (offsetRequired) { 9774 right += getRightPaddingOffset(); 9775 bottom += getBottomPaddingOffset(); 9776 } 9777 9778 final ScrollabilityCache scrollabilityCache = mScrollCache; 9779 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 9780 int length = (int) fadeHeight; 9781 9782 // clip the fade length if top and bottom fades overlap 9783 // overlapping fades produce odd-looking artifacts 9784 if (verticalEdges && (top + length > bottom - length)) { 9785 length = (bottom - top) / 2; 9786 } 9787 9788 // also clip horizontal fades if necessary 9789 if (horizontalEdges && (left + length > right - length)) { 9790 length = (right - left) / 2; 9791 } 9792 9793 if (verticalEdges) { 9794 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 9795 drawTop = topFadeStrength * fadeHeight > 1.0f; 9796 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 9797 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 9798 } 9799 9800 if (horizontalEdges) { 9801 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 9802 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 9803 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 9804 drawRight = rightFadeStrength * fadeHeight > 1.0f; 9805 } 9806 9807 saveCount = canvas.getSaveCount(); 9808 9809 int solidColor = getSolidColor(); 9810 if (solidColor == 0) { 9811 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 9812 9813 if (drawTop) { 9814 canvas.saveLayer(left, top, right, top + length, null, flags); 9815 } 9816 9817 if (drawBottom) { 9818 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 9819 } 9820 9821 if (drawLeft) { 9822 canvas.saveLayer(left, top, left + length, bottom, null, flags); 9823 } 9824 9825 if (drawRight) { 9826 canvas.saveLayer(right - length, top, right, bottom, null, flags); 9827 } 9828 } else { 9829 scrollabilityCache.setFadeColor(solidColor); 9830 } 9831 9832 // Step 3, draw the content 9833 if (!dirtyOpaque) onDraw(canvas); 9834 9835 // Step 4, draw the children 9836 dispatchDraw(canvas); 9837 9838 // Step 5, draw the fade effect and restore layers 9839 final Paint p = scrollabilityCache.paint; 9840 final Matrix matrix = scrollabilityCache.matrix; 9841 final Shader fade = scrollabilityCache.shader; 9842 9843 if (drawTop) { 9844 matrix.setScale(1, fadeHeight * topFadeStrength); 9845 matrix.postTranslate(left, top); 9846 fade.setLocalMatrix(matrix); 9847 canvas.drawRect(left, top, right, top + length, p); 9848 } 9849 9850 if (drawBottom) { 9851 matrix.setScale(1, fadeHeight * bottomFadeStrength); 9852 matrix.postRotate(180); 9853 matrix.postTranslate(left, bottom); 9854 fade.setLocalMatrix(matrix); 9855 canvas.drawRect(left, bottom - length, right, bottom, p); 9856 } 9857 9858 if (drawLeft) { 9859 matrix.setScale(1, fadeHeight * leftFadeStrength); 9860 matrix.postRotate(-90); 9861 matrix.postTranslate(left, top); 9862 fade.setLocalMatrix(matrix); 9863 canvas.drawRect(left, top, left + length, bottom, p); 9864 } 9865 9866 if (drawRight) { 9867 matrix.setScale(1, fadeHeight * rightFadeStrength); 9868 matrix.postRotate(90); 9869 matrix.postTranslate(right, top); 9870 fade.setLocalMatrix(matrix); 9871 canvas.drawRect(right - length, top, right, bottom, p); 9872 } 9873 9874 canvas.restoreToCount(saveCount); 9875 9876 // Step 6, draw decorations (scrollbars) 9877 onDrawScrollBars(canvas); 9878 } 9879 9880 /** 9881 * Override this if your view is known to always be drawn on top of a solid color background, 9882 * and needs to draw fading edges. Returning a non-zero color enables the view system to 9883 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 9884 * should be set to 0xFF. 9885 * 9886 * @see #setVerticalFadingEdgeEnabled(boolean) 9887 * @see #setHorizontalFadingEdgeEnabled(boolean) 9888 * 9889 * @return The known solid color background for this view, or 0 if the color may vary 9890 */ 9891 @ViewDebug.ExportedProperty(category = "drawing") 9892 public int getSolidColor() { 9893 return 0; 9894 } 9895 9896 /** 9897 * Build a human readable string representation of the specified view flags. 9898 * 9899 * @param flags the view flags to convert to a string 9900 * @return a String representing the supplied flags 9901 */ 9902 private static String printFlags(int flags) { 9903 String output = ""; 9904 int numFlags = 0; 9905 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 9906 output += "TAKES_FOCUS"; 9907 numFlags++; 9908 } 9909 9910 switch (flags & VISIBILITY_MASK) { 9911 case INVISIBLE: 9912 if (numFlags > 0) { 9913 output += " "; 9914 } 9915 output += "INVISIBLE"; 9916 // USELESS HERE numFlags++; 9917 break; 9918 case GONE: 9919 if (numFlags > 0) { 9920 output += " "; 9921 } 9922 output += "GONE"; 9923 // USELESS HERE numFlags++; 9924 break; 9925 default: 9926 break; 9927 } 9928 return output; 9929 } 9930 9931 /** 9932 * Build a human readable string representation of the specified private 9933 * view flags. 9934 * 9935 * @param privateFlags the private view flags to convert to a string 9936 * @return a String representing the supplied flags 9937 */ 9938 private static String printPrivateFlags(int privateFlags) { 9939 String output = ""; 9940 int numFlags = 0; 9941 9942 if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) { 9943 output += "WANTS_FOCUS"; 9944 numFlags++; 9945 } 9946 9947 if ((privateFlags & FOCUSED) == FOCUSED) { 9948 if (numFlags > 0) { 9949 output += " "; 9950 } 9951 output += "FOCUSED"; 9952 numFlags++; 9953 } 9954 9955 if ((privateFlags & SELECTED) == SELECTED) { 9956 if (numFlags > 0) { 9957 output += " "; 9958 } 9959 output += "SELECTED"; 9960 numFlags++; 9961 } 9962 9963 if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) { 9964 if (numFlags > 0) { 9965 output += " "; 9966 } 9967 output += "IS_ROOT_NAMESPACE"; 9968 numFlags++; 9969 } 9970 9971 if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) { 9972 if (numFlags > 0) { 9973 output += " "; 9974 } 9975 output += "HAS_BOUNDS"; 9976 numFlags++; 9977 } 9978 9979 if ((privateFlags & DRAWN) == DRAWN) { 9980 if (numFlags > 0) { 9981 output += " "; 9982 } 9983 output += "DRAWN"; 9984 // USELESS HERE numFlags++; 9985 } 9986 return output; 9987 } 9988 9989 /** 9990 * <p>Indicates whether or not this view's layout will be requested during 9991 * the next hierarchy layout pass.</p> 9992 * 9993 * @return true if the layout will be forced during next layout pass 9994 */ 9995 public boolean isLayoutRequested() { 9996 return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT; 9997 } 9998 9999 /** 10000 * <p>Indicates whether or not this view's layout is right-to-left. This is resolved from 10001 * layout attribute and/or the inherited value from the parent.</p> 10002 * 10003 * @return true if the layout is right-to-left. 10004 */ 10005 public boolean isLayoutRtl() { 10006 return (mPrivateFlags2 & RESOLVED_LAYOUT_RTL) == RESOLVED_LAYOUT_RTL; 10007 } 10008 10009 /** 10010 * Assign a size and position to a view and all of its 10011 * descendants 10012 * 10013 * <p>This is the second phase of the layout mechanism. 10014 * (The first is measuring). In this phase, each parent calls 10015 * layout on all of its children to position them. 10016 * This is typically done using the child measurements 10017 * that were stored in the measure pass().</p> 10018 * 10019 * <p>Derived classes should not override this method. 10020 * Derived classes with children should override 10021 * onLayout. In that method, they should 10022 * call layout on each of their children.</p> 10023 * 10024 * @param l Left position, relative to parent 10025 * @param t Top position, relative to parent 10026 * @param r Right position, relative to parent 10027 * @param b Bottom position, relative to parent 10028 */ 10029 @SuppressWarnings({"unchecked"}) 10030 public void layout(int l, int t, int r, int b) { 10031 int oldL = mLeft; 10032 int oldT = mTop; 10033 int oldB = mBottom; 10034 int oldR = mRight; 10035 boolean changed = setFrame(l, t, r, b); 10036 if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) { 10037 if (ViewDebug.TRACE_HIERARCHY) { 10038 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT); 10039 } 10040 10041 onLayout(changed, l, t, r, b); 10042 mPrivateFlags &= ~LAYOUT_REQUIRED; 10043 10044 if (mOnLayoutChangeListeners != null) { 10045 ArrayList<OnLayoutChangeListener> listenersCopy = 10046 (ArrayList<OnLayoutChangeListener>) mOnLayoutChangeListeners.clone(); 10047 int numListeners = listenersCopy.size(); 10048 for (int i = 0; i < numListeners; ++i) { 10049 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 10050 } 10051 } 10052 } 10053 mPrivateFlags &= ~FORCE_LAYOUT; 10054 } 10055 10056 /** 10057 * Called from layout when this view should 10058 * assign a size and position to each of its children. 10059 * 10060 * Derived classes with children should override 10061 * this method and call layout on each of 10062 * their children. 10063 * @param changed This is a new size or position for this view 10064 * @param left Left position, relative to parent 10065 * @param top Top position, relative to parent 10066 * @param right Right position, relative to parent 10067 * @param bottom Bottom position, relative to parent 10068 */ 10069 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 10070 } 10071 10072 /** 10073 * Assign a size and position to this view. 10074 * 10075 * This is called from layout. 10076 * 10077 * @param left Left position, relative to parent 10078 * @param top Top position, relative to parent 10079 * @param right Right position, relative to parent 10080 * @param bottom Bottom position, relative to parent 10081 * @return true if the new size and position are different than the 10082 * previous ones 10083 * {@hide} 10084 */ 10085 protected boolean setFrame(int left, int top, int right, int bottom) { 10086 boolean changed = false; 10087 10088 if (DBG) { 10089 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 10090 + right + "," + bottom + ")"); 10091 } 10092 10093 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 10094 changed = true; 10095 10096 // Remember our drawn bit 10097 int drawn = mPrivateFlags & DRAWN; 10098 10099 // Invalidate our old position 10100 invalidate(true); 10101 10102 10103 int oldWidth = mRight - mLeft; 10104 int oldHeight = mBottom - mTop; 10105 10106 mLeft = left; 10107 mTop = top; 10108 mRight = right; 10109 mBottom = bottom; 10110 10111 mPrivateFlags |= HAS_BOUNDS; 10112 10113 int newWidth = right - left; 10114 int newHeight = bottom - top; 10115 10116 if (newWidth != oldWidth || newHeight != oldHeight) { 10117 if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) { 10118 // A change in dimension means an auto-centered pivot point changes, too 10119 mMatrixDirty = true; 10120 } 10121 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 10122 } 10123 10124 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 10125 // If we are visible, force the DRAWN bit to on so that 10126 // this invalidate will go through (at least to our parent). 10127 // This is because someone may have invalidated this view 10128 // before this call to setFrame came in, thereby clearing 10129 // the DRAWN bit. 10130 mPrivateFlags |= DRAWN; 10131 invalidate(true); 10132 // parent display list may need to be recreated based on a change in the bounds 10133 // of any child 10134 invalidateParentCaches(); 10135 } 10136 10137 // Reset drawn bit to original value (invalidate turns it off) 10138 mPrivateFlags |= drawn; 10139 10140 mBackgroundSizeChanged = true; 10141 } 10142 return changed; 10143 } 10144 10145 /** 10146 * Finalize inflating a view from XML. This is called as the last phase 10147 * of inflation, after all child views have been added. 10148 * 10149 * <p>Even if the subclass overrides onFinishInflate, they should always be 10150 * sure to call the super method, so that we get called. 10151 */ 10152 protected void onFinishInflate() { 10153 } 10154 10155 /** 10156 * Returns the resources associated with this view. 10157 * 10158 * @return Resources object. 10159 */ 10160 public Resources getResources() { 10161 return mResources; 10162 } 10163 10164 /** 10165 * Invalidates the specified Drawable. 10166 * 10167 * @param drawable the drawable to invalidate 10168 */ 10169 public void invalidateDrawable(Drawable drawable) { 10170 if (verifyDrawable(drawable)) { 10171 final Rect dirty = drawable.getBounds(); 10172 final int scrollX = mScrollX; 10173 final int scrollY = mScrollY; 10174 10175 invalidate(dirty.left + scrollX, dirty.top + scrollY, 10176 dirty.right + scrollX, dirty.bottom + scrollY); 10177 } 10178 } 10179 10180 /** 10181 * Schedules an action on a drawable to occur at a specified time. 10182 * 10183 * @param who the recipient of the action 10184 * @param what the action to run on the drawable 10185 * @param when the time at which the action must occur. Uses the 10186 * {@link SystemClock#uptimeMillis} timebase. 10187 */ 10188 public void scheduleDrawable(Drawable who, Runnable what, long when) { 10189 if (verifyDrawable(who) && what != null && mAttachInfo != null) { 10190 mAttachInfo.mHandler.postAtTime(what, who, when); 10191 } 10192 } 10193 10194 /** 10195 * Cancels a scheduled action on a drawable. 10196 * 10197 * @param who the recipient of the action 10198 * @param what the action to cancel 10199 */ 10200 public void unscheduleDrawable(Drawable who, Runnable what) { 10201 if (verifyDrawable(who) && what != null && mAttachInfo != null) { 10202 mAttachInfo.mHandler.removeCallbacks(what, who); 10203 } 10204 } 10205 10206 /** 10207 * Unschedule any events associated with the given Drawable. This can be 10208 * used when selecting a new Drawable into a view, so that the previous 10209 * one is completely unscheduled. 10210 * 10211 * @param who The Drawable to unschedule. 10212 * 10213 * @see #drawableStateChanged 10214 */ 10215 public void unscheduleDrawable(Drawable who) { 10216 if (mAttachInfo != null) { 10217 mAttachInfo.mHandler.removeCallbacksAndMessages(who); 10218 } 10219 } 10220 10221 /** 10222 * If your view subclass is displaying its own Drawable objects, it should 10223 * override this function and return true for any Drawable it is 10224 * displaying. This allows animations for those drawables to be 10225 * scheduled. 10226 * 10227 * <p>Be sure to call through to the super class when overriding this 10228 * function. 10229 * 10230 * @param who The Drawable to verify. Return true if it is one you are 10231 * displaying, else return the result of calling through to the 10232 * super class. 10233 * 10234 * @return boolean If true than the Drawable is being displayed in the 10235 * view; else false and it is not allowed to animate. 10236 * 10237 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 10238 * @see #drawableStateChanged() 10239 */ 10240 protected boolean verifyDrawable(Drawable who) { 10241 return who == mBGDrawable; 10242 } 10243 10244 /** 10245 * This function is called whenever the state of the view changes in such 10246 * a way that it impacts the state of drawables being shown. 10247 * 10248 * <p>Be sure to call through to the superclass when overriding this 10249 * function. 10250 * 10251 * @see Drawable#setState(int[]) 10252 */ 10253 protected void drawableStateChanged() { 10254 Drawable d = mBGDrawable; 10255 if (d != null && d.isStateful()) { 10256 d.setState(getDrawableState()); 10257 } 10258 } 10259 10260 /** 10261 * Call this to force a view to update its drawable state. This will cause 10262 * drawableStateChanged to be called on this view. Views that are interested 10263 * in the new state should call getDrawableState. 10264 * 10265 * @see #drawableStateChanged 10266 * @see #getDrawableState 10267 */ 10268 public void refreshDrawableState() { 10269 mPrivateFlags |= DRAWABLE_STATE_DIRTY; 10270 drawableStateChanged(); 10271 10272 ViewParent parent = mParent; 10273 if (parent != null) { 10274 parent.childDrawableStateChanged(this); 10275 } 10276 } 10277 10278 /** 10279 * Return an array of resource IDs of the drawable states representing the 10280 * current state of the view. 10281 * 10282 * @return The current drawable state 10283 * 10284 * @see Drawable#setState(int[]) 10285 * @see #drawableStateChanged() 10286 * @see #onCreateDrawableState(int) 10287 */ 10288 public final int[] getDrawableState() { 10289 if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) { 10290 return mDrawableState; 10291 } else { 10292 mDrawableState = onCreateDrawableState(0); 10293 mPrivateFlags &= ~DRAWABLE_STATE_DIRTY; 10294 return mDrawableState; 10295 } 10296 } 10297 10298 /** 10299 * Generate the new {@link android.graphics.drawable.Drawable} state for 10300 * this view. This is called by the view 10301 * system when the cached Drawable state is determined to be invalid. To 10302 * retrieve the current state, you should use {@link #getDrawableState}. 10303 * 10304 * @param extraSpace if non-zero, this is the number of extra entries you 10305 * would like in the returned array in which you can place your own 10306 * states. 10307 * 10308 * @return Returns an array holding the current {@link Drawable} state of 10309 * the view. 10310 * 10311 * @see #mergeDrawableStates(int[], int[]) 10312 */ 10313 protected int[] onCreateDrawableState(int extraSpace) { 10314 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 10315 mParent instanceof View) { 10316 return ((View) mParent).onCreateDrawableState(extraSpace); 10317 } 10318 10319 int[] drawableState; 10320 10321 int privateFlags = mPrivateFlags; 10322 10323 int viewStateIndex = 0; 10324 if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 10325 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 10326 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 10327 if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 10328 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 10329 if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 10330 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 10331 HardwareRenderer.isAvailable()) { 10332 // This is set if HW acceleration is requested, even if the current 10333 // process doesn't allow it. This is just to allow app preview 10334 // windows to better match their app. 10335 viewStateIndex |= VIEW_STATE_ACCELERATED; 10336 } 10337 if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 10338 10339 final int privateFlags2 = mPrivateFlags2; 10340 if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 10341 if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 10342 10343 drawableState = VIEW_STATE_SETS[viewStateIndex]; 10344 10345 //noinspection ConstantIfStatement 10346 if (false) { 10347 Log.i("View", "drawableStateIndex=" + viewStateIndex); 10348 Log.i("View", toString() 10349 + " pressed=" + ((privateFlags & PRESSED) != 0) 10350 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 10351 + " fo=" + hasFocus() 10352 + " sl=" + ((privateFlags & SELECTED) != 0) 10353 + " wf=" + hasWindowFocus() 10354 + ": " + Arrays.toString(drawableState)); 10355 } 10356 10357 if (extraSpace == 0) { 10358 return drawableState; 10359 } 10360 10361 final int[] fullState; 10362 if (drawableState != null) { 10363 fullState = new int[drawableState.length + extraSpace]; 10364 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 10365 } else { 10366 fullState = new int[extraSpace]; 10367 } 10368 10369 return fullState; 10370 } 10371 10372 /** 10373 * Merge your own state values in <var>additionalState</var> into the base 10374 * state values <var>baseState</var> that were returned by 10375 * {@link #onCreateDrawableState(int)}. 10376 * 10377 * @param baseState The base state values returned by 10378 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 10379 * own additional state values. 10380 * 10381 * @param additionalState The additional state values you would like 10382 * added to <var>baseState</var>; this array is not modified. 10383 * 10384 * @return As a convenience, the <var>baseState</var> array you originally 10385 * passed into the function is returned. 10386 * 10387 * @see #onCreateDrawableState(int) 10388 */ 10389 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 10390 final int N = baseState.length; 10391 int i = N - 1; 10392 while (i >= 0 && baseState[i] == 0) { 10393 i--; 10394 } 10395 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 10396 return baseState; 10397 } 10398 10399 /** 10400 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 10401 * on all Drawable objects associated with this view. 10402 */ 10403 public void jumpDrawablesToCurrentState() { 10404 if (mBGDrawable != null) { 10405 mBGDrawable.jumpToCurrentState(); 10406 } 10407 } 10408 10409 /** 10410 * Sets the background color for this view. 10411 * @param color the color of the background 10412 */ 10413 @RemotableViewMethod 10414 public void setBackgroundColor(int color) { 10415 if (mBGDrawable instanceof ColorDrawable) { 10416 ((ColorDrawable) mBGDrawable).setColor(color); 10417 } else { 10418 setBackgroundDrawable(new ColorDrawable(color)); 10419 } 10420 } 10421 10422 /** 10423 * Set the background to a given resource. The resource should refer to 10424 * a Drawable object or 0 to remove the background. 10425 * @param resid The identifier of the resource. 10426 * @attr ref android.R.styleable#View_background 10427 */ 10428 @RemotableViewMethod 10429 public void setBackgroundResource(int resid) { 10430 if (resid != 0 && resid == mBackgroundResource) { 10431 return; 10432 } 10433 10434 Drawable d= null; 10435 if (resid != 0) { 10436 d = mResources.getDrawable(resid); 10437 } 10438 setBackgroundDrawable(d); 10439 10440 mBackgroundResource = resid; 10441 } 10442 10443 /** 10444 * Set the background to a given Drawable, or remove the background. If the 10445 * background has padding, this View's padding is set to the background's 10446 * padding. However, when a background is removed, this View's padding isn't 10447 * touched. If setting the padding is desired, please use 10448 * {@link #setPadding(int, int, int, int)}. 10449 * 10450 * @param d The Drawable to use as the background, or null to remove the 10451 * background 10452 */ 10453 public void setBackgroundDrawable(Drawable d) { 10454 boolean requestLayout = false; 10455 10456 mBackgroundResource = 0; 10457 10458 /* 10459 * Regardless of whether we're setting a new background or not, we want 10460 * to clear the previous drawable. 10461 */ 10462 if (mBGDrawable != null) { 10463 mBGDrawable.setCallback(null); 10464 unscheduleDrawable(mBGDrawable); 10465 } 10466 10467 if (d != null) { 10468 Rect padding = sThreadLocal.get(); 10469 if (padding == null) { 10470 padding = new Rect(); 10471 sThreadLocal.set(padding); 10472 } 10473 if (d.getPadding(padding)) { 10474 setPadding(padding.left, padding.top, padding.right, padding.bottom); 10475 } 10476 10477 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 10478 // if it has a different minimum size, we should layout again 10479 if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() || 10480 mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) { 10481 requestLayout = true; 10482 } 10483 10484 d.setCallback(this); 10485 if (d.isStateful()) { 10486 d.setState(getDrawableState()); 10487 } 10488 d.setVisible(getVisibility() == VISIBLE, false); 10489 mBGDrawable = d; 10490 10491 if ((mPrivateFlags & SKIP_DRAW) != 0) { 10492 mPrivateFlags &= ~SKIP_DRAW; 10493 mPrivateFlags |= ONLY_DRAWS_BACKGROUND; 10494 requestLayout = true; 10495 } 10496 } else { 10497 /* Remove the background */ 10498 mBGDrawable = null; 10499 10500 if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) { 10501 /* 10502 * This view ONLY drew the background before and we're removing 10503 * the background, so now it won't draw anything 10504 * (hence we SKIP_DRAW) 10505 */ 10506 mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND; 10507 mPrivateFlags |= SKIP_DRAW; 10508 } 10509 10510 /* 10511 * When the background is set, we try to apply its padding to this 10512 * View. When the background is removed, we don't touch this View's 10513 * padding. This is noted in the Javadocs. Hence, we don't need to 10514 * requestLayout(), the invalidate() below is sufficient. 10515 */ 10516 10517 // The old background's minimum size could have affected this 10518 // View's layout, so let's requestLayout 10519 requestLayout = true; 10520 } 10521 10522 computeOpaqueFlags(); 10523 10524 if (requestLayout) { 10525 requestLayout(); 10526 } 10527 10528 mBackgroundSizeChanged = true; 10529 invalidate(true); 10530 } 10531 10532 /** 10533 * Gets the background drawable 10534 * @return The drawable used as the background for this view, if any. 10535 */ 10536 public Drawable getBackground() { 10537 return mBGDrawable; 10538 } 10539 10540 /** 10541 * Sets the padding. The view may add on the space required to display 10542 * the scrollbars, depending on the style and visibility of the scrollbars. 10543 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 10544 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 10545 * from the values set in this call. 10546 * 10547 * @attr ref android.R.styleable#View_padding 10548 * @attr ref android.R.styleable#View_paddingBottom 10549 * @attr ref android.R.styleable#View_paddingLeft 10550 * @attr ref android.R.styleable#View_paddingRight 10551 * @attr ref android.R.styleable#View_paddingTop 10552 * @param left the left padding in pixels 10553 * @param top the top padding in pixels 10554 * @param right the right padding in pixels 10555 * @param bottom the bottom padding in pixels 10556 */ 10557 public void setPadding(int left, int top, int right, int bottom) { 10558 boolean changed = false; 10559 10560 mUserPaddingLeft = left; 10561 mUserPaddingRight = right; 10562 mUserPaddingBottom = bottom; 10563 10564 final int viewFlags = mViewFlags; 10565 10566 // Common case is there are no scroll bars. 10567 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 10568 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 10569 // TODO Determine what to do with SCROLLBAR_POSITION_DEFAULT based on RTL settings. 10570 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 10571 ? 0 : getVerticalScrollbarWidth(); 10572 switch (mVerticalScrollbarPosition) { 10573 case SCROLLBAR_POSITION_DEFAULT: 10574 case SCROLLBAR_POSITION_RIGHT: 10575 right += offset; 10576 break; 10577 case SCROLLBAR_POSITION_LEFT: 10578 left += offset; 10579 break; 10580 } 10581 } 10582 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 10583 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 10584 ? 0 : getHorizontalScrollbarHeight(); 10585 } 10586 } 10587 10588 if (mPaddingLeft != left) { 10589 changed = true; 10590 mPaddingLeft = left; 10591 } 10592 if (mPaddingTop != top) { 10593 changed = true; 10594 mPaddingTop = top; 10595 } 10596 if (mPaddingRight != right) { 10597 changed = true; 10598 mPaddingRight = right; 10599 } 10600 if (mPaddingBottom != bottom) { 10601 changed = true; 10602 mPaddingBottom = bottom; 10603 } 10604 10605 if (changed) { 10606 requestLayout(); 10607 } 10608 } 10609 10610 /** 10611 * Returns the top padding of this view. 10612 * 10613 * @return the top padding in pixels 10614 */ 10615 public int getPaddingTop() { 10616 return mPaddingTop; 10617 } 10618 10619 /** 10620 * Returns the bottom padding of this view. If there are inset and enabled 10621 * scrollbars, this value may include the space required to display the 10622 * scrollbars as well. 10623 * 10624 * @return the bottom padding in pixels 10625 */ 10626 public int getPaddingBottom() { 10627 return mPaddingBottom; 10628 } 10629 10630 /** 10631 * Returns the left padding of this view. If there are inset and enabled 10632 * scrollbars, this value may include the space required to display the 10633 * scrollbars as well. 10634 * 10635 * @return the left padding in pixels 10636 */ 10637 public int getPaddingLeft() { 10638 return mPaddingLeft; 10639 } 10640 10641 /** 10642 * Returns the right padding of this view. If there are inset and enabled 10643 * scrollbars, this value may include the space required to display the 10644 * scrollbars as well. 10645 * 10646 * @return the right padding in pixels 10647 */ 10648 public int getPaddingRight() { 10649 return mPaddingRight; 10650 } 10651 10652 /** 10653 * Changes the selection state of this view. A view can be selected or not. 10654 * Note that selection is not the same as focus. Views are typically 10655 * selected in the context of an AdapterView like ListView or GridView; 10656 * the selected view is the view that is highlighted. 10657 * 10658 * @param selected true if the view must be selected, false otherwise 10659 */ 10660 public void setSelected(boolean selected) { 10661 if (((mPrivateFlags & SELECTED) != 0) != selected) { 10662 mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0); 10663 if (!selected) resetPressedState(); 10664 invalidate(true); 10665 refreshDrawableState(); 10666 dispatchSetSelected(selected); 10667 } 10668 } 10669 10670 /** 10671 * Dispatch setSelected to all of this View's children. 10672 * 10673 * @see #setSelected(boolean) 10674 * 10675 * @param selected The new selected state 10676 */ 10677 protected void dispatchSetSelected(boolean selected) { 10678 } 10679 10680 /** 10681 * Indicates the selection state of this view. 10682 * 10683 * @return true if the view is selected, false otherwise 10684 */ 10685 @ViewDebug.ExportedProperty 10686 public boolean isSelected() { 10687 return (mPrivateFlags & SELECTED) != 0; 10688 } 10689 10690 /** 10691 * Changes the activated state of this view. A view can be activated or not. 10692 * Note that activation is not the same as selection. Selection is 10693 * a transient property, representing the view (hierarchy) the user is 10694 * currently interacting with. Activation is a longer-term state that the 10695 * user can move views in and out of. For example, in a list view with 10696 * single or multiple selection enabled, the views in the current selection 10697 * set are activated. (Um, yeah, we are deeply sorry about the terminology 10698 * here.) The activated state is propagated down to children of the view it 10699 * is set on. 10700 * 10701 * @param activated true if the view must be activated, false otherwise 10702 */ 10703 public void setActivated(boolean activated) { 10704 if (((mPrivateFlags & ACTIVATED) != 0) != activated) { 10705 mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0); 10706 invalidate(true); 10707 refreshDrawableState(); 10708 dispatchSetActivated(activated); 10709 } 10710 } 10711 10712 /** 10713 * Dispatch setActivated to all of this View's children. 10714 * 10715 * @see #setActivated(boolean) 10716 * 10717 * @param activated The new activated state 10718 */ 10719 protected void dispatchSetActivated(boolean activated) { 10720 } 10721 10722 /** 10723 * Indicates the activation state of this view. 10724 * 10725 * @return true if the view is activated, false otherwise 10726 */ 10727 @ViewDebug.ExportedProperty 10728 public boolean isActivated() { 10729 return (mPrivateFlags & ACTIVATED) != 0; 10730 } 10731 10732 /** 10733 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 10734 * observer can be used to get notifications when global events, like 10735 * layout, happen. 10736 * 10737 * The returned ViewTreeObserver observer is not guaranteed to remain 10738 * valid for the lifetime of this View. If the caller of this method keeps 10739 * a long-lived reference to ViewTreeObserver, it should always check for 10740 * the return value of {@link ViewTreeObserver#isAlive()}. 10741 * 10742 * @return The ViewTreeObserver for this view's hierarchy. 10743 */ 10744 public ViewTreeObserver getViewTreeObserver() { 10745 if (mAttachInfo != null) { 10746 return mAttachInfo.mTreeObserver; 10747 } 10748 if (mFloatingTreeObserver == null) { 10749 mFloatingTreeObserver = new ViewTreeObserver(); 10750 } 10751 return mFloatingTreeObserver; 10752 } 10753 10754 /** 10755 * <p>Finds the topmost view in the current view hierarchy.</p> 10756 * 10757 * @return the topmost view containing this view 10758 */ 10759 public View getRootView() { 10760 if (mAttachInfo != null) { 10761 final View v = mAttachInfo.mRootView; 10762 if (v != null) { 10763 return v; 10764 } 10765 } 10766 10767 View parent = this; 10768 10769 while (parent.mParent != null && parent.mParent instanceof View) { 10770 parent = (View) parent.mParent; 10771 } 10772 10773 return parent; 10774 } 10775 10776 /** 10777 * <p>Computes the coordinates of this view on the screen. The argument 10778 * must be an array of two integers. After the method returns, the array 10779 * contains the x and y location in that order.</p> 10780 * 10781 * @param location an array of two integers in which to hold the coordinates 10782 */ 10783 public void getLocationOnScreen(int[] location) { 10784 getLocationInWindow(location); 10785 10786 final AttachInfo info = mAttachInfo; 10787 if (info != null) { 10788 location[0] += info.mWindowLeft; 10789 location[1] += info.mWindowTop; 10790 } 10791 } 10792 10793 /** 10794 * <p>Computes the coordinates of this view in its window. The argument 10795 * must be an array of two integers. After the method returns, the array 10796 * contains the x and y location in that order.</p> 10797 * 10798 * @param location an array of two integers in which to hold the coordinates 10799 */ 10800 public void getLocationInWindow(int[] location) { 10801 if (location == null || location.length < 2) { 10802 throw new IllegalArgumentException("location must be an array of " 10803 + "two integers"); 10804 } 10805 10806 location[0] = mLeft + (int) (mTranslationX + 0.5f); 10807 location[1] = mTop + (int) (mTranslationY + 0.5f); 10808 10809 ViewParent viewParent = mParent; 10810 while (viewParent instanceof View) { 10811 final View view = (View)viewParent; 10812 location[0] += view.mLeft + (int) (view.mTranslationX + 0.5f) - view.mScrollX; 10813 location[1] += view.mTop + (int) (view.mTranslationY + 0.5f) - view.mScrollY; 10814 viewParent = view.mParent; 10815 } 10816 10817 if (viewParent instanceof ViewAncestor) { 10818 // *cough* 10819 final ViewAncestor vr = (ViewAncestor)viewParent; 10820 location[1] -= vr.mCurScrollY; 10821 } 10822 } 10823 10824 /** 10825 * {@hide} 10826 * @param id the id of the view to be found 10827 * @return the view of the specified id, null if cannot be found 10828 */ 10829 protected View findViewTraversal(int id) { 10830 if (id == mID) { 10831 return this; 10832 } 10833 return null; 10834 } 10835 10836 /** 10837 * {@hide} 10838 * @param tag the tag of the view to be found 10839 * @return the view of specified tag, null if cannot be found 10840 */ 10841 protected View findViewWithTagTraversal(Object tag) { 10842 if (tag != null && tag.equals(mTag)) { 10843 return this; 10844 } 10845 return null; 10846 } 10847 10848 /** 10849 * {@hide} 10850 * @param predicate The predicate to evaluate. 10851 * @return The first view that matches the predicate or null. 10852 */ 10853 protected View findViewByPredicateTraversal(Predicate<View> predicate) { 10854 if (predicate.apply(this)) { 10855 return this; 10856 } 10857 return null; 10858 } 10859 10860 /** 10861 * Look for a child view with the given id. If this view has the given 10862 * id, return this view. 10863 * 10864 * @param id The id to search for. 10865 * @return The view that has the given id in the hierarchy or null 10866 */ 10867 public final View findViewById(int id) { 10868 if (id < 0) { 10869 return null; 10870 } 10871 return findViewTraversal(id); 10872 } 10873 10874 /** 10875 * Look for a child view with the given tag. If this view has the given 10876 * tag, return this view. 10877 * 10878 * @param tag The tag to search for, using "tag.equals(getTag())". 10879 * @return The View that has the given tag in the hierarchy or null 10880 */ 10881 public final View findViewWithTag(Object tag) { 10882 if (tag == null) { 10883 return null; 10884 } 10885 return findViewWithTagTraversal(tag); 10886 } 10887 10888 /** 10889 * {@hide} 10890 * Look for a child view that matches the specified predicate. 10891 * If this view matches the predicate, return this view. 10892 * 10893 * @param predicate The predicate to evaluate. 10894 * @return The first view that matches the predicate or null. 10895 */ 10896 public final View findViewByPredicate(Predicate<View> predicate) { 10897 return findViewByPredicateTraversal(predicate); 10898 } 10899 10900 /** 10901 * Sets the identifier for this view. The identifier does not have to be 10902 * unique in this view's hierarchy. The identifier should be a positive 10903 * number. 10904 * 10905 * @see #NO_ID 10906 * @see #getId() 10907 * @see #findViewById(int) 10908 * 10909 * @param id a number used to identify the view 10910 * 10911 * @attr ref android.R.styleable#View_id 10912 */ 10913 public void setId(int id) { 10914 mID = id; 10915 } 10916 10917 /** 10918 * {@hide} 10919 * 10920 * @param isRoot true if the view belongs to the root namespace, false 10921 * otherwise 10922 */ 10923 public void setIsRootNamespace(boolean isRoot) { 10924 if (isRoot) { 10925 mPrivateFlags |= IS_ROOT_NAMESPACE; 10926 } else { 10927 mPrivateFlags &= ~IS_ROOT_NAMESPACE; 10928 } 10929 } 10930 10931 /** 10932 * {@hide} 10933 * 10934 * @return true if the view belongs to the root namespace, false otherwise 10935 */ 10936 public boolean isRootNamespace() { 10937 return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0; 10938 } 10939 10940 /** 10941 * Returns this view's identifier. 10942 * 10943 * @return a positive integer used to identify the view or {@link #NO_ID} 10944 * if the view has no ID 10945 * 10946 * @see #setId(int) 10947 * @see #findViewById(int) 10948 * @attr ref android.R.styleable#View_id 10949 */ 10950 @ViewDebug.CapturedViewProperty 10951 public int getId() { 10952 return mID; 10953 } 10954 10955 /** 10956 * Returns this view's tag. 10957 * 10958 * @return the Object stored in this view as a tag 10959 * 10960 * @see #setTag(Object) 10961 * @see #getTag(int) 10962 */ 10963 @ViewDebug.ExportedProperty 10964 public Object getTag() { 10965 return mTag; 10966 } 10967 10968 /** 10969 * Sets the tag associated with this view. A tag can be used to mark 10970 * a view in its hierarchy and does not have to be unique within the 10971 * hierarchy. Tags can also be used to store data within a view without 10972 * resorting to another data structure. 10973 * 10974 * @param tag an Object to tag the view with 10975 * 10976 * @see #getTag() 10977 * @see #setTag(int, Object) 10978 */ 10979 public void setTag(final Object tag) { 10980 mTag = tag; 10981 } 10982 10983 /** 10984 * Returns the tag associated with this view and the specified key. 10985 * 10986 * @param key The key identifying the tag 10987 * 10988 * @return the Object stored in this view as a tag 10989 * 10990 * @see #setTag(int, Object) 10991 * @see #getTag() 10992 */ 10993 public Object getTag(int key) { 10994 SparseArray<Object> tags = null; 10995 synchronized (sTagsLock) { 10996 if (sTags != null) { 10997 tags = sTags.get(this); 10998 } 10999 } 11000 11001 if (tags != null) return tags.get(key); 11002 return null; 11003 } 11004 11005 /** 11006 * Sets a tag associated with this view and a key. A tag can be used 11007 * to mark a view in its hierarchy and does not have to be unique within 11008 * the hierarchy. Tags can also be used to store data within a view 11009 * without resorting to another data structure. 11010 * 11011 * The specified key should be an id declared in the resources of the 11012 * application to ensure it is unique (see the <a 11013 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 11014 * Keys identified as belonging to 11015 * the Android framework or not associated with any package will cause 11016 * an {@link IllegalArgumentException} to be thrown. 11017 * 11018 * @param key The key identifying the tag 11019 * @param tag An Object to tag the view with 11020 * 11021 * @throws IllegalArgumentException If they specified key is not valid 11022 * 11023 * @see #setTag(Object) 11024 * @see #getTag(int) 11025 */ 11026 public void setTag(int key, final Object tag) { 11027 // If the package id is 0x00 or 0x01, it's either an undefined package 11028 // or a framework id 11029 if ((key >>> 24) < 2) { 11030 throw new IllegalArgumentException("The key must be an application-specific " 11031 + "resource id."); 11032 } 11033 11034 setTagInternal(this, key, tag); 11035 } 11036 11037 /** 11038 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 11039 * framework id. 11040 * 11041 * @hide 11042 */ 11043 public void setTagInternal(int key, Object tag) { 11044 if ((key >>> 24) != 0x1) { 11045 throw new IllegalArgumentException("The key must be a framework-specific " 11046 + "resource id."); 11047 } 11048 11049 setTagInternal(this, key, tag); 11050 } 11051 11052 private static void setTagInternal(View view, int key, Object tag) { 11053 SparseArray<Object> tags = null; 11054 synchronized (sTagsLock) { 11055 if (sTags == null) { 11056 sTags = new WeakHashMap<View, SparseArray<Object>>(); 11057 } else { 11058 tags = sTags.get(view); 11059 } 11060 } 11061 11062 if (tags == null) { 11063 tags = new SparseArray<Object>(2); 11064 synchronized (sTagsLock) { 11065 sTags.put(view, tags); 11066 } 11067 } 11068 11069 tags.put(key, tag); 11070 } 11071 11072 /** 11073 * @param consistency The type of consistency. See ViewDebug for more information. 11074 * 11075 * @hide 11076 */ 11077 protected boolean dispatchConsistencyCheck(int consistency) { 11078 return onConsistencyCheck(consistency); 11079 } 11080 11081 /** 11082 * Method that subclasses should implement to check their consistency. The type of 11083 * consistency check is indicated by the bit field passed as a parameter. 11084 * 11085 * @param consistency The type of consistency. See ViewDebug for more information. 11086 * 11087 * @throws IllegalStateException if the view is in an inconsistent state. 11088 * 11089 * @hide 11090 */ 11091 protected boolean onConsistencyCheck(int consistency) { 11092 boolean result = true; 11093 11094 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0; 11095 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0; 11096 11097 if (checkLayout) { 11098 if (getParent() == null) { 11099 result = false; 11100 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 11101 "View " + this + " does not have a parent."); 11102 } 11103 11104 if (mAttachInfo == null) { 11105 result = false; 11106 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 11107 "View " + this + " is not attached to a window."); 11108 } 11109 } 11110 11111 if (checkDrawing) { 11112 // Do not check the DIRTY/DRAWN flags because views can call invalidate() 11113 // from their draw() method 11114 11115 if ((mPrivateFlags & DRAWN) != DRAWN && 11116 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) { 11117 result = false; 11118 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 11119 "View " + this + " was invalidated but its drawing cache is valid."); 11120 } 11121 } 11122 11123 return result; 11124 } 11125 11126 /** 11127 * Prints information about this view in the log output, with the tag 11128 * {@link #VIEW_LOG_TAG}. 11129 * 11130 * @hide 11131 */ 11132 public void debug() { 11133 debug(0); 11134 } 11135 11136 /** 11137 * Prints information about this view in the log output, with the tag 11138 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 11139 * indentation defined by the <code>depth</code>. 11140 * 11141 * @param depth the indentation level 11142 * 11143 * @hide 11144 */ 11145 protected void debug(int depth) { 11146 String output = debugIndent(depth - 1); 11147 11148 output += "+ " + this; 11149 int id = getId(); 11150 if (id != -1) { 11151 output += " (id=" + id + ")"; 11152 } 11153 Object tag = getTag(); 11154 if (tag != null) { 11155 output += " (tag=" + tag + ")"; 11156 } 11157 Log.d(VIEW_LOG_TAG, output); 11158 11159 if ((mPrivateFlags & FOCUSED) != 0) { 11160 output = debugIndent(depth) + " FOCUSED"; 11161 Log.d(VIEW_LOG_TAG, output); 11162 } 11163 11164 output = debugIndent(depth); 11165 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 11166 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 11167 + "} "; 11168 Log.d(VIEW_LOG_TAG, output); 11169 11170 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 11171 || mPaddingBottom != 0) { 11172 output = debugIndent(depth); 11173 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 11174 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 11175 Log.d(VIEW_LOG_TAG, output); 11176 } 11177 11178 output = debugIndent(depth); 11179 output += "mMeasureWidth=" + mMeasuredWidth + 11180 " mMeasureHeight=" + mMeasuredHeight; 11181 Log.d(VIEW_LOG_TAG, output); 11182 11183 output = debugIndent(depth); 11184 if (mLayoutParams == null) { 11185 output += "BAD! no layout params"; 11186 } else { 11187 output = mLayoutParams.debug(output); 11188 } 11189 Log.d(VIEW_LOG_TAG, output); 11190 11191 output = debugIndent(depth); 11192 output += "flags={"; 11193 output += View.printFlags(mViewFlags); 11194 output += "}"; 11195 Log.d(VIEW_LOG_TAG, output); 11196 11197 output = debugIndent(depth); 11198 output += "privateFlags={"; 11199 output += View.printPrivateFlags(mPrivateFlags); 11200 output += "}"; 11201 Log.d(VIEW_LOG_TAG, output); 11202 } 11203 11204 /** 11205 * Creates an string of whitespaces used for indentation. 11206 * 11207 * @param depth the indentation level 11208 * @return a String containing (depth * 2 + 3) * 2 white spaces 11209 * 11210 * @hide 11211 */ 11212 protected static String debugIndent(int depth) { 11213 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 11214 for (int i = 0; i < (depth * 2) + 3; i++) { 11215 spaces.append(' ').append(' '); 11216 } 11217 return spaces.toString(); 11218 } 11219 11220 /** 11221 * <p>Return the offset of the widget's text baseline from the widget's top 11222 * boundary. If this widget does not support baseline alignment, this 11223 * method returns -1. </p> 11224 * 11225 * @return the offset of the baseline within the widget's bounds or -1 11226 * if baseline alignment is not supported 11227 */ 11228 @ViewDebug.ExportedProperty(category = "layout") 11229 public int getBaseline() { 11230 return -1; 11231 } 11232 11233 /** 11234 * Call this when something has changed which has invalidated the 11235 * layout of this view. This will schedule a layout pass of the view 11236 * tree. 11237 */ 11238 public void requestLayout() { 11239 if (ViewDebug.TRACE_HIERARCHY) { 11240 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT); 11241 } 11242 11243 mPrivateFlags |= FORCE_LAYOUT; 11244 mPrivateFlags |= INVALIDATED; 11245 11246 if (mParent != null && !mParent.isLayoutRequested()) { 11247 mParent.requestLayout(); 11248 } 11249 } 11250 11251 /** 11252 * Forces this view to be laid out during the next layout pass. 11253 * This method does not call requestLayout() or forceLayout() 11254 * on the parent. 11255 */ 11256 public void forceLayout() { 11257 mPrivateFlags |= FORCE_LAYOUT; 11258 mPrivateFlags |= INVALIDATED; 11259 } 11260 11261 /** 11262 * <p> 11263 * This is called to find out how big a view should be. The parent 11264 * supplies constraint information in the width and height parameters. 11265 * </p> 11266 * 11267 * <p> 11268 * The actual mesurement work of a view is performed in 11269 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 11270 * {@link #onMeasure(int, int)} can and must be overriden by subclasses. 11271 * </p> 11272 * 11273 * 11274 * @param widthMeasureSpec Horizontal space requirements as imposed by the 11275 * parent 11276 * @param heightMeasureSpec Vertical space requirements as imposed by the 11277 * parent 11278 * 11279 * @see #onMeasure(int, int) 11280 */ 11281 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 11282 if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT || 11283 widthMeasureSpec != mOldWidthMeasureSpec || 11284 heightMeasureSpec != mOldHeightMeasureSpec) { 11285 11286 // first clears the measured dimension flag 11287 mPrivateFlags &= ~MEASURED_DIMENSION_SET; 11288 11289 if (ViewDebug.TRACE_HIERARCHY) { 11290 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE); 11291 } 11292 11293 // measure ourselves, this should set the measured dimension flag back 11294 onMeasure(widthMeasureSpec, heightMeasureSpec); 11295 11296 // flag not set, setMeasuredDimension() was not invoked, we raise 11297 // an exception to warn the developer 11298 if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) { 11299 throw new IllegalStateException("onMeasure() did not set the" 11300 + " measured dimension by calling" 11301 + " setMeasuredDimension()"); 11302 } 11303 11304 mPrivateFlags |= LAYOUT_REQUIRED; 11305 } 11306 11307 mOldWidthMeasureSpec = widthMeasureSpec; 11308 mOldHeightMeasureSpec = heightMeasureSpec; 11309 } 11310 11311 /** 11312 * <p> 11313 * Measure the view and its content to determine the measured width and the 11314 * measured height. This method is invoked by {@link #measure(int, int)} and 11315 * should be overriden by subclasses to provide accurate and efficient 11316 * measurement of their contents. 11317 * </p> 11318 * 11319 * <p> 11320 * <strong>CONTRACT:</strong> When overriding this method, you 11321 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 11322 * measured width and height of this view. Failure to do so will trigger an 11323 * <code>IllegalStateException</code>, thrown by 11324 * {@link #measure(int, int)}. Calling the superclass' 11325 * {@link #onMeasure(int, int)} is a valid use. 11326 * </p> 11327 * 11328 * <p> 11329 * The base class implementation of measure defaults to the background size, 11330 * unless a larger size is allowed by the MeasureSpec. Subclasses should 11331 * override {@link #onMeasure(int, int)} to provide better measurements of 11332 * their content. 11333 * </p> 11334 * 11335 * <p> 11336 * If this method is overridden, it is the subclass's responsibility to make 11337 * sure the measured height and width are at least the view's minimum height 11338 * and width ({@link #getSuggestedMinimumHeight()} and 11339 * {@link #getSuggestedMinimumWidth()}). 11340 * </p> 11341 * 11342 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 11343 * The requirements are encoded with 11344 * {@link android.view.View.MeasureSpec}. 11345 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 11346 * The requirements are encoded with 11347 * {@link android.view.View.MeasureSpec}. 11348 * 11349 * @see #getMeasuredWidth() 11350 * @see #getMeasuredHeight() 11351 * @see #setMeasuredDimension(int, int) 11352 * @see #getSuggestedMinimumHeight() 11353 * @see #getSuggestedMinimumWidth() 11354 * @see android.view.View.MeasureSpec#getMode(int) 11355 * @see android.view.View.MeasureSpec#getSize(int) 11356 */ 11357 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 11358 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 11359 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 11360 } 11361 11362 /** 11363 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the 11364 * measured width and measured height. Failing to do so will trigger an 11365 * exception at measurement time.</p> 11366 * 11367 * @param measuredWidth The measured width of this view. May be a complex 11368 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 11369 * {@link #MEASURED_STATE_TOO_SMALL}. 11370 * @param measuredHeight The measured height of this view. May be a complex 11371 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 11372 * {@link #MEASURED_STATE_TOO_SMALL}. 11373 */ 11374 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 11375 mMeasuredWidth = measuredWidth; 11376 mMeasuredHeight = measuredHeight; 11377 11378 mPrivateFlags |= MEASURED_DIMENSION_SET; 11379 } 11380 11381 /** 11382 * Merge two states as returned by {@link #getMeasuredState()}. 11383 * @param curState The current state as returned from a view or the result 11384 * of combining multiple views. 11385 * @param newState The new view state to combine. 11386 * @return Returns a new integer reflecting the combination of the two 11387 * states. 11388 */ 11389 public static int combineMeasuredStates(int curState, int newState) { 11390 return curState | newState; 11391 } 11392 11393 /** 11394 * Version of {@link #resolveSizeAndState(int, int, int)} 11395 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 11396 */ 11397 public static int resolveSize(int size, int measureSpec) { 11398 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 11399 } 11400 11401 /** 11402 * Utility to reconcile a desired size and state, with constraints imposed 11403 * by a MeasureSpec. Will take the desired size, unless a different size 11404 * is imposed by the constraints. The returned value is a compound integer, 11405 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 11406 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 11407 * size is smaller than the size the view wants to be. 11408 * 11409 * @param size How big the view wants to be 11410 * @param measureSpec Constraints imposed by the parent 11411 * @return Size information bit mask as defined by 11412 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 11413 */ 11414 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 11415 int result = size; 11416 int specMode = MeasureSpec.getMode(measureSpec); 11417 int specSize = MeasureSpec.getSize(measureSpec); 11418 switch (specMode) { 11419 case MeasureSpec.UNSPECIFIED: 11420 result = size; 11421 break; 11422 case MeasureSpec.AT_MOST: 11423 if (specSize < size) { 11424 result = specSize | MEASURED_STATE_TOO_SMALL; 11425 } else { 11426 result = size; 11427 } 11428 break; 11429 case MeasureSpec.EXACTLY: 11430 result = specSize; 11431 break; 11432 } 11433 return result | (childMeasuredState&MEASURED_STATE_MASK); 11434 } 11435 11436 /** 11437 * Utility to return a default size. Uses the supplied size if the 11438 * MeasureSpec imposed no contraints. Will get larger if allowed 11439 * by the MeasureSpec. 11440 * 11441 * @param size Default size for this view 11442 * @param measureSpec Constraints imposed by the parent 11443 * @return The size this view should be. 11444 */ 11445 public static int getDefaultSize(int size, int measureSpec) { 11446 int result = size; 11447 int specMode = MeasureSpec.getMode(measureSpec); 11448 int specSize = MeasureSpec.getSize(measureSpec); 11449 11450 switch (specMode) { 11451 case MeasureSpec.UNSPECIFIED: 11452 result = size; 11453 break; 11454 case MeasureSpec.AT_MOST: 11455 case MeasureSpec.EXACTLY: 11456 result = specSize; 11457 break; 11458 } 11459 return result; 11460 } 11461 11462 /** 11463 * Returns the suggested minimum height that the view should use. This 11464 * returns the maximum of the view's minimum height 11465 * and the background's minimum height 11466 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 11467 * <p> 11468 * When being used in {@link #onMeasure(int, int)}, the caller should still 11469 * ensure the returned height is within the requirements of the parent. 11470 * 11471 * @return The suggested minimum height of the view. 11472 */ 11473 protected int getSuggestedMinimumHeight() { 11474 int suggestedMinHeight = mMinHeight; 11475 11476 if (mBGDrawable != null) { 11477 final int bgMinHeight = mBGDrawable.getMinimumHeight(); 11478 if (suggestedMinHeight < bgMinHeight) { 11479 suggestedMinHeight = bgMinHeight; 11480 } 11481 } 11482 11483 return suggestedMinHeight; 11484 } 11485 11486 /** 11487 * Returns the suggested minimum width that the view should use. This 11488 * returns the maximum of the view's minimum width) 11489 * and the background's minimum width 11490 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 11491 * <p> 11492 * When being used in {@link #onMeasure(int, int)}, the caller should still 11493 * ensure the returned width is within the requirements of the parent. 11494 * 11495 * @return The suggested minimum width of the view. 11496 */ 11497 protected int getSuggestedMinimumWidth() { 11498 int suggestedMinWidth = mMinWidth; 11499 11500 if (mBGDrawable != null) { 11501 final int bgMinWidth = mBGDrawable.getMinimumWidth(); 11502 if (suggestedMinWidth < bgMinWidth) { 11503 suggestedMinWidth = bgMinWidth; 11504 } 11505 } 11506 11507 return suggestedMinWidth; 11508 } 11509 11510 /** 11511 * Sets the minimum height of the view. It is not guaranteed the view will 11512 * be able to achieve this minimum height (for example, if its parent layout 11513 * constrains it with less available height). 11514 * 11515 * @param minHeight The minimum height the view will try to be. 11516 */ 11517 public void setMinimumHeight(int minHeight) { 11518 mMinHeight = minHeight; 11519 } 11520 11521 /** 11522 * Sets the minimum width of the view. It is not guaranteed the view will 11523 * be able to achieve this minimum width (for example, if its parent layout 11524 * constrains it with less available width). 11525 * 11526 * @param minWidth The minimum width the view will try to be. 11527 */ 11528 public void setMinimumWidth(int minWidth) { 11529 mMinWidth = minWidth; 11530 } 11531 11532 /** 11533 * Get the animation currently associated with this view. 11534 * 11535 * @return The animation that is currently playing or 11536 * scheduled to play for this view. 11537 */ 11538 public Animation getAnimation() { 11539 return mCurrentAnimation; 11540 } 11541 11542 /** 11543 * Start the specified animation now. 11544 * 11545 * @param animation the animation to start now 11546 */ 11547 public void startAnimation(Animation animation) { 11548 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 11549 setAnimation(animation); 11550 invalidateParentCaches(); 11551 invalidate(true); 11552 } 11553 11554 /** 11555 * Cancels any animations for this view. 11556 */ 11557 public void clearAnimation() { 11558 if (mCurrentAnimation != null) { 11559 mCurrentAnimation.detach(); 11560 } 11561 mCurrentAnimation = null; 11562 invalidateParentIfNeeded(); 11563 } 11564 11565 /** 11566 * Sets the next animation to play for this view. 11567 * If you want the animation to play immediately, use 11568 * startAnimation. This method provides allows fine-grained 11569 * control over the start time and invalidation, but you 11570 * must make sure that 1) the animation has a start time set, and 11571 * 2) the view will be invalidated when the animation is supposed to 11572 * start. 11573 * 11574 * @param animation The next animation, or null. 11575 */ 11576 public void setAnimation(Animation animation) { 11577 mCurrentAnimation = animation; 11578 if (animation != null) { 11579 animation.reset(); 11580 } 11581 } 11582 11583 /** 11584 * Invoked by a parent ViewGroup to notify the start of the animation 11585 * currently associated with this view. If you override this method, 11586 * always call super.onAnimationStart(); 11587 * 11588 * @see #setAnimation(android.view.animation.Animation) 11589 * @see #getAnimation() 11590 */ 11591 protected void onAnimationStart() { 11592 mPrivateFlags |= ANIMATION_STARTED; 11593 } 11594 11595 /** 11596 * Invoked by a parent ViewGroup to notify the end of the animation 11597 * currently associated with this view. If you override this method, 11598 * always call super.onAnimationEnd(); 11599 * 11600 * @see #setAnimation(android.view.animation.Animation) 11601 * @see #getAnimation() 11602 */ 11603 protected void onAnimationEnd() { 11604 mPrivateFlags &= ~ANIMATION_STARTED; 11605 } 11606 11607 /** 11608 * Invoked if there is a Transform that involves alpha. Subclass that can 11609 * draw themselves with the specified alpha should return true, and then 11610 * respect that alpha when their onDraw() is called. If this returns false 11611 * then the view may be redirected to draw into an offscreen buffer to 11612 * fulfill the request, which will look fine, but may be slower than if the 11613 * subclass handles it internally. The default implementation returns false. 11614 * 11615 * @param alpha The alpha (0..255) to apply to the view's drawing 11616 * @return true if the view can draw with the specified alpha. 11617 */ 11618 protected boolean onSetAlpha(int alpha) { 11619 return false; 11620 } 11621 11622 /** 11623 * This is used by the RootView to perform an optimization when 11624 * the view hierarchy contains one or several SurfaceView. 11625 * SurfaceView is always considered transparent, but its children are not, 11626 * therefore all View objects remove themselves from the global transparent 11627 * region (passed as a parameter to this function). 11628 * 11629 * @param region The transparent region for this ViewAncestor (window). 11630 * 11631 * @return Returns true if the effective visibility of the view at this 11632 * point is opaque, regardless of the transparent region; returns false 11633 * if it is possible for underlying windows to be seen behind the view. 11634 * 11635 * {@hide} 11636 */ 11637 public boolean gatherTransparentRegion(Region region) { 11638 final AttachInfo attachInfo = mAttachInfo; 11639 if (region != null && attachInfo != null) { 11640 final int pflags = mPrivateFlags; 11641 if ((pflags & SKIP_DRAW) == 0) { 11642 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 11643 // remove it from the transparent region. 11644 final int[] location = attachInfo.mTransparentLocation; 11645 getLocationInWindow(location); 11646 region.op(location[0], location[1], location[0] + mRight - mLeft, 11647 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 11648 } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) { 11649 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 11650 // exists, so we remove the background drawable's non-transparent 11651 // parts from this transparent region. 11652 applyDrawableToTransparentRegion(mBGDrawable, region); 11653 } 11654 } 11655 return true; 11656 } 11657 11658 /** 11659 * Play a sound effect for this view. 11660 * 11661 * <p>The framework will play sound effects for some built in actions, such as 11662 * clicking, but you may wish to play these effects in your widget, 11663 * for instance, for internal navigation. 11664 * 11665 * <p>The sound effect will only be played if sound effects are enabled by the user, and 11666 * {@link #isSoundEffectsEnabled()} is true. 11667 * 11668 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 11669 */ 11670 public void playSoundEffect(int soundConstant) { 11671 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 11672 return; 11673 } 11674 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 11675 } 11676 11677 /** 11678 * BZZZTT!!1! 11679 * 11680 * <p>Provide haptic feedback to the user for this view. 11681 * 11682 * <p>The framework will provide haptic feedback for some built in actions, 11683 * such as long presses, but you may wish to provide feedback for your 11684 * own widget. 11685 * 11686 * <p>The feedback will only be performed if 11687 * {@link #isHapticFeedbackEnabled()} is true. 11688 * 11689 * @param feedbackConstant One of the constants defined in 11690 * {@link HapticFeedbackConstants} 11691 */ 11692 public boolean performHapticFeedback(int feedbackConstant) { 11693 return performHapticFeedback(feedbackConstant, 0); 11694 } 11695 11696 /** 11697 * BZZZTT!!1! 11698 * 11699 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 11700 * 11701 * @param feedbackConstant One of the constants defined in 11702 * {@link HapticFeedbackConstants} 11703 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 11704 */ 11705 public boolean performHapticFeedback(int feedbackConstant, int flags) { 11706 if (mAttachInfo == null) { 11707 return false; 11708 } 11709 //noinspection SimplifiableIfStatement 11710 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 11711 && !isHapticFeedbackEnabled()) { 11712 return false; 11713 } 11714 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 11715 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 11716 } 11717 11718 /** 11719 * Request that the visibility of the status bar be changed. 11720 */ 11721 public void setSystemUiVisibility(int visibility) { 11722 if (visibility != mSystemUiVisibility) { 11723 mSystemUiVisibility = visibility; 11724 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 11725 mParent.recomputeViewAttributes(this); 11726 } 11727 } 11728 } 11729 11730 /** 11731 * Returns the status bar visibility that this view has requested. 11732 */ 11733 public int getSystemUiVisibility() { 11734 return mSystemUiVisibility; 11735 } 11736 11737 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 11738 mOnSystemUiVisibilityChangeListener = l; 11739 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 11740 mParent.recomputeViewAttributes(this); 11741 } 11742 } 11743 11744 /** 11745 */ 11746 public void dispatchSystemUiVisibilityChanged(int visibility) { 11747 if (mOnSystemUiVisibilityChangeListener != null) { 11748 mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 11749 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 11750 } 11751 } 11752 11753 /** 11754 * Creates an image that the system displays during the drag and drop 11755 * operation. This is called a "drag shadow". The default implementation 11756 * for a DragShadowBuilder based on a View returns an image that has exactly the same 11757 * appearance as the given View. The default also positions the center of the drag shadow 11758 * directly under the touch point. If no View is provided (the constructor with no parameters 11759 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 11760 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 11761 * default is an invisible drag shadow. 11762 * <p> 11763 * You are not required to use the View you provide to the constructor as the basis of the 11764 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 11765 * anything you want as the drag shadow. 11766 * </p> 11767 * <p> 11768 * You pass a DragShadowBuilder object to the system when you start the drag. The system 11769 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 11770 * size and position of the drag shadow. It uses this data to construct a 11771 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 11772 * so that your application can draw the shadow image in the Canvas. 11773 * </p> 11774 */ 11775 public static class DragShadowBuilder { 11776 private final WeakReference<View> mView; 11777 11778 /** 11779 * Constructs a shadow image builder based on a View. By default, the resulting drag 11780 * shadow will have the same appearance and dimensions as the View, with the touch point 11781 * over the center of the View. 11782 * @param view A View. Any View in scope can be used. 11783 */ 11784 public DragShadowBuilder(View view) { 11785 mView = new WeakReference<View>(view); 11786 } 11787 11788 /** 11789 * Construct a shadow builder object with no associated View. This 11790 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 11791 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 11792 * to supply the drag shadow's dimensions and appearance without 11793 * reference to any View object. If they are not overridden, then the result is an 11794 * invisible drag shadow. 11795 */ 11796 public DragShadowBuilder() { 11797 mView = new WeakReference<View>(null); 11798 } 11799 11800 /** 11801 * Returns the View object that had been passed to the 11802 * {@link #View.DragShadowBuilder(View)} 11803 * constructor. If that View parameter was {@code null} or if the 11804 * {@link #View.DragShadowBuilder()} 11805 * constructor was used to instantiate the builder object, this method will return 11806 * null. 11807 * 11808 * @return The View object associate with this builder object. 11809 */ 11810 @SuppressWarnings({"JavadocReference"}) 11811 final public View getView() { 11812 return mView.get(); 11813 } 11814 11815 /** 11816 * Provides the metrics for the shadow image. These include the dimensions of 11817 * the shadow image, and the point within that shadow that should 11818 * be centered under the touch location while dragging. 11819 * <p> 11820 * The default implementation sets the dimensions of the shadow to be the 11821 * same as the dimensions of the View itself and centers the shadow under 11822 * the touch point. 11823 * </p> 11824 * 11825 * @param shadowSize A {@link android.graphics.Point} containing the width and height 11826 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 11827 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 11828 * image. 11829 * 11830 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 11831 * shadow image that should be underneath the touch point during the drag and drop 11832 * operation. Your application must set {@link android.graphics.Point#x} to the 11833 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 11834 */ 11835 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 11836 final View view = mView.get(); 11837 if (view != null) { 11838 shadowSize.set(view.getWidth(), view.getHeight()); 11839 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 11840 } else { 11841 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 11842 } 11843 } 11844 11845 /** 11846 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 11847 * based on the dimensions it received from the 11848 * {@link #onProvideShadowMetrics(Point, Point)} callback. 11849 * 11850 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 11851 */ 11852 public void onDrawShadow(Canvas canvas) { 11853 final View view = mView.get(); 11854 if (view != null) { 11855 view.draw(canvas); 11856 } else { 11857 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 11858 } 11859 } 11860 } 11861 11862 /** 11863 * Starts a drag and drop operation. When your application calls this method, it passes a 11864 * {@link android.view.View.DragShadowBuilder} object to the system. The 11865 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 11866 * to get metrics for the drag shadow, and then calls the object's 11867 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 11868 * <p> 11869 * Once the system has the drag shadow, it begins the drag and drop operation by sending 11870 * drag events to all the View objects in your application that are currently visible. It does 11871 * this either by calling the View object's drag listener (an implementation of 11872 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 11873 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 11874 * Both are passed a {@link android.view.DragEvent} object that has a 11875 * {@link android.view.DragEvent#getAction()} value of 11876 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 11877 * </p> 11878 * <p> 11879 * Your application can invoke startDrag() on any attached View object. The View object does not 11880 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 11881 * be related to the View the user selected for dragging. 11882 * </p> 11883 * @param data A {@link android.content.ClipData} object pointing to the data to be 11884 * transferred by the drag and drop operation. 11885 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 11886 * drag shadow. 11887 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 11888 * drop operation. This Object is put into every DragEvent object sent by the system during the 11889 * current drag. 11890 * <p> 11891 * myLocalState is a lightweight mechanism for the sending information from the dragged View 11892 * to the target Views. For example, it can contain flags that differentiate between a 11893 * a copy operation and a move operation. 11894 * </p> 11895 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 11896 * so the parameter should be set to 0. 11897 * @return {@code true} if the method completes successfully, or 11898 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 11899 * do a drag, and so no drag operation is in progress. 11900 */ 11901 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 11902 Object myLocalState, int flags) { 11903 if (ViewDebug.DEBUG_DRAG) { 11904 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 11905 } 11906 boolean okay = false; 11907 11908 Point shadowSize = new Point(); 11909 Point shadowTouchPoint = new Point(); 11910 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 11911 11912 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 11913 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 11914 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 11915 } 11916 11917 if (ViewDebug.DEBUG_DRAG) { 11918 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 11919 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 11920 } 11921 Surface surface = new Surface(); 11922 try { 11923 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 11924 flags, shadowSize.x, shadowSize.y, surface); 11925 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 11926 + " surface=" + surface); 11927 if (token != null) { 11928 Canvas canvas = surface.lockCanvas(null); 11929 try { 11930 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 11931 shadowBuilder.onDrawShadow(canvas); 11932 } finally { 11933 surface.unlockCanvasAndPost(canvas); 11934 } 11935 11936 final ViewAncestor root = getViewAncestor(); 11937 11938 // Cache the local state object for delivery with DragEvents 11939 root.setLocalDragState(myLocalState); 11940 11941 // repurpose 'shadowSize' for the last touch point 11942 root.getLastTouchPoint(shadowSize); 11943 11944 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 11945 shadowSize.x, shadowSize.y, 11946 shadowTouchPoint.x, shadowTouchPoint.y, data); 11947 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 11948 } 11949 } catch (Exception e) { 11950 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 11951 surface.destroy(); 11952 } 11953 11954 return okay; 11955 } 11956 11957 /** 11958 * Handles drag events sent by the system following a call to 11959 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 11960 *<p> 11961 * When the system calls this method, it passes a 11962 * {@link android.view.DragEvent} object. A call to 11963 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 11964 * in DragEvent. The method uses these to determine what is happening in the drag and drop 11965 * operation. 11966 * @param event The {@link android.view.DragEvent} sent by the system. 11967 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 11968 * in DragEvent, indicating the type of drag event represented by this object. 11969 * @return {@code true} if the method was successful, otherwise {@code false}. 11970 * <p> 11971 * The method should return {@code true} in response to an action type of 11972 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 11973 * operation. 11974 * </p> 11975 * <p> 11976 * The method should also return {@code true} in response to an action type of 11977 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 11978 * {@code false} if it didn't. 11979 * </p> 11980 */ 11981 public boolean onDragEvent(DragEvent event) { 11982 return false; 11983 } 11984 11985 /** 11986 * Detects if this View is enabled and has a drag event listener. 11987 * If both are true, then it calls the drag event listener with the 11988 * {@link android.view.DragEvent} it received. If the drag event listener returns 11989 * {@code true}, then dispatchDragEvent() returns {@code true}. 11990 * <p> 11991 * For all other cases, the method calls the 11992 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 11993 * method and returns its result. 11994 * </p> 11995 * <p> 11996 * This ensures that a drag event is always consumed, even if the View does not have a drag 11997 * event listener. However, if the View has a listener and the listener returns true, then 11998 * onDragEvent() is not called. 11999 * </p> 12000 */ 12001 public boolean dispatchDragEvent(DragEvent event) { 12002 //noinspection SimplifiableIfStatement 12003 if (mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 12004 && mOnDragListener.onDrag(this, event)) { 12005 return true; 12006 } 12007 return onDragEvent(event); 12008 } 12009 12010 boolean canAcceptDrag() { 12011 return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0; 12012 } 12013 12014 /** 12015 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 12016 * it is ever exposed at all. 12017 * @hide 12018 */ 12019 public void onCloseSystemDialogs(String reason) { 12020 } 12021 12022 /** 12023 * Given a Drawable whose bounds have been set to draw into this view, 12024 * update a Region being computed for 12025 * {@link #gatherTransparentRegion(android.graphics.Region)} so 12026 * that any non-transparent parts of the Drawable are removed from the 12027 * given transparent region. 12028 * 12029 * @param dr The Drawable whose transparency is to be applied to the region. 12030 * @param region A Region holding the current transparency information, 12031 * where any parts of the region that are set are considered to be 12032 * transparent. On return, this region will be modified to have the 12033 * transparency information reduced by the corresponding parts of the 12034 * Drawable that are not transparent. 12035 * {@hide} 12036 */ 12037 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 12038 if (DBG) { 12039 Log.i("View", "Getting transparent region for: " + this); 12040 } 12041 final Region r = dr.getTransparentRegion(); 12042 final Rect db = dr.getBounds(); 12043 final AttachInfo attachInfo = mAttachInfo; 12044 if (r != null && attachInfo != null) { 12045 final int w = getRight()-getLeft(); 12046 final int h = getBottom()-getTop(); 12047 if (db.left > 0) { 12048 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 12049 r.op(0, 0, db.left, h, Region.Op.UNION); 12050 } 12051 if (db.right < w) { 12052 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 12053 r.op(db.right, 0, w, h, Region.Op.UNION); 12054 } 12055 if (db.top > 0) { 12056 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 12057 r.op(0, 0, w, db.top, Region.Op.UNION); 12058 } 12059 if (db.bottom < h) { 12060 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 12061 r.op(0, db.bottom, w, h, Region.Op.UNION); 12062 } 12063 final int[] location = attachInfo.mTransparentLocation; 12064 getLocationInWindow(location); 12065 r.translate(location[0], location[1]); 12066 region.op(r, Region.Op.INTERSECT); 12067 } else { 12068 region.op(db, Region.Op.DIFFERENCE); 12069 } 12070 } 12071 12072 private void checkForLongClick(int delayOffset) { 12073 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 12074 mHasPerformedLongPress = false; 12075 12076 if (mPendingCheckForLongPress == null) { 12077 mPendingCheckForLongPress = new CheckForLongPress(); 12078 } 12079 mPendingCheckForLongPress.rememberWindowAttachCount(); 12080 postDelayed(mPendingCheckForLongPress, 12081 ViewConfiguration.getLongPressTimeout() - delayOffset); 12082 } 12083 } 12084 12085 /** 12086 * Inflate a view from an XML resource. This convenience method wraps the {@link 12087 * LayoutInflater} class, which provides a full range of options for view inflation. 12088 * 12089 * @param context The Context object for your activity or application. 12090 * @param resource The resource ID to inflate 12091 * @param root A view group that will be the parent. Used to properly inflate the 12092 * layout_* parameters. 12093 * @see LayoutInflater 12094 */ 12095 public static View inflate(Context context, int resource, ViewGroup root) { 12096 LayoutInflater factory = LayoutInflater.from(context); 12097 return factory.inflate(resource, root); 12098 } 12099 12100 /** 12101 * Scroll the view with standard behavior for scrolling beyond the normal 12102 * content boundaries. Views that call this method should override 12103 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 12104 * results of an over-scroll operation. 12105 * 12106 * Views can use this method to handle any touch or fling-based scrolling. 12107 * 12108 * @param deltaX Change in X in pixels 12109 * @param deltaY Change in Y in pixels 12110 * @param scrollX Current X scroll value in pixels before applying deltaX 12111 * @param scrollY Current Y scroll value in pixels before applying deltaY 12112 * @param scrollRangeX Maximum content scroll range along the X axis 12113 * @param scrollRangeY Maximum content scroll range along the Y axis 12114 * @param maxOverScrollX Number of pixels to overscroll by in either direction 12115 * along the X axis. 12116 * @param maxOverScrollY Number of pixels to overscroll by in either direction 12117 * along the Y axis. 12118 * @param isTouchEvent true if this scroll operation is the result of a touch event. 12119 * @return true if scrolling was clamped to an over-scroll boundary along either 12120 * axis, false otherwise. 12121 */ 12122 @SuppressWarnings({"UnusedParameters"}) 12123 protected boolean overScrollBy(int deltaX, int deltaY, 12124 int scrollX, int scrollY, 12125 int scrollRangeX, int scrollRangeY, 12126 int maxOverScrollX, int maxOverScrollY, 12127 boolean isTouchEvent) { 12128 final int overScrollMode = mOverScrollMode; 12129 final boolean canScrollHorizontal = 12130 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 12131 final boolean canScrollVertical = 12132 computeVerticalScrollRange() > computeVerticalScrollExtent(); 12133 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 12134 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 12135 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 12136 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 12137 12138 int newScrollX = scrollX + deltaX; 12139 if (!overScrollHorizontal) { 12140 maxOverScrollX = 0; 12141 } 12142 12143 int newScrollY = scrollY + deltaY; 12144 if (!overScrollVertical) { 12145 maxOverScrollY = 0; 12146 } 12147 12148 // Clamp values if at the limits and record 12149 final int left = -maxOverScrollX; 12150 final int right = maxOverScrollX + scrollRangeX; 12151 final int top = -maxOverScrollY; 12152 final int bottom = maxOverScrollY + scrollRangeY; 12153 12154 boolean clampedX = false; 12155 if (newScrollX > right) { 12156 newScrollX = right; 12157 clampedX = true; 12158 } else if (newScrollX < left) { 12159 newScrollX = left; 12160 clampedX = true; 12161 } 12162 12163 boolean clampedY = false; 12164 if (newScrollY > bottom) { 12165 newScrollY = bottom; 12166 clampedY = true; 12167 } else if (newScrollY < top) { 12168 newScrollY = top; 12169 clampedY = true; 12170 } 12171 12172 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 12173 12174 return clampedX || clampedY; 12175 } 12176 12177 /** 12178 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 12179 * respond to the results of an over-scroll operation. 12180 * 12181 * @param scrollX New X scroll value in pixels 12182 * @param scrollY New Y scroll value in pixels 12183 * @param clampedX True if scrollX was clamped to an over-scroll boundary 12184 * @param clampedY True if scrollY was clamped to an over-scroll boundary 12185 */ 12186 protected void onOverScrolled(int scrollX, int scrollY, 12187 boolean clampedX, boolean clampedY) { 12188 // Intentionally empty. 12189 } 12190 12191 /** 12192 * Returns the over-scroll mode for this view. The result will be 12193 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 12194 * (allow over-scrolling only if the view content is larger than the container), 12195 * or {@link #OVER_SCROLL_NEVER}. 12196 * 12197 * @return This view's over-scroll mode. 12198 */ 12199 public int getOverScrollMode() { 12200 return mOverScrollMode; 12201 } 12202 12203 /** 12204 * Set the over-scroll mode for this view. Valid over-scroll modes are 12205 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 12206 * (allow over-scrolling only if the view content is larger than the container), 12207 * or {@link #OVER_SCROLL_NEVER}. 12208 * 12209 * Setting the over-scroll mode of a view will have an effect only if the 12210 * view is capable of scrolling. 12211 * 12212 * @param overScrollMode The new over-scroll mode for this view. 12213 */ 12214 public void setOverScrollMode(int overScrollMode) { 12215 if (overScrollMode != OVER_SCROLL_ALWAYS && 12216 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 12217 overScrollMode != OVER_SCROLL_NEVER) { 12218 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 12219 } 12220 mOverScrollMode = overScrollMode; 12221 } 12222 12223 /** 12224 * Gets a scale factor that determines the distance the view should scroll 12225 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 12226 * @return The vertical scroll scale factor. 12227 * @hide 12228 */ 12229 protected float getVerticalScrollFactor() { 12230 if (mVerticalScrollFactor == 0) { 12231 TypedValue outValue = new TypedValue(); 12232 if (!mContext.getTheme().resolveAttribute( 12233 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 12234 throw new IllegalStateException( 12235 "Expected theme to define listPreferredItemHeight."); 12236 } 12237 mVerticalScrollFactor = outValue.getDimension( 12238 mContext.getResources().getDisplayMetrics()); 12239 } 12240 return mVerticalScrollFactor; 12241 } 12242 12243 /** 12244 * Gets a scale factor that determines the distance the view should scroll 12245 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 12246 * @return The horizontal scroll scale factor. 12247 * @hide 12248 */ 12249 protected float getHorizontalScrollFactor() { 12250 // TODO: Should use something else. 12251 return getVerticalScrollFactor(); 12252 } 12253 12254 /** 12255 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 12256 * Each MeasureSpec represents a requirement for either the width or the height. 12257 * A MeasureSpec is comprised of a size and a mode. There are three possible 12258 * modes: 12259 * <dl> 12260 * <dt>UNSPECIFIED</dt> 12261 * <dd> 12262 * The parent has not imposed any constraint on the child. It can be whatever size 12263 * it wants. 12264 * </dd> 12265 * 12266 * <dt>EXACTLY</dt> 12267 * <dd> 12268 * The parent has determined an exact size for the child. The child is going to be 12269 * given those bounds regardless of how big it wants to be. 12270 * </dd> 12271 * 12272 * <dt>AT_MOST</dt> 12273 * <dd> 12274 * The child can be as large as it wants up to the specified size. 12275 * </dd> 12276 * </dl> 12277 * 12278 * MeasureSpecs are implemented as ints to reduce object allocation. This class 12279 * is provided to pack and unpack the <size, mode> tuple into the int. 12280 */ 12281 public static class MeasureSpec { 12282 private static final int MODE_SHIFT = 30; 12283 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 12284 12285 /** 12286 * Measure specification mode: The parent has not imposed any constraint 12287 * on the child. It can be whatever size it wants. 12288 */ 12289 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 12290 12291 /** 12292 * Measure specification mode: The parent has determined an exact size 12293 * for the child. The child is going to be given those bounds regardless 12294 * of how big it wants to be. 12295 */ 12296 public static final int EXACTLY = 1 << MODE_SHIFT; 12297 12298 /** 12299 * Measure specification mode: The child can be as large as it wants up 12300 * to the specified size. 12301 */ 12302 public static final int AT_MOST = 2 << MODE_SHIFT; 12303 12304 /** 12305 * Creates a measure specification based on the supplied size and mode. 12306 * 12307 * The mode must always be one of the following: 12308 * <ul> 12309 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 12310 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 12311 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 12312 * </ul> 12313 * 12314 * @param size the size of the measure specification 12315 * @param mode the mode of the measure specification 12316 * @return the measure specification based on size and mode 12317 */ 12318 public static int makeMeasureSpec(int size, int mode) { 12319 return size + mode; 12320 } 12321 12322 /** 12323 * Extracts the mode from the supplied measure specification. 12324 * 12325 * @param measureSpec the measure specification to extract the mode from 12326 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 12327 * {@link android.view.View.MeasureSpec#AT_MOST} or 12328 * {@link android.view.View.MeasureSpec#EXACTLY} 12329 */ 12330 public static int getMode(int measureSpec) { 12331 return (measureSpec & MODE_MASK); 12332 } 12333 12334 /** 12335 * Extracts the size from the supplied measure specification. 12336 * 12337 * @param measureSpec the measure specification to extract the size from 12338 * @return the size in pixels defined in the supplied measure specification 12339 */ 12340 public static int getSize(int measureSpec) { 12341 return (measureSpec & ~MODE_MASK); 12342 } 12343 12344 /** 12345 * Returns a String representation of the specified measure 12346 * specification. 12347 * 12348 * @param measureSpec the measure specification to convert to a String 12349 * @return a String with the following format: "MeasureSpec: MODE SIZE" 12350 */ 12351 public static String toString(int measureSpec) { 12352 int mode = getMode(measureSpec); 12353 int size = getSize(measureSpec); 12354 12355 StringBuilder sb = new StringBuilder("MeasureSpec: "); 12356 12357 if (mode == UNSPECIFIED) 12358 sb.append("UNSPECIFIED "); 12359 else if (mode == EXACTLY) 12360 sb.append("EXACTLY "); 12361 else if (mode == AT_MOST) 12362 sb.append("AT_MOST "); 12363 else 12364 sb.append(mode).append(" "); 12365 12366 sb.append(size); 12367 return sb.toString(); 12368 } 12369 } 12370 12371 class CheckForLongPress implements Runnable { 12372 12373 private int mOriginalWindowAttachCount; 12374 12375 public void run() { 12376 if (isPressed() && (mParent != null) 12377 && mOriginalWindowAttachCount == mWindowAttachCount) { 12378 if (performLongClick()) { 12379 mHasPerformedLongPress = true; 12380 } 12381 } 12382 } 12383 12384 public void rememberWindowAttachCount() { 12385 mOriginalWindowAttachCount = mWindowAttachCount; 12386 } 12387 } 12388 12389 private final class CheckForTap implements Runnable { 12390 public void run() { 12391 mPrivateFlags &= ~PREPRESSED; 12392 mPrivateFlags |= PRESSED; 12393 refreshDrawableState(); 12394 checkForLongClick(ViewConfiguration.getTapTimeout()); 12395 } 12396 } 12397 12398 private final class PerformClick implements Runnable { 12399 public void run() { 12400 performClick(); 12401 } 12402 } 12403 12404 /** @hide */ 12405 public void hackTurnOffWindowResizeAnim(boolean off) { 12406 mAttachInfo.mTurnOffWindowResizeAnim = off; 12407 } 12408 12409 /** 12410 * This method returns a ViewPropertyAnimator object, which can be used to animate 12411 * specific properties on this View. 12412 * 12413 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 12414 */ 12415 public ViewPropertyAnimator animate() { 12416 if (mAnimator == null) { 12417 mAnimator = new ViewPropertyAnimator(this); 12418 } 12419 return mAnimator; 12420 } 12421 12422 /** 12423 * Interface definition for a callback to be invoked when a key event is 12424 * dispatched to this view. The callback will be invoked before the key 12425 * event is given to the view. 12426 */ 12427 public interface OnKeyListener { 12428 /** 12429 * Called when a key is dispatched to a view. This allows listeners to 12430 * get a chance to respond before the target view. 12431 * 12432 * @param v The view the key has been dispatched to. 12433 * @param keyCode The code for the physical key that was pressed 12434 * @param event The KeyEvent object containing full information about 12435 * the event. 12436 * @return True if the listener has consumed the event, false otherwise. 12437 */ 12438 boolean onKey(View v, int keyCode, KeyEvent event); 12439 } 12440 12441 /** 12442 * Interface definition for a callback to be invoked when a touch event is 12443 * dispatched to this view. The callback will be invoked before the touch 12444 * event is given to the view. 12445 */ 12446 public interface OnTouchListener { 12447 /** 12448 * Called when a touch event is dispatched to a view. This allows listeners to 12449 * get a chance to respond before the target view. 12450 * 12451 * @param v The view the touch event has been dispatched to. 12452 * @param event The MotionEvent object containing full information about 12453 * the event. 12454 * @return True if the listener has consumed the event, false otherwise. 12455 */ 12456 boolean onTouch(View v, MotionEvent event); 12457 } 12458 12459 /** 12460 * Interface definition for a callback to be invoked when a generic motion event is 12461 * dispatched to this view. The callback will be invoked before the generic motion 12462 * event is given to the view. 12463 */ 12464 public interface OnGenericMotionListener { 12465 /** 12466 * Called when a generic motion event is dispatched to a view. This allows listeners to 12467 * get a chance to respond before the target view. 12468 * 12469 * @param v The view the generic motion event has been dispatched to. 12470 * @param event The MotionEvent object containing full information about 12471 * the event. 12472 * @return True if the listener has consumed the event, false otherwise. 12473 */ 12474 boolean onGenericMotion(View v, MotionEvent event); 12475 } 12476 12477 /** 12478 * Interface definition for a callback to be invoked when a view has been clicked and held. 12479 */ 12480 public interface OnLongClickListener { 12481 /** 12482 * Called when a view has been clicked and held. 12483 * 12484 * @param v The view that was clicked and held. 12485 * 12486 * @return true if the callback consumed the long click, false otherwise. 12487 */ 12488 boolean onLongClick(View v); 12489 } 12490 12491 /** 12492 * Interface definition for a callback to be invoked when a drag is being dispatched 12493 * to this view. The callback will be invoked before the hosting view's own 12494 * onDrag(event) method. If the listener wants to fall back to the hosting view's 12495 * onDrag(event) behavior, it should return 'false' from this callback. 12496 */ 12497 public interface OnDragListener { 12498 /** 12499 * Called when a drag event is dispatched to a view. This allows listeners 12500 * to get a chance to override base View behavior. 12501 * 12502 * @param v The View that received the drag event. 12503 * @param event The {@link android.view.DragEvent} object for the drag event. 12504 * @return {@code true} if the drag event was handled successfully, or {@code false} 12505 * if the drag event was not handled. Note that {@code false} will trigger the View 12506 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 12507 */ 12508 boolean onDrag(View v, DragEvent event); 12509 } 12510 12511 /** 12512 * Interface definition for a callback to be invoked when the focus state of 12513 * a view changed. 12514 */ 12515 public interface OnFocusChangeListener { 12516 /** 12517 * Called when the focus state of a view has changed. 12518 * 12519 * @param v The view whose state has changed. 12520 * @param hasFocus The new focus state of v. 12521 */ 12522 void onFocusChange(View v, boolean hasFocus); 12523 } 12524 12525 /** 12526 * Interface definition for a callback to be invoked when a view is clicked. 12527 */ 12528 public interface OnClickListener { 12529 /** 12530 * Called when a view has been clicked. 12531 * 12532 * @param v The view that was clicked. 12533 */ 12534 void onClick(View v); 12535 } 12536 12537 /** 12538 * Interface definition for a callback to be invoked when the context menu 12539 * for this view is being built. 12540 */ 12541 public interface OnCreateContextMenuListener { 12542 /** 12543 * Called when the context menu for this view is being built. It is not 12544 * safe to hold onto the menu after this method returns. 12545 * 12546 * @param menu The context menu that is being built 12547 * @param v The view for which the context menu is being built 12548 * @param menuInfo Extra information about the item for which the 12549 * context menu should be shown. This information will vary 12550 * depending on the class of v. 12551 */ 12552 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 12553 } 12554 12555 /** 12556 * Interface definition for a callback to be invoked when the status bar changes 12557 * visibility. 12558 * 12559 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 12560 */ 12561 public interface OnSystemUiVisibilityChangeListener { 12562 /** 12563 * Called when the status bar changes visibility because of a call to 12564 * {@link View#setSystemUiVisibility(int)}. 12565 * 12566 * @param visibility {@link #STATUS_BAR_VISIBLE} or {@link #STATUS_BAR_HIDDEN}. 12567 */ 12568 public void onSystemUiVisibilityChange(int visibility); 12569 } 12570 12571 /** 12572 * Interface definition for a callback to be invoked when this view is attached 12573 * or detached from its window. 12574 */ 12575 public interface OnAttachStateChangeListener { 12576 /** 12577 * Called when the view is attached to a window. 12578 * @param v The view that was attached 12579 */ 12580 public void onViewAttachedToWindow(View v); 12581 /** 12582 * Called when the view is detached from a window. 12583 * @param v The view that was detached 12584 */ 12585 public void onViewDetachedFromWindow(View v); 12586 } 12587 12588 private final class UnsetPressedState implements Runnable { 12589 public void run() { 12590 setPressed(false); 12591 } 12592 } 12593 12594 /** 12595 * Base class for derived classes that want to save and restore their own 12596 * state in {@link android.view.View#onSaveInstanceState()}. 12597 */ 12598 public static class BaseSavedState extends AbsSavedState { 12599 /** 12600 * Constructor used when reading from a parcel. Reads the state of the superclass. 12601 * 12602 * @param source 12603 */ 12604 public BaseSavedState(Parcel source) { 12605 super(source); 12606 } 12607 12608 /** 12609 * Constructor called by derived classes when creating their SavedState objects 12610 * 12611 * @param superState The state of the superclass of this view 12612 */ 12613 public BaseSavedState(Parcelable superState) { 12614 super(superState); 12615 } 12616 12617 public static final Parcelable.Creator<BaseSavedState> CREATOR = 12618 new Parcelable.Creator<BaseSavedState>() { 12619 public BaseSavedState createFromParcel(Parcel in) { 12620 return new BaseSavedState(in); 12621 } 12622 12623 public BaseSavedState[] newArray(int size) { 12624 return new BaseSavedState[size]; 12625 } 12626 }; 12627 } 12628 12629 /** 12630 * A set of information given to a view when it is attached to its parent 12631 * window. 12632 */ 12633 static class AttachInfo { 12634 interface Callbacks { 12635 void playSoundEffect(int effectId); 12636 boolean performHapticFeedback(int effectId, boolean always); 12637 } 12638 12639 /** 12640 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 12641 * to a Handler. This class contains the target (View) to invalidate and 12642 * the coordinates of the dirty rectangle. 12643 * 12644 * For performance purposes, this class also implements a pool of up to 12645 * POOL_LIMIT objects that get reused. This reduces memory allocations 12646 * whenever possible. 12647 */ 12648 static class InvalidateInfo implements Poolable<InvalidateInfo> { 12649 private static final int POOL_LIMIT = 10; 12650 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool( 12651 Pools.finitePool(new PoolableManager<InvalidateInfo>() { 12652 public InvalidateInfo newInstance() { 12653 return new InvalidateInfo(); 12654 } 12655 12656 public void onAcquired(InvalidateInfo element) { 12657 } 12658 12659 public void onReleased(InvalidateInfo element) { 12660 } 12661 }, POOL_LIMIT) 12662 ); 12663 12664 private InvalidateInfo mNext; 12665 12666 View target; 12667 12668 int left; 12669 int top; 12670 int right; 12671 int bottom; 12672 12673 public void setNextPoolable(InvalidateInfo element) { 12674 mNext = element; 12675 } 12676 12677 public InvalidateInfo getNextPoolable() { 12678 return mNext; 12679 } 12680 12681 static InvalidateInfo acquire() { 12682 return sPool.acquire(); 12683 } 12684 12685 void release() { 12686 sPool.release(this); 12687 } 12688 } 12689 12690 final IWindowSession mSession; 12691 12692 final IWindow mWindow; 12693 12694 final IBinder mWindowToken; 12695 12696 final Callbacks mRootCallbacks; 12697 12698 Canvas mHardwareCanvas; 12699 12700 /** 12701 * The top view of the hierarchy. 12702 */ 12703 View mRootView; 12704 12705 IBinder mPanelParentWindowToken; 12706 Surface mSurface; 12707 12708 boolean mHardwareAccelerated; 12709 boolean mHardwareAccelerationRequested; 12710 HardwareRenderer mHardwareRenderer; 12711 12712 /** 12713 * Scale factor used by the compatibility mode 12714 */ 12715 float mApplicationScale; 12716 12717 /** 12718 * Indicates whether the application is in compatibility mode 12719 */ 12720 boolean mScalingRequired; 12721 12722 /** 12723 * If set, ViewAncestor doesn't use its lame animation for when the window resizes. 12724 */ 12725 boolean mTurnOffWindowResizeAnim; 12726 12727 /** 12728 * Left position of this view's window 12729 */ 12730 int mWindowLeft; 12731 12732 /** 12733 * Top position of this view's window 12734 */ 12735 int mWindowTop; 12736 12737 /** 12738 * Indicates whether views need to use 32-bit drawing caches 12739 */ 12740 boolean mUse32BitDrawingCache; 12741 12742 /** 12743 * For windows that are full-screen but using insets to layout inside 12744 * of the screen decorations, these are the current insets for the 12745 * content of the window. 12746 */ 12747 final Rect mContentInsets = new Rect(); 12748 12749 /** 12750 * For windows that are full-screen but using insets to layout inside 12751 * of the screen decorations, these are the current insets for the 12752 * actual visible parts of the window. 12753 */ 12754 final Rect mVisibleInsets = new Rect(); 12755 12756 /** 12757 * The internal insets given by this window. This value is 12758 * supplied by the client (through 12759 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 12760 * be given to the window manager when changed to be used in laying 12761 * out windows behind it. 12762 */ 12763 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 12764 = new ViewTreeObserver.InternalInsetsInfo(); 12765 12766 /** 12767 * All views in the window's hierarchy that serve as scroll containers, 12768 * used to determine if the window can be resized or must be panned 12769 * to adjust for a soft input area. 12770 */ 12771 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 12772 12773 final KeyEvent.DispatcherState mKeyDispatchState 12774 = new KeyEvent.DispatcherState(); 12775 12776 /** 12777 * Indicates whether the view's window currently has the focus. 12778 */ 12779 boolean mHasWindowFocus; 12780 12781 /** 12782 * The current visibility of the window. 12783 */ 12784 int mWindowVisibility; 12785 12786 /** 12787 * Indicates the time at which drawing started to occur. 12788 */ 12789 long mDrawingTime; 12790 12791 /** 12792 * Indicates whether or not ignoring the DIRTY_MASK flags. 12793 */ 12794 boolean mIgnoreDirtyState; 12795 12796 /** 12797 * Indicates whether the view's window is currently in touch mode. 12798 */ 12799 boolean mInTouchMode; 12800 12801 /** 12802 * Indicates that ViewAncestor should trigger a global layout change 12803 * the next time it performs a traversal 12804 */ 12805 boolean mRecomputeGlobalAttributes; 12806 12807 /** 12808 * Set during a traveral if any views want to keep the screen on. 12809 */ 12810 boolean mKeepScreenOn; 12811 12812 /** 12813 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 12814 */ 12815 int mSystemUiVisibility; 12816 12817 /** 12818 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 12819 * attached. 12820 */ 12821 boolean mHasSystemUiListeners; 12822 12823 /** 12824 * Set if the visibility of any views has changed. 12825 */ 12826 boolean mViewVisibilityChanged; 12827 12828 /** 12829 * Set to true if a view has been scrolled. 12830 */ 12831 boolean mViewScrollChanged; 12832 12833 /** 12834 * Global to the view hierarchy used as a temporary for dealing with 12835 * x/y points in the transparent region computations. 12836 */ 12837 final int[] mTransparentLocation = new int[2]; 12838 12839 /** 12840 * Global to the view hierarchy used as a temporary for dealing with 12841 * x/y points in the ViewGroup.invalidateChild implementation. 12842 */ 12843 final int[] mInvalidateChildLocation = new int[2]; 12844 12845 12846 /** 12847 * Global to the view hierarchy used as a temporary for dealing with 12848 * x/y location when view is transformed. 12849 */ 12850 final float[] mTmpTransformLocation = new float[2]; 12851 12852 /** 12853 * The view tree observer used to dispatch global events like 12854 * layout, pre-draw, touch mode change, etc. 12855 */ 12856 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 12857 12858 /** 12859 * A Canvas used by the view hierarchy to perform bitmap caching. 12860 */ 12861 Canvas mCanvas; 12862 12863 /** 12864 * A Handler supplied by a view's {@link android.view.ViewAncestor}. This 12865 * handler can be used to pump events in the UI events queue. 12866 */ 12867 final Handler mHandler; 12868 12869 /** 12870 * Identifier for messages requesting the view to be invalidated. 12871 * Such messages should be sent to {@link #mHandler}. 12872 */ 12873 static final int INVALIDATE_MSG = 0x1; 12874 12875 /** 12876 * Identifier for messages requesting the view to invalidate a region. 12877 * Such messages should be sent to {@link #mHandler}. 12878 */ 12879 static final int INVALIDATE_RECT_MSG = 0x2; 12880 12881 /** 12882 * Temporary for use in computing invalidate rectangles while 12883 * calling up the hierarchy. 12884 */ 12885 final Rect mTmpInvalRect = new Rect(); 12886 12887 /** 12888 * Temporary for use in computing hit areas with transformed views 12889 */ 12890 final RectF mTmpTransformRect = new RectF(); 12891 12892 /** 12893 * Temporary list for use in collecting focusable descendents of a view. 12894 */ 12895 final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24); 12896 12897 /** 12898 * Creates a new set of attachment information with the specified 12899 * events handler and thread. 12900 * 12901 * @param handler the events handler the view must use 12902 */ 12903 AttachInfo(IWindowSession session, IWindow window, 12904 Handler handler, Callbacks effectPlayer) { 12905 mSession = session; 12906 mWindow = window; 12907 mWindowToken = window.asBinder(); 12908 mHandler = handler; 12909 mRootCallbacks = effectPlayer; 12910 } 12911 } 12912 12913 /** 12914 * <p>ScrollabilityCache holds various fields used by a View when scrolling 12915 * is supported. This avoids keeping too many unused fields in most 12916 * instances of View.</p> 12917 */ 12918 private static class ScrollabilityCache implements Runnable { 12919 12920 /** 12921 * Scrollbars are not visible 12922 */ 12923 public static final int OFF = 0; 12924 12925 /** 12926 * Scrollbars are visible 12927 */ 12928 public static final int ON = 1; 12929 12930 /** 12931 * Scrollbars are fading away 12932 */ 12933 public static final int FADING = 2; 12934 12935 public boolean fadeScrollBars; 12936 12937 public int fadingEdgeLength; 12938 public int scrollBarDefaultDelayBeforeFade; 12939 public int scrollBarFadeDuration; 12940 12941 public int scrollBarSize; 12942 public ScrollBarDrawable scrollBar; 12943 public float[] interpolatorValues; 12944 public View host; 12945 12946 public final Paint paint; 12947 public final Matrix matrix; 12948 public Shader shader; 12949 12950 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 12951 12952 private static final float[] OPAQUE = { 255 }; 12953 private static final float[] TRANSPARENT = { 0.0f }; 12954 12955 /** 12956 * When fading should start. This time moves into the future every time 12957 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 12958 */ 12959 public long fadeStartTime; 12960 12961 12962 /** 12963 * The current state of the scrollbars: ON, OFF, or FADING 12964 */ 12965 public int state = OFF; 12966 12967 private int mLastColor; 12968 12969 public ScrollabilityCache(ViewConfiguration configuration, View host) { 12970 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 12971 scrollBarSize = configuration.getScaledScrollBarSize(); 12972 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 12973 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 12974 12975 paint = new Paint(); 12976 matrix = new Matrix(); 12977 // use use a height of 1, and then wack the matrix each time we 12978 // actually use it. 12979 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 12980 12981 paint.setShader(shader); 12982 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 12983 this.host = host; 12984 } 12985 12986 public void setFadeColor(int color) { 12987 if (color != 0 && color != mLastColor) { 12988 mLastColor = color; 12989 color |= 0xFF000000; 12990 12991 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 12992 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 12993 12994 paint.setShader(shader); 12995 // Restore the default transfer mode (src_over) 12996 paint.setXfermode(null); 12997 } 12998 } 12999 13000 public void run() { 13001 long now = AnimationUtils.currentAnimationTimeMillis(); 13002 if (now >= fadeStartTime) { 13003 13004 // the animation fades the scrollbars out by changing 13005 // the opacity (alpha) from fully opaque to fully 13006 // transparent 13007 int nextFrame = (int) now; 13008 int framesCount = 0; 13009 13010 Interpolator interpolator = scrollBarInterpolator; 13011 13012 // Start opaque 13013 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 13014 13015 // End transparent 13016 nextFrame += scrollBarFadeDuration; 13017 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 13018 13019 state = FADING; 13020 13021 // Kick off the fade animation 13022 host.invalidate(true); 13023 } 13024 } 13025 13026 } 13027} 13028