View.java revision 6254f4806dd3db53b7380e77fbb183065685573e
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.view; 18 19import android.content.ClipData; 20import android.content.Context; 21import android.content.res.Configuration; 22import android.content.res.Resources; 23import android.content.res.TypedArray; 24import android.graphics.Bitmap; 25import android.graphics.Camera; 26import android.graphics.Canvas; 27import android.graphics.Insets; 28import android.graphics.Interpolator; 29import android.graphics.LinearGradient; 30import android.graphics.Matrix; 31import android.graphics.Paint; 32import android.graphics.PixelFormat; 33import android.graphics.Point; 34import android.graphics.PorterDuff; 35import android.graphics.PorterDuffXfermode; 36import android.graphics.Rect; 37import android.graphics.RectF; 38import android.graphics.Region; 39import android.graphics.Shader; 40import android.graphics.drawable.ColorDrawable; 41import android.graphics.drawable.Drawable; 42import android.hardware.display.DisplayManagerGlobal; 43import android.os.Build; 44import android.os.Bundle; 45import android.os.Handler; 46import android.os.IBinder; 47import android.os.Parcel; 48import android.os.Parcelable; 49import android.os.RemoteException; 50import android.os.SystemClock; 51import android.os.SystemProperties; 52import android.text.TextUtils; 53import android.util.AttributeSet; 54import android.util.FloatProperty; 55import android.util.Log; 56import android.util.Pools.SynchronizedPool; 57import android.util.Property; 58import android.util.SparseArray; 59import android.util.TypedValue; 60import android.view.ContextMenu.ContextMenuInfo; 61import android.view.AccessibilityIterators.TextSegmentIterator; 62import android.view.AccessibilityIterators.CharacterTextSegmentIterator; 63import android.view.AccessibilityIterators.WordTextSegmentIterator; 64import android.view.AccessibilityIterators.ParagraphTextSegmentIterator; 65import android.view.accessibility.AccessibilityEvent; 66import android.view.accessibility.AccessibilityEventSource; 67import android.view.accessibility.AccessibilityManager; 68import android.view.accessibility.AccessibilityNodeInfo; 69import android.view.accessibility.AccessibilityNodeProvider; 70import android.view.animation.Animation; 71import android.view.animation.AnimationUtils; 72import android.view.animation.Transformation; 73import android.view.inputmethod.EditorInfo; 74import android.view.inputmethod.InputConnection; 75import android.view.inputmethod.InputMethodManager; 76import android.view.transition.Scene; 77import android.widget.ScrollBarDrawable; 78 79import static android.os.Build.VERSION_CODES.*; 80import static java.lang.Math.max; 81 82import com.android.internal.R; 83import com.android.internal.util.Predicate; 84import com.android.internal.view.menu.MenuBuilder; 85import com.google.android.collect.Lists; 86import com.google.android.collect.Maps; 87 88import java.lang.ref.WeakReference; 89import java.lang.reflect.Field; 90import java.lang.reflect.InvocationTargetException; 91import java.lang.reflect.Method; 92import java.lang.reflect.Modifier; 93import java.util.ArrayList; 94import java.util.Arrays; 95import java.util.Collections; 96import java.util.HashMap; 97import java.util.Locale; 98import java.util.concurrent.CopyOnWriteArrayList; 99import java.util.concurrent.atomic.AtomicInteger; 100 101/** 102 * <p> 103 * This class represents the basic building block for user interface components. A View 104 * occupies a rectangular area on the screen and is responsible for drawing and 105 * event handling. View is the base class for <em>widgets</em>, which are 106 * used to create interactive UI components (buttons, text fields, etc.). The 107 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 108 * are invisible containers that hold other Views (or other ViewGroups) and define 109 * their layout properties. 110 * </p> 111 * 112 * <div class="special reference"> 113 * <h3>Developer Guides</h3> 114 * <p>For information about using this class to develop your application's user interface, 115 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide. 116 * </div> 117 * 118 * <a name="Using"></a> 119 * <h3>Using Views</h3> 120 * <p> 121 * All of the views in a window are arranged in a single tree. You can add views 122 * either from code or by specifying a tree of views in one or more XML layout 123 * files. There are many specialized subclasses of views that act as controls or 124 * are capable of displaying text, images, or other content. 125 * </p> 126 * <p> 127 * Once you have created a tree of views, there are typically a few types of 128 * common operations you may wish to perform: 129 * <ul> 130 * <li><strong>Set properties:</strong> for example setting the text of a 131 * {@link android.widget.TextView}. The available properties and the methods 132 * that set them will vary among the different subclasses of views. Note that 133 * properties that are known at build time can be set in the XML layout 134 * files.</li> 135 * <li><strong>Set focus:</strong> The framework will handled moving focus in 136 * response to user input. To force focus to a specific view, call 137 * {@link #requestFocus}.</li> 138 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 139 * that will be notified when something interesting happens to the view. For 140 * example, all views will let you set a listener to be notified when the view 141 * gains or loses focus. You can register such a listener using 142 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 143 * Other view subclasses offer more specialized listeners. For example, a Button 144 * exposes a listener to notify clients when the button is clicked.</li> 145 * <li><strong>Set visibility:</strong> You can hide or show views using 146 * {@link #setVisibility(int)}.</li> 147 * </ul> 148 * </p> 149 * <p><em> 150 * Note: The Android framework is responsible for measuring, laying out and 151 * drawing views. You should not call methods that perform these actions on 152 * views yourself unless you are actually implementing a 153 * {@link android.view.ViewGroup}. 154 * </em></p> 155 * 156 * <a name="Lifecycle"></a> 157 * <h3>Implementing a Custom View</h3> 158 * 159 * <p> 160 * To implement a custom view, you will usually begin by providing overrides for 161 * some of the standard methods that the framework calls on all views. You do 162 * not need to override all of these methods. In fact, you can start by just 163 * overriding {@link #onDraw(android.graphics.Canvas)}. 164 * <table border="2" width="85%" align="center" cellpadding="5"> 165 * <thead> 166 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 167 * </thead> 168 * 169 * <tbody> 170 * <tr> 171 * <td rowspan="2">Creation</td> 172 * <td>Constructors</td> 173 * <td>There is a form of the constructor that are called when the view 174 * is created from code and a form that is called when the view is 175 * inflated from a layout file. The second form should parse and apply 176 * any attributes defined in the layout file. 177 * </td> 178 * </tr> 179 * <tr> 180 * <td><code>{@link #onFinishInflate()}</code></td> 181 * <td>Called after a view and all of its children has been inflated 182 * from XML.</td> 183 * </tr> 184 * 185 * <tr> 186 * <td rowspan="3">Layout</td> 187 * <td><code>{@link #onMeasure(int, int)}</code></td> 188 * <td>Called to determine the size requirements for this view and all 189 * of its children. 190 * </td> 191 * </tr> 192 * <tr> 193 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 194 * <td>Called when this view should assign a size and position to all 195 * of its children. 196 * </td> 197 * </tr> 198 * <tr> 199 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 200 * <td>Called when the size of this view has changed. 201 * </td> 202 * </tr> 203 * 204 * <tr> 205 * <td>Drawing</td> 206 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 207 * <td>Called when the view should render its content. 208 * </td> 209 * </tr> 210 * 211 * <tr> 212 * <td rowspan="4">Event processing</td> 213 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 214 * <td>Called when a new hardware key event occurs. 215 * </td> 216 * </tr> 217 * <tr> 218 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 219 * <td>Called when a hardware key up event occurs. 220 * </td> 221 * </tr> 222 * <tr> 223 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 224 * <td>Called when a trackball motion event occurs. 225 * </td> 226 * </tr> 227 * <tr> 228 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 229 * <td>Called when a touch screen motion event occurs. 230 * </td> 231 * </tr> 232 * 233 * <tr> 234 * <td rowspan="2">Focus</td> 235 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 236 * <td>Called when the view gains or loses focus. 237 * </td> 238 * </tr> 239 * 240 * <tr> 241 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 242 * <td>Called when the window containing the view gains or loses focus. 243 * </td> 244 * </tr> 245 * 246 * <tr> 247 * <td rowspan="3">Attaching</td> 248 * <td><code>{@link #onAttachedToWindow()}</code></td> 249 * <td>Called when the view is attached to a window. 250 * </td> 251 * </tr> 252 * 253 * <tr> 254 * <td><code>{@link #onDetachedFromWindow}</code></td> 255 * <td>Called when the view is detached from its window. 256 * </td> 257 * </tr> 258 * 259 * <tr> 260 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 261 * <td>Called when the visibility of the window containing the view 262 * has changed. 263 * </td> 264 * </tr> 265 * </tbody> 266 * 267 * </table> 268 * </p> 269 * 270 * <a name="IDs"></a> 271 * <h3>IDs</h3> 272 * Views may have an integer id associated with them. These ids are typically 273 * assigned in the layout XML files, and are used to find specific views within 274 * the view tree. A common pattern is to: 275 * <ul> 276 * <li>Define a Button in the layout file and assign it a unique ID. 277 * <pre> 278 * <Button 279 * android:id="@+id/my_button" 280 * android:layout_width="wrap_content" 281 * android:layout_height="wrap_content" 282 * android:text="@string/my_button_text"/> 283 * </pre></li> 284 * <li>From the onCreate method of an Activity, find the Button 285 * <pre class="prettyprint"> 286 * Button myButton = (Button) findViewById(R.id.my_button); 287 * </pre></li> 288 * </ul> 289 * <p> 290 * View IDs need not be unique throughout the tree, but it is good practice to 291 * ensure that they are at least unique within the part of the tree you are 292 * searching. 293 * </p> 294 * 295 * <a name="Position"></a> 296 * <h3>Position</h3> 297 * <p> 298 * The geometry of a view is that of a rectangle. A view has a location, 299 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 300 * two dimensions, expressed as a width and a height. The unit for location 301 * and dimensions is the pixel. 302 * </p> 303 * 304 * <p> 305 * It is possible to retrieve the location of a view by invoking the methods 306 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 307 * coordinate of the rectangle representing the view. The latter returns the 308 * top, or Y, coordinate of the rectangle representing the view. These methods 309 * both return the location of the view relative to its parent. For instance, 310 * when getLeft() returns 20, that means the view is located 20 pixels to the 311 * right of the left edge of its direct parent. 312 * </p> 313 * 314 * <p> 315 * In addition, several convenience methods are offered to avoid unnecessary 316 * computations, namely {@link #getRight()} and {@link #getBottom()}. 317 * These methods return the coordinates of the right and bottom edges of the 318 * rectangle representing the view. For instance, calling {@link #getRight()} 319 * is similar to the following computation: <code>getLeft() + getWidth()</code> 320 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 321 * </p> 322 * 323 * <a name="SizePaddingMargins"></a> 324 * <h3>Size, padding and margins</h3> 325 * <p> 326 * The size of a view is expressed with a width and a height. A view actually 327 * possess two pairs of width and height values. 328 * </p> 329 * 330 * <p> 331 * The first pair is known as <em>measured width</em> and 332 * <em>measured height</em>. These dimensions define how big a view wants to be 333 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 334 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 335 * and {@link #getMeasuredHeight()}. 336 * </p> 337 * 338 * <p> 339 * The second pair is simply known as <em>width</em> and <em>height</em>, or 340 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 341 * dimensions define the actual size of the view on screen, at drawing time and 342 * after layout. These values may, but do not have to, be different from the 343 * measured width and height. The width and height can be obtained by calling 344 * {@link #getWidth()} and {@link #getHeight()}. 345 * </p> 346 * 347 * <p> 348 * To measure its dimensions, a view takes into account its padding. The padding 349 * is expressed in pixels for the left, top, right and bottom parts of the view. 350 * Padding can be used to offset the content of the view by a specific amount of 351 * pixels. For instance, a left padding of 2 will push the view's content by 352 * 2 pixels to the right of the left edge. Padding can be set using the 353 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)} 354 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 355 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()}, 356 * {@link #getPaddingEnd()}. 357 * </p> 358 * 359 * <p> 360 * Even though a view can define a padding, it does not provide any support for 361 * margins. However, view groups provide such a support. Refer to 362 * {@link android.view.ViewGroup} and 363 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 364 * </p> 365 * 366 * <a name="Layout"></a> 367 * <h3>Layout</h3> 368 * <p> 369 * Layout is a two pass process: a measure pass and a layout pass. The measuring 370 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 371 * of the view tree. Each view pushes dimension specifications down the tree 372 * during the recursion. At the end of the measure pass, every view has stored 373 * its measurements. The second pass happens in 374 * {@link #layout(int,int,int,int)} and is also top-down. During 375 * this pass each parent is responsible for positioning all of its children 376 * using the sizes computed in the measure pass. 377 * </p> 378 * 379 * <p> 380 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 381 * {@link #getMeasuredHeight()} values must be set, along with those for all of 382 * that view's descendants. A view's measured width and measured height values 383 * must respect the constraints imposed by the view's parents. This guarantees 384 * that at the end of the measure pass, all parents accept all of their 385 * children's measurements. A parent view may call measure() more than once on 386 * its children. For example, the parent may measure each child once with 387 * unspecified dimensions to find out how big they want to be, then call 388 * measure() on them again with actual numbers if the sum of all the children's 389 * unconstrained sizes is too big or too small. 390 * </p> 391 * 392 * <p> 393 * The measure pass uses two classes to communicate dimensions. The 394 * {@link MeasureSpec} class is used by views to tell their parents how they 395 * want to be measured and positioned. The base LayoutParams class just 396 * describes how big the view wants to be for both width and height. For each 397 * dimension, it can specify one of: 398 * <ul> 399 * <li> an exact number 400 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 401 * (minus padding) 402 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 403 * enclose its content (plus padding). 404 * </ul> 405 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 406 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 407 * an X and Y value. 408 * </p> 409 * 410 * <p> 411 * MeasureSpecs are used to push requirements down the tree from parent to 412 * child. A MeasureSpec can be in one of three modes: 413 * <ul> 414 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 415 * of a child view. For example, a LinearLayout may call measure() on its child 416 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 417 * tall the child view wants to be given a width of 240 pixels. 418 * <li>EXACTLY: This is used by the parent to impose an exact size on the 419 * child. The child must use this size, and guarantee that all of its 420 * descendants will fit within this size. 421 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 422 * child. The child must gurantee that it and all of its descendants will fit 423 * within this size. 424 * </ul> 425 * </p> 426 * 427 * <p> 428 * To intiate a layout, call {@link #requestLayout}. This method is typically 429 * called by a view on itself when it believes that is can no longer fit within 430 * its current bounds. 431 * </p> 432 * 433 * <a name="Drawing"></a> 434 * <h3>Drawing</h3> 435 * <p> 436 * Drawing is handled by walking the tree and rendering each view that 437 * intersects the invalid region. Because the tree is traversed in-order, 438 * this means that parents will draw before (i.e., behind) their children, with 439 * siblings drawn in the order they appear in the tree. 440 * If you set a background drawable for a View, then the View will draw it for you 441 * before calling back to its <code>onDraw()</code> method. 442 * </p> 443 * 444 * <p> 445 * Note that the framework will not draw views that are not in the invalid region. 446 * </p> 447 * 448 * <p> 449 * To force a view to draw, call {@link #invalidate()}. 450 * </p> 451 * 452 * <a name="EventHandlingThreading"></a> 453 * <h3>Event Handling and Threading</h3> 454 * <p> 455 * The basic cycle of a view is as follows: 456 * <ol> 457 * <li>An event comes in and is dispatched to the appropriate view. The view 458 * handles the event and notifies any listeners.</li> 459 * <li>If in the course of processing the event, the view's bounds may need 460 * to be changed, the view will call {@link #requestLayout()}.</li> 461 * <li>Similarly, if in the course of processing the event the view's appearance 462 * may need to be changed, the view will call {@link #invalidate()}.</li> 463 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 464 * the framework will take care of measuring, laying out, and drawing the tree 465 * as appropriate.</li> 466 * </ol> 467 * </p> 468 * 469 * <p><em>Note: The entire view tree is single threaded. You must always be on 470 * the UI thread when calling any method on any view.</em> 471 * If you are doing work on other threads and want to update the state of a view 472 * from that thread, you should use a {@link Handler}. 473 * </p> 474 * 475 * <a name="FocusHandling"></a> 476 * <h3>Focus Handling</h3> 477 * <p> 478 * The framework will handle routine focus movement in response to user input. 479 * This includes changing the focus as views are removed or hidden, or as new 480 * views become available. Views indicate their willingness to take focus 481 * through the {@link #isFocusable} method. To change whether a view can take 482 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 483 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 484 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 485 * </p> 486 * <p> 487 * Focus movement is based on an algorithm which finds the nearest neighbor in a 488 * given direction. In rare cases, the default algorithm may not match the 489 * intended behavior of the developer. In these situations, you can provide 490 * explicit overrides by using these XML attributes in the layout file: 491 * <pre> 492 * nextFocusDown 493 * nextFocusLeft 494 * nextFocusRight 495 * nextFocusUp 496 * </pre> 497 * </p> 498 * 499 * 500 * <p> 501 * To get a particular view to take focus, call {@link #requestFocus()}. 502 * </p> 503 * 504 * <a name="TouchMode"></a> 505 * <h3>Touch Mode</h3> 506 * <p> 507 * When a user is navigating a user interface via directional keys such as a D-pad, it is 508 * necessary to give focus to actionable items such as buttons so the user can see 509 * what will take input. If the device has touch capabilities, however, and the user 510 * begins interacting with the interface by touching it, it is no longer necessary to 511 * always highlight, or give focus to, a particular view. This motivates a mode 512 * for interaction named 'touch mode'. 513 * </p> 514 * <p> 515 * For a touch capable device, once the user touches the screen, the device 516 * will enter touch mode. From this point onward, only views for which 517 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 518 * Other views that are touchable, like buttons, will not take focus when touched; they will 519 * only fire the on click listeners. 520 * </p> 521 * <p> 522 * Any time a user hits a directional key, such as a D-pad direction, the view device will 523 * exit touch mode, and find a view to take focus, so that the user may resume interacting 524 * with the user interface without touching the screen again. 525 * </p> 526 * <p> 527 * The touch mode state is maintained across {@link android.app.Activity}s. Call 528 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 529 * </p> 530 * 531 * <a name="Scrolling"></a> 532 * <h3>Scrolling</h3> 533 * <p> 534 * The framework provides basic support for views that wish to internally 535 * scroll their content. This includes keeping track of the X and Y scroll 536 * offset as well as mechanisms for drawing scrollbars. See 537 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 538 * {@link #awakenScrollBars()} for more details. 539 * </p> 540 * 541 * <a name="Tags"></a> 542 * <h3>Tags</h3> 543 * <p> 544 * Unlike IDs, tags are not used to identify views. Tags are essentially an 545 * extra piece of information that can be associated with a view. They are most 546 * often used as a convenience to store data related to views in the views 547 * themselves rather than by putting them in a separate structure. 548 * </p> 549 * 550 * <a name="Properties"></a> 551 * <h3>Properties</h3> 552 * <p> 553 * The View class exposes an {@link #ALPHA} property, as well as several transform-related 554 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are 555 * available both in the {@link Property} form as well as in similarly-named setter/getter 556 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can 557 * be used to set persistent state associated with these rendering-related properties on the view. 558 * The properties and methods can also be used in conjunction with 559 * {@link android.animation.Animator Animator}-based animations, described more in the 560 * <a href="#Animation">Animation</a> section. 561 * </p> 562 * 563 * <a name="Animation"></a> 564 * <h3>Animation</h3> 565 * <p> 566 * Starting with Android 3.0, the preferred way of animating views is to use the 567 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based 568 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and 569 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0 570 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only 571 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class 572 * makes animating these View properties particularly easy and efficient. 573 * </p> 574 * <p> 575 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered. 576 * You can attach an {@link Animation} object to a view using 577 * {@link #setAnimation(Animation)} or 578 * {@link #startAnimation(Animation)}. The animation can alter the scale, 579 * rotation, translation and alpha of a view over time. If the animation is 580 * attached to a view that has children, the animation will affect the entire 581 * subtree rooted by that node. When an animation is started, the framework will 582 * take care of redrawing the appropriate views until the animation completes. 583 * </p> 584 * 585 * <a name="Security"></a> 586 * <h3>Security</h3> 587 * <p> 588 * Sometimes it is essential that an application be able to verify that an action 589 * is being performed with the full knowledge and consent of the user, such as 590 * granting a permission request, making a purchase or clicking on an advertisement. 591 * Unfortunately, a malicious application could try to spoof the user into 592 * performing these actions, unaware, by concealing the intended purpose of the view. 593 * As a remedy, the framework offers a touch filtering mechanism that can be used to 594 * improve the security of views that provide access to sensitive functionality. 595 * </p><p> 596 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 597 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 598 * will discard touches that are received whenever the view's window is obscured by 599 * another visible window. As a result, the view will not receive touches whenever a 600 * toast, dialog or other window appears above the view's window. 601 * </p><p> 602 * For more fine-grained control over security, consider overriding the 603 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 604 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 605 * </p> 606 * 607 * @attr ref android.R.styleable#View_alpha 608 * @attr ref android.R.styleable#View_background 609 * @attr ref android.R.styleable#View_clickable 610 * @attr ref android.R.styleable#View_contentDescription 611 * @attr ref android.R.styleable#View_drawingCacheQuality 612 * @attr ref android.R.styleable#View_duplicateParentState 613 * @attr ref android.R.styleable#View_id 614 * @attr ref android.R.styleable#View_requiresFadingEdge 615 * @attr ref android.R.styleable#View_fadeScrollbars 616 * @attr ref android.R.styleable#View_fadingEdgeLength 617 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 618 * @attr ref android.R.styleable#View_fitsSystemWindows 619 * @attr ref android.R.styleable#View_isScrollContainer 620 * @attr ref android.R.styleable#View_focusable 621 * @attr ref android.R.styleable#View_focusableInTouchMode 622 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 623 * @attr ref android.R.styleable#View_keepScreenOn 624 * @attr ref android.R.styleable#View_layerType 625 * @attr ref android.R.styleable#View_layoutDirection 626 * @attr ref android.R.styleable#View_longClickable 627 * @attr ref android.R.styleable#View_minHeight 628 * @attr ref android.R.styleable#View_minWidth 629 * @attr ref android.R.styleable#View_nextFocusDown 630 * @attr ref android.R.styleable#View_nextFocusLeft 631 * @attr ref android.R.styleable#View_nextFocusRight 632 * @attr ref android.R.styleable#View_nextFocusUp 633 * @attr ref android.R.styleable#View_onClick 634 * @attr ref android.R.styleable#View_padding 635 * @attr ref android.R.styleable#View_paddingBottom 636 * @attr ref android.R.styleable#View_paddingLeft 637 * @attr ref android.R.styleable#View_paddingRight 638 * @attr ref android.R.styleable#View_paddingTop 639 * @attr ref android.R.styleable#View_paddingStart 640 * @attr ref android.R.styleable#View_paddingEnd 641 * @attr ref android.R.styleable#View_saveEnabled 642 * @attr ref android.R.styleable#View_rotation 643 * @attr ref android.R.styleable#View_rotationX 644 * @attr ref android.R.styleable#View_rotationY 645 * @attr ref android.R.styleable#View_scaleX 646 * @attr ref android.R.styleable#View_scaleY 647 * @attr ref android.R.styleable#View_scrollX 648 * @attr ref android.R.styleable#View_scrollY 649 * @attr ref android.R.styleable#View_scrollbarSize 650 * @attr ref android.R.styleable#View_scrollbarStyle 651 * @attr ref android.R.styleable#View_scrollbars 652 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 653 * @attr ref android.R.styleable#View_scrollbarFadeDuration 654 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 655 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 656 * @attr ref android.R.styleable#View_scrollbarThumbVertical 657 * @attr ref android.R.styleable#View_scrollbarTrackVertical 658 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 659 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 660 * @attr ref android.R.styleable#View_soundEffectsEnabled 661 * @attr ref android.R.styleable#View_tag 662 * @attr ref android.R.styleable#View_textAlignment 663 * @attr ref android.R.styleable#View_textDirection 664 * @attr ref android.R.styleable#View_transformPivotX 665 * @attr ref android.R.styleable#View_transformPivotY 666 * @attr ref android.R.styleable#View_translationX 667 * @attr ref android.R.styleable#View_translationY 668 * @attr ref android.R.styleable#View_visibility 669 * 670 * @see android.view.ViewGroup 671 */ 672public class View implements Drawable.Callback, KeyEvent.Callback, 673 AccessibilityEventSource { 674 private static final boolean DBG = false; 675 676 /** 677 * The logging tag used by this class with android.util.Log. 678 */ 679 protected static final String VIEW_LOG_TAG = "View"; 680 681 /** 682 * When set to true, apps will draw debugging information about their layouts. 683 * 684 * @hide 685 */ 686 public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout"; 687 688 /** 689 * Used to mark a View that has no ID. 690 */ 691 public static final int NO_ID = -1; 692 693 private static boolean sUseBrokenMakeMeasureSpec = false; 694 695 /** 696 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 697 * calling setFlags. 698 */ 699 private static final int NOT_FOCUSABLE = 0x00000000; 700 701 /** 702 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 703 * setFlags. 704 */ 705 private static final int FOCUSABLE = 0x00000001; 706 707 /** 708 * Mask for use with setFlags indicating bits used for focus. 709 */ 710 private static final int FOCUSABLE_MASK = 0x00000001; 711 712 /** 713 * This view will adjust its padding to fit sytem windows (e.g. status bar) 714 */ 715 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 716 717 /** 718 * This view is visible. 719 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 720 * android:visibility}. 721 */ 722 public static final int VISIBLE = 0x00000000; 723 724 /** 725 * This view is invisible, but it still takes up space for layout purposes. 726 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 727 * android:visibility}. 728 */ 729 public static final int INVISIBLE = 0x00000004; 730 731 /** 732 * This view is invisible, and it doesn't take any space for layout 733 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 734 * android:visibility}. 735 */ 736 public static final int GONE = 0x00000008; 737 738 /** 739 * Mask for use with setFlags indicating bits used for visibility. 740 * {@hide} 741 */ 742 static final int VISIBILITY_MASK = 0x0000000C; 743 744 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 745 746 /** 747 * This view is enabled. Interpretation varies by subclass. 748 * Use with ENABLED_MASK when calling setFlags. 749 * {@hide} 750 */ 751 static final int ENABLED = 0x00000000; 752 753 /** 754 * This view is disabled. Interpretation varies by subclass. 755 * Use with ENABLED_MASK when calling setFlags. 756 * {@hide} 757 */ 758 static final int DISABLED = 0x00000020; 759 760 /** 761 * Mask for use with setFlags indicating bits used for indicating whether 762 * this view is enabled 763 * {@hide} 764 */ 765 static final int ENABLED_MASK = 0x00000020; 766 767 /** 768 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 769 * called and further optimizations will be performed. It is okay to have 770 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 771 * {@hide} 772 */ 773 static final int WILL_NOT_DRAW = 0x00000080; 774 775 /** 776 * Mask for use with setFlags indicating bits used for indicating whether 777 * this view is will draw 778 * {@hide} 779 */ 780 static final int DRAW_MASK = 0x00000080; 781 782 /** 783 * <p>This view doesn't show scrollbars.</p> 784 * {@hide} 785 */ 786 static final int SCROLLBARS_NONE = 0x00000000; 787 788 /** 789 * <p>This view shows horizontal scrollbars.</p> 790 * {@hide} 791 */ 792 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 793 794 /** 795 * <p>This view shows vertical scrollbars.</p> 796 * {@hide} 797 */ 798 static final int SCROLLBARS_VERTICAL = 0x00000200; 799 800 /** 801 * <p>Mask for use with setFlags indicating bits used for indicating which 802 * scrollbars are enabled.</p> 803 * {@hide} 804 */ 805 static final int SCROLLBARS_MASK = 0x00000300; 806 807 /** 808 * Indicates that the view should filter touches when its window is obscured. 809 * Refer to the class comments for more information about this security feature. 810 * {@hide} 811 */ 812 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 813 814 /** 815 * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate 816 * that they are optional and should be skipped if the window has 817 * requested system UI flags that ignore those insets for layout. 818 */ 819 static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800; 820 821 /** 822 * <p>This view doesn't show fading edges.</p> 823 * {@hide} 824 */ 825 static final int FADING_EDGE_NONE = 0x00000000; 826 827 /** 828 * <p>This view shows horizontal fading edges.</p> 829 * {@hide} 830 */ 831 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 832 833 /** 834 * <p>This view shows vertical fading edges.</p> 835 * {@hide} 836 */ 837 static final int FADING_EDGE_VERTICAL = 0x00002000; 838 839 /** 840 * <p>Mask for use with setFlags indicating bits used for indicating which 841 * fading edges are enabled.</p> 842 * {@hide} 843 */ 844 static final int FADING_EDGE_MASK = 0x00003000; 845 846 /** 847 * <p>Indicates this view can be clicked. When clickable, a View reacts 848 * to clicks by notifying the OnClickListener.<p> 849 * {@hide} 850 */ 851 static final int CLICKABLE = 0x00004000; 852 853 /** 854 * <p>Indicates this view is caching its drawing into a bitmap.</p> 855 * {@hide} 856 */ 857 static final int DRAWING_CACHE_ENABLED = 0x00008000; 858 859 /** 860 * <p>Indicates that no icicle should be saved for this view.<p> 861 * {@hide} 862 */ 863 static final int SAVE_DISABLED = 0x000010000; 864 865 /** 866 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 867 * property.</p> 868 * {@hide} 869 */ 870 static final int SAVE_DISABLED_MASK = 0x000010000; 871 872 /** 873 * <p>Indicates that no drawing cache should ever be created for this view.<p> 874 * {@hide} 875 */ 876 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 877 878 /** 879 * <p>Indicates this view can take / keep focus when int touch mode.</p> 880 * {@hide} 881 */ 882 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 883 884 /** 885 * <p>Enables low quality mode for the drawing cache.</p> 886 */ 887 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 888 889 /** 890 * <p>Enables high quality mode for the drawing cache.</p> 891 */ 892 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 893 894 /** 895 * <p>Enables automatic quality mode for the drawing cache.</p> 896 */ 897 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 898 899 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 900 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 901 }; 902 903 /** 904 * <p>Mask for use with setFlags indicating bits used for the cache 905 * quality property.</p> 906 * {@hide} 907 */ 908 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 909 910 /** 911 * <p> 912 * Indicates this view can be long clicked. When long clickable, a View 913 * reacts to long clicks by notifying the OnLongClickListener or showing a 914 * context menu. 915 * </p> 916 * {@hide} 917 */ 918 static final int LONG_CLICKABLE = 0x00200000; 919 920 /** 921 * <p>Indicates that this view gets its drawable states from its direct parent 922 * and ignores its original internal states.</p> 923 * 924 * @hide 925 */ 926 static final int DUPLICATE_PARENT_STATE = 0x00400000; 927 928 /** 929 * The scrollbar style to display the scrollbars inside the content area, 930 * without increasing the padding. The scrollbars will be overlaid with 931 * translucency on the view's content. 932 */ 933 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 934 935 /** 936 * The scrollbar style to display the scrollbars inside the padded area, 937 * increasing the padding of the view. The scrollbars will not overlap the 938 * content area of the view. 939 */ 940 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 941 942 /** 943 * The scrollbar style to display the scrollbars at the edge of the view, 944 * without increasing the padding. The scrollbars will be overlaid with 945 * translucency. 946 */ 947 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 948 949 /** 950 * The scrollbar style to display the scrollbars at the edge of the view, 951 * increasing the padding of the view. The scrollbars will only overlap the 952 * background, if any. 953 */ 954 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 955 956 /** 957 * Mask to check if the scrollbar style is overlay or inset. 958 * {@hide} 959 */ 960 static final int SCROLLBARS_INSET_MASK = 0x01000000; 961 962 /** 963 * Mask to check if the scrollbar style is inside or outside. 964 * {@hide} 965 */ 966 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 967 968 /** 969 * Mask for scrollbar style. 970 * {@hide} 971 */ 972 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 973 974 /** 975 * View flag indicating that the screen should remain on while the 976 * window containing this view is visible to the user. This effectively 977 * takes care of automatically setting the WindowManager's 978 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 979 */ 980 public static final int KEEP_SCREEN_ON = 0x04000000; 981 982 /** 983 * View flag indicating whether this view should have sound effects enabled 984 * for events such as clicking and touching. 985 */ 986 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 987 988 /** 989 * View flag indicating whether this view should have haptic feedback 990 * enabled for events such as long presses. 991 */ 992 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 993 994 /** 995 * <p>Indicates that the view hierarchy should stop saving state when 996 * it reaches this view. If state saving is initiated immediately at 997 * the view, it will be allowed. 998 * {@hide} 999 */ 1000 static final int PARENT_SAVE_DISABLED = 0x20000000; 1001 1002 /** 1003 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 1004 * {@hide} 1005 */ 1006 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 1007 1008 /** 1009 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1010 * should add all focusable Views regardless if they are focusable in touch mode. 1011 */ 1012 public static final int FOCUSABLES_ALL = 0x00000000; 1013 1014 /** 1015 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1016 * should add only Views focusable in touch mode. 1017 */ 1018 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1019 1020 /** 1021 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1022 * item. 1023 */ 1024 public static final int FOCUS_BACKWARD = 0x00000001; 1025 1026 /** 1027 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1028 * item. 1029 */ 1030 public static final int FOCUS_FORWARD = 0x00000002; 1031 1032 /** 1033 * Use with {@link #focusSearch(int)}. Move focus to the left. 1034 */ 1035 public static final int FOCUS_LEFT = 0x00000011; 1036 1037 /** 1038 * Use with {@link #focusSearch(int)}. Move focus up. 1039 */ 1040 public static final int FOCUS_UP = 0x00000021; 1041 1042 /** 1043 * Use with {@link #focusSearch(int)}. Move focus to the right. 1044 */ 1045 public static final int FOCUS_RIGHT = 0x00000042; 1046 1047 /** 1048 * Use with {@link #focusSearch(int)}. Move focus down. 1049 */ 1050 public static final int FOCUS_DOWN = 0x00000082; 1051 1052 /** 1053 * Bits of {@link #getMeasuredWidthAndState()} and 1054 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1055 */ 1056 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1057 1058 /** 1059 * Bits of {@link #getMeasuredWidthAndState()} and 1060 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1061 */ 1062 public static final int MEASURED_STATE_MASK = 0xff000000; 1063 1064 /** 1065 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1066 * for functions that combine both width and height into a single int, 1067 * such as {@link #getMeasuredState()} and the childState argument of 1068 * {@link #resolveSizeAndState(int, int, int)}. 1069 */ 1070 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1071 1072 /** 1073 * Bit of {@link #getMeasuredWidthAndState()} and 1074 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1075 * is smaller that the space the view would like to have. 1076 */ 1077 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1078 1079 /** 1080 * Base View state sets 1081 */ 1082 // Singles 1083 /** 1084 * Indicates the view has no states set. States are used with 1085 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1086 * view depending on its state. 1087 * 1088 * @see android.graphics.drawable.Drawable 1089 * @see #getDrawableState() 1090 */ 1091 protected static final int[] EMPTY_STATE_SET; 1092 /** 1093 * Indicates the view is enabled. States are used with 1094 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1095 * view depending on its state. 1096 * 1097 * @see android.graphics.drawable.Drawable 1098 * @see #getDrawableState() 1099 */ 1100 protected static final int[] ENABLED_STATE_SET; 1101 /** 1102 * Indicates the view is focused. States are used with 1103 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1104 * view depending on its state. 1105 * 1106 * @see android.graphics.drawable.Drawable 1107 * @see #getDrawableState() 1108 */ 1109 protected static final int[] FOCUSED_STATE_SET; 1110 /** 1111 * Indicates the view is selected. States are used with 1112 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1113 * view depending on its state. 1114 * 1115 * @see android.graphics.drawable.Drawable 1116 * @see #getDrawableState() 1117 */ 1118 protected static final int[] SELECTED_STATE_SET; 1119 /** 1120 * Indicates the view is pressed. States are used with 1121 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1122 * view depending on its state. 1123 * 1124 * @see android.graphics.drawable.Drawable 1125 * @see #getDrawableState() 1126 * @hide 1127 */ 1128 protected static final int[] PRESSED_STATE_SET; 1129 /** 1130 * Indicates the view's window has focus. States are used with 1131 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1132 * view depending on its state. 1133 * 1134 * @see android.graphics.drawable.Drawable 1135 * @see #getDrawableState() 1136 */ 1137 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1138 // Doubles 1139 /** 1140 * Indicates the view is enabled and has the focus. 1141 * 1142 * @see #ENABLED_STATE_SET 1143 * @see #FOCUSED_STATE_SET 1144 */ 1145 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1146 /** 1147 * Indicates the view is enabled and selected. 1148 * 1149 * @see #ENABLED_STATE_SET 1150 * @see #SELECTED_STATE_SET 1151 */ 1152 protected static final int[] ENABLED_SELECTED_STATE_SET; 1153 /** 1154 * Indicates the view is enabled and that its window has focus. 1155 * 1156 * @see #ENABLED_STATE_SET 1157 * @see #WINDOW_FOCUSED_STATE_SET 1158 */ 1159 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1160 /** 1161 * Indicates the view is focused and selected. 1162 * 1163 * @see #FOCUSED_STATE_SET 1164 * @see #SELECTED_STATE_SET 1165 */ 1166 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1167 /** 1168 * Indicates the view has the focus and that its window has the focus. 1169 * 1170 * @see #FOCUSED_STATE_SET 1171 * @see #WINDOW_FOCUSED_STATE_SET 1172 */ 1173 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1174 /** 1175 * Indicates the view is selected and that its window has the focus. 1176 * 1177 * @see #SELECTED_STATE_SET 1178 * @see #WINDOW_FOCUSED_STATE_SET 1179 */ 1180 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1181 // Triples 1182 /** 1183 * Indicates the view is enabled, focused and selected. 1184 * 1185 * @see #ENABLED_STATE_SET 1186 * @see #FOCUSED_STATE_SET 1187 * @see #SELECTED_STATE_SET 1188 */ 1189 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1190 /** 1191 * Indicates the view is enabled, focused and its window has the focus. 1192 * 1193 * @see #ENABLED_STATE_SET 1194 * @see #FOCUSED_STATE_SET 1195 * @see #WINDOW_FOCUSED_STATE_SET 1196 */ 1197 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1198 /** 1199 * Indicates the view is enabled, selected and its window has the focus. 1200 * 1201 * @see #ENABLED_STATE_SET 1202 * @see #SELECTED_STATE_SET 1203 * @see #WINDOW_FOCUSED_STATE_SET 1204 */ 1205 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1206 /** 1207 * Indicates the view is focused, selected and its window has the focus. 1208 * 1209 * @see #FOCUSED_STATE_SET 1210 * @see #SELECTED_STATE_SET 1211 * @see #WINDOW_FOCUSED_STATE_SET 1212 */ 1213 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1214 /** 1215 * Indicates the view is enabled, focused, selected and its window 1216 * has the focus. 1217 * 1218 * @see #ENABLED_STATE_SET 1219 * @see #FOCUSED_STATE_SET 1220 * @see #SELECTED_STATE_SET 1221 * @see #WINDOW_FOCUSED_STATE_SET 1222 */ 1223 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1224 /** 1225 * Indicates the view is pressed and its window has the focus. 1226 * 1227 * @see #PRESSED_STATE_SET 1228 * @see #WINDOW_FOCUSED_STATE_SET 1229 */ 1230 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1231 /** 1232 * Indicates the view is pressed and selected. 1233 * 1234 * @see #PRESSED_STATE_SET 1235 * @see #SELECTED_STATE_SET 1236 */ 1237 protected static final int[] PRESSED_SELECTED_STATE_SET; 1238 /** 1239 * Indicates the view is pressed, selected and its window has the focus. 1240 * 1241 * @see #PRESSED_STATE_SET 1242 * @see #SELECTED_STATE_SET 1243 * @see #WINDOW_FOCUSED_STATE_SET 1244 */ 1245 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1246 /** 1247 * Indicates the view is pressed and focused. 1248 * 1249 * @see #PRESSED_STATE_SET 1250 * @see #FOCUSED_STATE_SET 1251 */ 1252 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1253 /** 1254 * Indicates the view is pressed, focused and its window has the focus. 1255 * 1256 * @see #PRESSED_STATE_SET 1257 * @see #FOCUSED_STATE_SET 1258 * @see #WINDOW_FOCUSED_STATE_SET 1259 */ 1260 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1261 /** 1262 * Indicates the view is pressed, focused and selected. 1263 * 1264 * @see #PRESSED_STATE_SET 1265 * @see #SELECTED_STATE_SET 1266 * @see #FOCUSED_STATE_SET 1267 */ 1268 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1269 /** 1270 * Indicates the view is pressed, focused, selected and its window has the focus. 1271 * 1272 * @see #PRESSED_STATE_SET 1273 * @see #FOCUSED_STATE_SET 1274 * @see #SELECTED_STATE_SET 1275 * @see #WINDOW_FOCUSED_STATE_SET 1276 */ 1277 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1278 /** 1279 * Indicates the view is pressed and enabled. 1280 * 1281 * @see #PRESSED_STATE_SET 1282 * @see #ENABLED_STATE_SET 1283 */ 1284 protected static final int[] PRESSED_ENABLED_STATE_SET; 1285 /** 1286 * Indicates the view is pressed, enabled and its window has the focus. 1287 * 1288 * @see #PRESSED_STATE_SET 1289 * @see #ENABLED_STATE_SET 1290 * @see #WINDOW_FOCUSED_STATE_SET 1291 */ 1292 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1293 /** 1294 * Indicates the view is pressed, enabled and selected. 1295 * 1296 * @see #PRESSED_STATE_SET 1297 * @see #ENABLED_STATE_SET 1298 * @see #SELECTED_STATE_SET 1299 */ 1300 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1301 /** 1302 * Indicates the view is pressed, enabled, selected and its window has the 1303 * focus. 1304 * 1305 * @see #PRESSED_STATE_SET 1306 * @see #ENABLED_STATE_SET 1307 * @see #SELECTED_STATE_SET 1308 * @see #WINDOW_FOCUSED_STATE_SET 1309 */ 1310 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1311 /** 1312 * Indicates the view is pressed, enabled and focused. 1313 * 1314 * @see #PRESSED_STATE_SET 1315 * @see #ENABLED_STATE_SET 1316 * @see #FOCUSED_STATE_SET 1317 */ 1318 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1319 /** 1320 * Indicates the view is pressed, enabled, focused and its window has the 1321 * focus. 1322 * 1323 * @see #PRESSED_STATE_SET 1324 * @see #ENABLED_STATE_SET 1325 * @see #FOCUSED_STATE_SET 1326 * @see #WINDOW_FOCUSED_STATE_SET 1327 */ 1328 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1329 /** 1330 * Indicates the view is pressed, enabled, focused and selected. 1331 * 1332 * @see #PRESSED_STATE_SET 1333 * @see #ENABLED_STATE_SET 1334 * @see #SELECTED_STATE_SET 1335 * @see #FOCUSED_STATE_SET 1336 */ 1337 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1338 /** 1339 * Indicates the view is pressed, enabled, focused, selected and its window 1340 * has the focus. 1341 * 1342 * @see #PRESSED_STATE_SET 1343 * @see #ENABLED_STATE_SET 1344 * @see #SELECTED_STATE_SET 1345 * @see #FOCUSED_STATE_SET 1346 * @see #WINDOW_FOCUSED_STATE_SET 1347 */ 1348 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1349 1350 /** 1351 * The order here is very important to {@link #getDrawableState()} 1352 */ 1353 private static final int[][] VIEW_STATE_SETS; 1354 1355 static final int VIEW_STATE_WINDOW_FOCUSED = 1; 1356 static final int VIEW_STATE_SELECTED = 1 << 1; 1357 static final int VIEW_STATE_FOCUSED = 1 << 2; 1358 static final int VIEW_STATE_ENABLED = 1 << 3; 1359 static final int VIEW_STATE_PRESSED = 1 << 4; 1360 static final int VIEW_STATE_ACTIVATED = 1 << 5; 1361 static final int VIEW_STATE_ACCELERATED = 1 << 6; 1362 static final int VIEW_STATE_HOVERED = 1 << 7; 1363 static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8; 1364 static final int VIEW_STATE_DRAG_HOVERED = 1 << 9; 1365 1366 static final int[] VIEW_STATE_IDS = new int[] { 1367 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED, 1368 R.attr.state_selected, VIEW_STATE_SELECTED, 1369 R.attr.state_focused, VIEW_STATE_FOCUSED, 1370 R.attr.state_enabled, VIEW_STATE_ENABLED, 1371 R.attr.state_pressed, VIEW_STATE_PRESSED, 1372 R.attr.state_activated, VIEW_STATE_ACTIVATED, 1373 R.attr.state_accelerated, VIEW_STATE_ACCELERATED, 1374 R.attr.state_hovered, VIEW_STATE_HOVERED, 1375 R.attr.state_drag_can_accept, VIEW_STATE_DRAG_CAN_ACCEPT, 1376 R.attr.state_drag_hovered, VIEW_STATE_DRAG_HOVERED 1377 }; 1378 1379 static { 1380 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) { 1381 throw new IllegalStateException( 1382 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array"); 1383 } 1384 int[] orderedIds = new int[VIEW_STATE_IDS.length]; 1385 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) { 1386 int viewState = R.styleable.ViewDrawableStates[i]; 1387 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) { 1388 if (VIEW_STATE_IDS[j] == viewState) { 1389 orderedIds[i * 2] = viewState; 1390 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1]; 1391 } 1392 } 1393 } 1394 final int NUM_BITS = VIEW_STATE_IDS.length / 2; 1395 VIEW_STATE_SETS = new int[1 << NUM_BITS][]; 1396 for (int i = 0; i < VIEW_STATE_SETS.length; i++) { 1397 int numBits = Integer.bitCount(i); 1398 int[] set = new int[numBits]; 1399 int pos = 0; 1400 for (int j = 0; j < orderedIds.length; j += 2) { 1401 if ((i & orderedIds[j+1]) != 0) { 1402 set[pos++] = orderedIds[j]; 1403 } 1404 } 1405 VIEW_STATE_SETS[i] = set; 1406 } 1407 1408 EMPTY_STATE_SET = VIEW_STATE_SETS[0]; 1409 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED]; 1410 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED]; 1411 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1412 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED]; 1413 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED]; 1414 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1415 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED]; 1416 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1417 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED]; 1418 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1419 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1420 | VIEW_STATE_FOCUSED]; 1421 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED]; 1422 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1423 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED]; 1424 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1425 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED]; 1426 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1427 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1428 | VIEW_STATE_ENABLED]; 1429 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1430 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED]; 1431 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1432 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1433 | VIEW_STATE_ENABLED]; 1434 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1435 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1436 | VIEW_STATE_ENABLED]; 1437 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1438 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1439 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED]; 1440 1441 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED]; 1442 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1443 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED]; 1444 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1445 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED]; 1446 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1447 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1448 | VIEW_STATE_PRESSED]; 1449 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1450 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1451 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1452 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1453 | VIEW_STATE_PRESSED]; 1454 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1455 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1456 | VIEW_STATE_PRESSED]; 1457 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1458 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1459 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1460 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[ 1461 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1462 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1463 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED 1464 | VIEW_STATE_PRESSED]; 1465 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1466 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED 1467 | VIEW_STATE_PRESSED]; 1468 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1469 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1470 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1471 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1472 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED 1473 | VIEW_STATE_PRESSED]; 1474 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1475 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1476 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1477 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1478 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1479 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1480 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1481 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1482 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED 1483 | VIEW_STATE_PRESSED]; 1484 } 1485 1486 /** 1487 * Accessibility event types that are dispatched for text population. 1488 */ 1489 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 1490 AccessibilityEvent.TYPE_VIEW_CLICKED 1491 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 1492 | AccessibilityEvent.TYPE_VIEW_SELECTED 1493 | AccessibilityEvent.TYPE_VIEW_FOCUSED 1494 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 1495 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 1496 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 1497 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 1498 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED 1499 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED 1500 | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY; 1501 1502 /** 1503 * Temporary Rect currently for use in setBackground(). This will probably 1504 * be extended in the future to hold our own class with more than just 1505 * a Rect. :) 1506 */ 1507 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1508 1509 /** 1510 * Map used to store views' tags. 1511 */ 1512 private SparseArray<Object> mKeyedTags; 1513 1514 /** 1515 * The next available accessibility id. 1516 */ 1517 private static int sNextAccessibilityViewId; 1518 1519 /** 1520 * The animation currently associated with this view. 1521 * @hide 1522 */ 1523 protected Animation mCurrentAnimation = null; 1524 1525 /** 1526 * Width as measured during measure pass. 1527 * {@hide} 1528 */ 1529 @ViewDebug.ExportedProperty(category = "measurement") 1530 int mMeasuredWidth; 1531 1532 /** 1533 * Height as measured during measure pass. 1534 * {@hide} 1535 */ 1536 @ViewDebug.ExportedProperty(category = "measurement") 1537 int mMeasuredHeight; 1538 1539 /** 1540 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1541 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1542 * its display list. This flag, used only when hw accelerated, allows us to clear the 1543 * flag while retaining this information until it's needed (at getDisplayList() time and 1544 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1545 * 1546 * {@hide} 1547 */ 1548 boolean mRecreateDisplayList = false; 1549 1550 /** 1551 * The view's identifier. 1552 * {@hide} 1553 * 1554 * @see #setId(int) 1555 * @see #getId() 1556 */ 1557 @ViewDebug.ExportedProperty(resolveId = true) 1558 int mID = NO_ID; 1559 1560 /** 1561 * The stable ID of this view for accessibility purposes. 1562 */ 1563 int mAccessibilityViewId = NO_ID; 1564 1565 private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 1566 1567 SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent; 1568 1569 /** 1570 * The view's tag. 1571 * {@hide} 1572 * 1573 * @see #setTag(Object) 1574 * @see #getTag() 1575 */ 1576 protected Object mTag; 1577 1578 private Scene mCurrentScene = null; 1579 1580 // for mPrivateFlags: 1581 /** {@hide} */ 1582 static final int PFLAG_WANTS_FOCUS = 0x00000001; 1583 /** {@hide} */ 1584 static final int PFLAG_FOCUSED = 0x00000002; 1585 /** {@hide} */ 1586 static final int PFLAG_SELECTED = 0x00000004; 1587 /** {@hide} */ 1588 static final int PFLAG_IS_ROOT_NAMESPACE = 0x00000008; 1589 /** {@hide} */ 1590 static final int PFLAG_HAS_BOUNDS = 0x00000010; 1591 /** {@hide} */ 1592 static final int PFLAG_DRAWN = 0x00000020; 1593 /** 1594 * When this flag is set, this view is running an animation on behalf of its 1595 * children and should therefore not cancel invalidate requests, even if they 1596 * lie outside of this view's bounds. 1597 * 1598 * {@hide} 1599 */ 1600 static final int PFLAG_DRAW_ANIMATION = 0x00000040; 1601 /** {@hide} */ 1602 static final int PFLAG_SKIP_DRAW = 0x00000080; 1603 /** {@hide} */ 1604 static final int PFLAG_ONLY_DRAWS_BACKGROUND = 0x00000100; 1605 /** {@hide} */ 1606 static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1607 /** {@hide} */ 1608 static final int PFLAG_DRAWABLE_STATE_DIRTY = 0x00000400; 1609 /** {@hide} */ 1610 static final int PFLAG_MEASURED_DIMENSION_SET = 0x00000800; 1611 /** {@hide} */ 1612 static final int PFLAG_FORCE_LAYOUT = 0x00001000; 1613 /** {@hide} */ 1614 static final int PFLAG_LAYOUT_REQUIRED = 0x00002000; 1615 1616 private static final int PFLAG_PRESSED = 0x00004000; 1617 1618 /** {@hide} */ 1619 static final int PFLAG_DRAWING_CACHE_VALID = 0x00008000; 1620 /** 1621 * Flag used to indicate that this view should be drawn once more (and only once 1622 * more) after its animation has completed. 1623 * {@hide} 1624 */ 1625 static final int PFLAG_ANIMATION_STARTED = 0x00010000; 1626 1627 private static final int PFLAG_SAVE_STATE_CALLED = 0x00020000; 1628 1629 /** 1630 * Indicates that the View returned true when onSetAlpha() was called and that 1631 * the alpha must be restored. 1632 * {@hide} 1633 */ 1634 static final int PFLAG_ALPHA_SET = 0x00040000; 1635 1636 /** 1637 * Set by {@link #setScrollContainer(boolean)}. 1638 */ 1639 static final int PFLAG_SCROLL_CONTAINER = 0x00080000; 1640 1641 /** 1642 * Set by {@link #setScrollContainer(boolean)}. 1643 */ 1644 static final int PFLAG_SCROLL_CONTAINER_ADDED = 0x00100000; 1645 1646 /** 1647 * View flag indicating whether this view was invalidated (fully or partially.) 1648 * 1649 * @hide 1650 */ 1651 static final int PFLAG_DIRTY = 0x00200000; 1652 1653 /** 1654 * View flag indicating whether this view was invalidated by an opaque 1655 * invalidate request. 1656 * 1657 * @hide 1658 */ 1659 static final int PFLAG_DIRTY_OPAQUE = 0x00400000; 1660 1661 /** 1662 * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}. 1663 * 1664 * @hide 1665 */ 1666 static final int PFLAG_DIRTY_MASK = 0x00600000; 1667 1668 /** 1669 * Indicates whether the background is opaque. 1670 * 1671 * @hide 1672 */ 1673 static final int PFLAG_OPAQUE_BACKGROUND = 0x00800000; 1674 1675 /** 1676 * Indicates whether the scrollbars are opaque. 1677 * 1678 * @hide 1679 */ 1680 static final int PFLAG_OPAQUE_SCROLLBARS = 0x01000000; 1681 1682 /** 1683 * Indicates whether the view is opaque. 1684 * 1685 * @hide 1686 */ 1687 static final int PFLAG_OPAQUE_MASK = 0x01800000; 1688 1689 /** 1690 * Indicates a prepressed state; 1691 * the short time between ACTION_DOWN and recognizing 1692 * a 'real' press. Prepressed is used to recognize quick taps 1693 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1694 * 1695 * @hide 1696 */ 1697 private static final int PFLAG_PREPRESSED = 0x02000000; 1698 1699 /** 1700 * Indicates whether the view is temporarily detached. 1701 * 1702 * @hide 1703 */ 1704 static final int PFLAG_CANCEL_NEXT_UP_EVENT = 0x04000000; 1705 1706 /** 1707 * Indicates that we should awaken scroll bars once attached 1708 * 1709 * @hide 1710 */ 1711 private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1712 1713 /** 1714 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1715 * @hide 1716 */ 1717 private static final int PFLAG_HOVERED = 0x10000000; 1718 1719 /** 1720 * Indicates that pivotX or pivotY were explicitly set and we should not assume the center 1721 * for transform operations 1722 * 1723 * @hide 1724 */ 1725 private static final int PFLAG_PIVOT_EXPLICITLY_SET = 0x20000000; 1726 1727 /** {@hide} */ 1728 static final int PFLAG_ACTIVATED = 0x40000000; 1729 1730 /** 1731 * Indicates that this view was specifically invalidated, not just dirtied because some 1732 * child view was invalidated. The flag is used to determine when we need to recreate 1733 * a view's display list (as opposed to just returning a reference to its existing 1734 * display list). 1735 * 1736 * @hide 1737 */ 1738 static final int PFLAG_INVALIDATED = 0x80000000; 1739 1740 /** 1741 * Masks for mPrivateFlags2, as generated by dumpFlags(): 1742 * 1743 * -------|-------|-------|-------| 1744 * PFLAG2_TEXT_ALIGNMENT_FLAGS[0] 1745 * PFLAG2_TEXT_DIRECTION_FLAGS[0] 1746 * 1 PFLAG2_DRAG_CAN_ACCEPT 1747 * 1 PFLAG2_DRAG_HOVERED 1748 * 1 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT 1749 * 11 PFLAG2_TEXT_DIRECTION_MASK_SHIFT 1750 * 1 1 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT 1751 * 11 PFLAG2_LAYOUT_DIRECTION_MASK 1752 * 11 1 PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 1753 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL 1754 * 1 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT 1755 * 1 1 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT 1756 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED 1757 * 11 PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK 1758 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[1] 1759 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[2] 1760 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[3] 1761 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[4] 1762 * 1 1 PFLAG2_TEXT_DIRECTION_FLAGS[5] 1763 * 111 PFLAG2_TEXT_DIRECTION_MASK 1764 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED 1765 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT 1766 * 111 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK 1767 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[1] 1768 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[2] 1769 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[3] 1770 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[4] 1771 * 1 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[5] 1772 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[6] 1773 * 111 PFLAG2_TEXT_ALIGNMENT_MASK 1774 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED 1775 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT 1776 * 111 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK 1777 * 11 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK 1778 * 1 PFLAG2_HAS_TRANSIENT_STATE 1779 * 1 PFLAG2_ACCESSIBILITY_FOCUSED 1780 * 1 PFLAG2_ACCESSIBILITY_STATE_CHANGED 1781 * 1 PFLAG2_VIEW_QUICK_REJECTED 1782 * 1 PFLAG2_PADDING_RESOLVED 1783 * -------|-------|-------|-------| 1784 */ 1785 1786 /** 1787 * Indicates that this view has reported that it can accept the current drag's content. 1788 * Cleared when the drag operation concludes. 1789 * @hide 1790 */ 1791 static final int PFLAG2_DRAG_CAN_ACCEPT = 0x00000001; 1792 1793 /** 1794 * Indicates that this view is currently directly under the drag location in a 1795 * drag-and-drop operation involving content that it can accept. Cleared when 1796 * the drag exits the view, or when the drag operation concludes. 1797 * @hide 1798 */ 1799 static final int PFLAG2_DRAG_HOVERED = 0x00000002; 1800 1801 /** 1802 * Horizontal layout direction of this view is from Left to Right. 1803 * Use with {@link #setLayoutDirection}. 1804 */ 1805 public static final int LAYOUT_DIRECTION_LTR = 0; 1806 1807 /** 1808 * Horizontal layout direction of this view is from Right to Left. 1809 * Use with {@link #setLayoutDirection}. 1810 */ 1811 public static final int LAYOUT_DIRECTION_RTL = 1; 1812 1813 /** 1814 * Horizontal layout direction of this view is inherited from its parent. 1815 * Use with {@link #setLayoutDirection}. 1816 */ 1817 public static final int LAYOUT_DIRECTION_INHERIT = 2; 1818 1819 /** 1820 * Horizontal layout direction of this view is from deduced from the default language 1821 * script for the locale. Use with {@link #setLayoutDirection}. 1822 */ 1823 public static final int LAYOUT_DIRECTION_LOCALE = 3; 1824 1825 /** 1826 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1827 * @hide 1828 */ 1829 static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2; 1830 1831 /** 1832 * Mask for use with private flags indicating bits used for horizontal layout direction. 1833 * @hide 1834 */ 1835 static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1836 1837 /** 1838 * Indicates whether the view horizontal layout direction has been resolved and drawn to the 1839 * right-to-left direction. 1840 * @hide 1841 */ 1842 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1843 1844 /** 1845 * Indicates whether the view horizontal layout direction has been resolved. 1846 * @hide 1847 */ 1848 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1849 1850 /** 1851 * Mask for use with private flags indicating bits used for resolved horizontal layout direction. 1852 * @hide 1853 */ 1854 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C 1855 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1856 1857 /* 1858 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct 1859 * flag value. 1860 * @hide 1861 */ 1862 private static final int[] LAYOUT_DIRECTION_FLAGS = { 1863 LAYOUT_DIRECTION_LTR, 1864 LAYOUT_DIRECTION_RTL, 1865 LAYOUT_DIRECTION_INHERIT, 1866 LAYOUT_DIRECTION_LOCALE 1867 }; 1868 1869 /** 1870 * Default horizontal layout direction. 1871 */ 1872 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 1873 1874 /** 1875 * Default horizontal layout direction. 1876 * @hide 1877 */ 1878 static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR; 1879 1880 /** 1881 * Indicates that the view is tracking some sort of transient state 1882 * that the app should not need to be aware of, but that the framework 1883 * should take special care to preserve. 1884 * 1885 * @hide 1886 */ 1887 static final int PFLAG2_HAS_TRANSIENT_STATE = 0x1 << 22; 1888 1889 /** 1890 * Text direction is inherited thru {@link ViewGroup} 1891 */ 1892 public static final int TEXT_DIRECTION_INHERIT = 0; 1893 1894 /** 1895 * Text direction is using "first strong algorithm". The first strong directional character 1896 * determines the paragraph direction. If there is no strong directional character, the 1897 * paragraph direction is the view's resolved layout direction. 1898 */ 1899 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 1900 1901 /** 1902 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 1903 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 1904 * If there are neither, the paragraph direction is the view's resolved layout direction. 1905 */ 1906 public static final int TEXT_DIRECTION_ANY_RTL = 2; 1907 1908 /** 1909 * Text direction is forced to LTR. 1910 */ 1911 public static final int TEXT_DIRECTION_LTR = 3; 1912 1913 /** 1914 * Text direction is forced to RTL. 1915 */ 1916 public static final int TEXT_DIRECTION_RTL = 4; 1917 1918 /** 1919 * Text direction is coming from the system Locale. 1920 */ 1921 public static final int TEXT_DIRECTION_LOCALE = 5; 1922 1923 /** 1924 * Default text direction is inherited 1925 */ 1926 private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT; 1927 1928 /** 1929 * Default resolved text direction 1930 * @hide 1931 */ 1932 static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG; 1933 1934 /** 1935 * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED) 1936 * @hide 1937 */ 1938 static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6; 1939 1940 /** 1941 * Mask for use with private flags indicating bits used for text direction. 1942 * @hide 1943 */ 1944 static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007 1945 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 1946 1947 /** 1948 * Array of text direction flags for mapping attribute "textDirection" to correct 1949 * flag value. 1950 * @hide 1951 */ 1952 private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = { 1953 TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1954 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1955 TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1956 TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1957 TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1958 TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT 1959 }; 1960 1961 /** 1962 * Indicates whether the view text direction has been resolved. 1963 * @hide 1964 */ 1965 static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008 1966 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 1967 1968 /** 1969 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1970 * @hide 1971 */ 1972 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10; 1973 1974 /** 1975 * Mask for use with private flags indicating bits used for resolved text direction. 1976 * @hide 1977 */ 1978 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 1979 << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 1980 1981 /** 1982 * Indicates whether the view text direction has been resolved to the "first strong" heuristic. 1983 * @hide 1984 */ 1985 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT = 1986 TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 1987 1988 /* 1989 * Default text alignment. The text alignment of this View is inherited from its parent. 1990 * Use with {@link #setTextAlignment(int)} 1991 */ 1992 public static final int TEXT_ALIGNMENT_INHERIT = 0; 1993 1994 /** 1995 * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL, 1996 * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction. 1997 * 1998 * Use with {@link #setTextAlignment(int)} 1999 */ 2000 public static final int TEXT_ALIGNMENT_GRAVITY = 1; 2001 2002 /** 2003 * Align to the start of the paragraph, e.g. ALIGN_NORMAL. 2004 * 2005 * Use with {@link #setTextAlignment(int)} 2006 */ 2007 public static final int TEXT_ALIGNMENT_TEXT_START = 2; 2008 2009 /** 2010 * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE. 2011 * 2012 * Use with {@link #setTextAlignment(int)} 2013 */ 2014 public static final int TEXT_ALIGNMENT_TEXT_END = 3; 2015 2016 /** 2017 * Center the paragraph, e.g. ALIGN_CENTER. 2018 * 2019 * Use with {@link #setTextAlignment(int)} 2020 */ 2021 public static final int TEXT_ALIGNMENT_CENTER = 4; 2022 2023 /** 2024 * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved 2025 * layoutDirection is LTR, and ALIGN_RIGHT otherwise. 2026 * 2027 * Use with {@link #setTextAlignment(int)} 2028 */ 2029 public static final int TEXT_ALIGNMENT_VIEW_START = 5; 2030 2031 /** 2032 * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved 2033 * layoutDirection is LTR, and ALIGN_LEFT otherwise. 2034 * 2035 * Use with {@link #setTextAlignment(int)} 2036 */ 2037 public static final int TEXT_ALIGNMENT_VIEW_END = 6; 2038 2039 /** 2040 * Default text alignment is inherited 2041 */ 2042 private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2043 2044 /** 2045 * Default resolved text alignment 2046 * @hide 2047 */ 2048 static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2049 2050 /** 2051 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2052 * @hide 2053 */ 2054 static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13; 2055 2056 /** 2057 * Mask for use with private flags indicating bits used for text alignment. 2058 * @hide 2059 */ 2060 static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2061 2062 /** 2063 * Array of text direction flags for mapping attribute "textAlignment" to correct 2064 * flag value. 2065 * @hide 2066 */ 2067 private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = { 2068 TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2069 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2070 TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2071 TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2072 TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2073 TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2074 TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 2075 }; 2076 2077 /** 2078 * Indicates whether the view text alignment has been resolved. 2079 * @hide 2080 */ 2081 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2082 2083 /** 2084 * Bit shift to get the resolved text alignment. 2085 * @hide 2086 */ 2087 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17; 2088 2089 /** 2090 * Mask for use with private flags indicating bits used for text alignment. 2091 * @hide 2092 */ 2093 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 2094 << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2095 2096 /** 2097 * Indicates whether if the view text alignment has been resolved to gravity 2098 */ 2099 private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT = 2100 TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2101 2102 // Accessiblity constants for mPrivateFlags2 2103 2104 /** 2105 * Shift for the bits in {@link #mPrivateFlags2} related to the 2106 * "importantForAccessibility" attribute. 2107 */ 2108 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20; 2109 2110 /** 2111 * Automatically determine whether a view is important for accessibility. 2112 */ 2113 public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000; 2114 2115 /** 2116 * The view is important for accessibility. 2117 */ 2118 public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001; 2119 2120 /** 2121 * The view is not important for accessibility. 2122 */ 2123 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002; 2124 2125 /** 2126 * The default whether the view is important for accessibility. 2127 */ 2128 static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO; 2129 2130 /** 2131 * Mask for obtainig the bits which specify how to determine 2132 * whether a view is important for accessibility. 2133 */ 2134 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO 2135 | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO) 2136 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2137 2138 /** 2139 * Flag indicating whether a view has accessibility focus. 2140 */ 2141 static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000; 2142 2143 /** 2144 * Flag whether the accessibility state of the subtree rooted at this view changed. 2145 */ 2146 static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000; 2147 2148 /** 2149 * Flag indicating whether a view failed the quickReject() check in draw(). This condition 2150 * is used to check whether later changes to the view's transform should invalidate the 2151 * view to force the quickReject test to run again. 2152 */ 2153 static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000; 2154 2155 /** 2156 * Flag indicating that start/end padding has been resolved into left/right padding 2157 * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()} 2158 * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved 2159 * during measurement. In some special cases this is required such as when an adapter-based 2160 * view measures prospective children without attaching them to a window. 2161 */ 2162 static final int PFLAG2_PADDING_RESOLVED = 0x20000000; 2163 2164 /** 2165 * Flag indicating that the start/end drawables has been resolved into left/right ones. 2166 */ 2167 static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000; 2168 2169 /** 2170 * Group of bits indicating that RTL properties resolution is done. 2171 */ 2172 static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED | 2173 PFLAG2_TEXT_DIRECTION_RESOLVED | 2174 PFLAG2_TEXT_ALIGNMENT_RESOLVED | 2175 PFLAG2_PADDING_RESOLVED | 2176 PFLAG2_DRAWABLE_RESOLVED; 2177 2178 // There are a couple of flags left in mPrivateFlags2 2179 2180 /* End of masks for mPrivateFlags2 */ 2181 2182 /* Masks for mPrivateFlags3 */ 2183 2184 /** 2185 * Flag indicating that view has a transform animation set on it. This is used to track whether 2186 * an animation is cleared between successive frames, in order to tell the associated 2187 * DisplayList to clear its animation matrix. 2188 */ 2189 static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1; 2190 2191 /** 2192 * Flag indicating that view has an alpha animation set on it. This is used to track whether an 2193 * animation is cleared between successive frames, in order to tell the associated 2194 * DisplayList to restore its alpha value. 2195 */ 2196 static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2; 2197 2198 2199 /* End of masks for mPrivateFlags3 */ 2200 2201 static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED; 2202 2203 /** 2204 * Always allow a user to over-scroll this view, provided it is a 2205 * view that can scroll. 2206 * 2207 * @see #getOverScrollMode() 2208 * @see #setOverScrollMode(int) 2209 */ 2210 public static final int OVER_SCROLL_ALWAYS = 0; 2211 2212 /** 2213 * Allow a user to over-scroll this view only if the content is large 2214 * enough to meaningfully scroll, provided it is a view that can scroll. 2215 * 2216 * @see #getOverScrollMode() 2217 * @see #setOverScrollMode(int) 2218 */ 2219 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 2220 2221 /** 2222 * Never allow a user to over-scroll this view. 2223 * 2224 * @see #getOverScrollMode() 2225 * @see #setOverScrollMode(int) 2226 */ 2227 public static final int OVER_SCROLL_NEVER = 2; 2228 2229 /** 2230 * Special constant for {@link #setSystemUiVisibility(int)}: View has 2231 * requested the system UI (status bar) to be visible (the default). 2232 * 2233 * @see #setSystemUiVisibility(int) 2234 */ 2235 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 2236 2237 /** 2238 * Flag for {@link #setSystemUiVisibility(int)}: View has requested the 2239 * system UI to enter an unobtrusive "low profile" mode. 2240 * 2241 * <p>This is for use in games, book readers, video players, or any other 2242 * "immersive" application where the usual system chrome is deemed too distracting. 2243 * 2244 * <p>In low profile mode, the status bar and/or navigation icons may dim. 2245 * 2246 * @see #setSystemUiVisibility(int) 2247 */ 2248 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 2249 2250 /** 2251 * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the 2252 * system navigation be temporarily hidden. 2253 * 2254 * <p>This is an even less obtrusive state than that called for by 2255 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 2256 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 2257 * those to disappear. This is useful (in conjunction with the 2258 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 2259 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 2260 * window flags) for displaying content using every last pixel on the display. 2261 * 2262 * <p>There is a limitation: because navigation controls are so important, the least user 2263 * interaction will cause them to reappear immediately. When this happens, both 2264 * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically, 2265 * so that both elements reappear at the same time. 2266 * 2267 * @see #setSystemUiVisibility(int) 2268 */ 2269 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 2270 2271 /** 2272 * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go 2273 * into the normal fullscreen mode so that its content can take over the screen 2274 * while still allowing the user to interact with the application. 2275 * 2276 * <p>This has the same visual effect as 2277 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN 2278 * WindowManager.LayoutParams.FLAG_FULLSCREEN}, 2279 * meaning that non-critical screen decorations (such as the status bar) will be 2280 * hidden while the user is in the View's window, focusing the experience on 2281 * that content. Unlike the window flag, if you are using ActionBar in 2282 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2283 * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also 2284 * hide the action bar. 2285 * 2286 * <p>This approach to going fullscreen is best used over the window flag when 2287 * it is a transient state -- that is, the application does this at certain 2288 * points in its user interaction where it wants to allow the user to focus 2289 * on content, but not as a continuous state. For situations where the application 2290 * would like to simply stay full screen the entire time (such as a game that 2291 * wants to take over the screen), the 2292 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag} 2293 * is usually a better approach. The state set here will be removed by the system 2294 * in various situations (such as the user moving to another application) like 2295 * the other system UI states. 2296 * 2297 * <p>When using this flag, the application should provide some easy facility 2298 * for the user to go out of it. A common example would be in an e-book 2299 * reader, where tapping on the screen brings back whatever screen and UI 2300 * decorations that had been hidden while the user was immersed in reading 2301 * the book. 2302 * 2303 * @see #setSystemUiVisibility(int) 2304 */ 2305 public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004; 2306 2307 /** 2308 * Flag for {@link #setSystemUiVisibility(int)}: When using other layout 2309 * flags, we would like a stable view of the content insets given to 2310 * {@link #fitSystemWindows(Rect)}. This means that the insets seen there 2311 * will always represent the worst case that the application can expect 2312 * as a continuous state. In the stock Android UI this is the space for 2313 * the system bar, nav bar, and status bar, but not more transient elements 2314 * such as an input method. 2315 * 2316 * The stable layout your UI sees is based on the system UI modes you can 2317 * switch to. That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 2318 * then you will get a stable layout for changes of the 2319 * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify 2320 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and 2321 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition 2322 * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} 2323 * with a stable layout. (Note that you should avoid using 2324 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.) 2325 * 2326 * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN} 2327 * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}), 2328 * then a hidden status bar will be considered a "stable" state for purposes 2329 * here. This allows your UI to continually hide the status bar, while still 2330 * using the system UI flags to hide the action bar while still retaining 2331 * a stable layout. Note that changing the window fullscreen flag will never 2332 * provide a stable layout for a clean transition. 2333 * 2334 * <p>If you are using ActionBar in 2335 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2336 * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the 2337 * insets it adds to those given to the application. 2338 */ 2339 public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100; 2340 2341 /** 2342 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2343 * to be layed out as if it has requested 2344 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't. This 2345 * allows it to avoid artifacts when switching in and out of that mode, at 2346 * the expense that some of its user interface may be covered by screen 2347 * decorations when they are shown. You can perform layout of your inner 2348 * UI elements to account for the navigation system UI through the 2349 * {@link #fitSystemWindows(Rect)} method. 2350 */ 2351 public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200; 2352 2353 /** 2354 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2355 * to be layed out as if it has requested 2356 * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't. This 2357 * allows it to avoid artifacts when switching in and out of that mode, at 2358 * the expense that some of its user interface may be covered by screen 2359 * decorations when they are shown. You can perform layout of your inner 2360 * UI elements to account for non-fullscreen system UI through the 2361 * {@link #fitSystemWindows(Rect)} method. 2362 */ 2363 public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400; 2364 2365 /** 2366 * Flag for {@link #setSystemUiVisibility(int)}: View would like to receive touch events 2367 * when hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the 2368 * navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} instead of having the system 2369 * clear these flags upon interaction. The system may compensate by temporarily overlaying 2370 * transparent system ui while also delivering the event. 2371 */ 2372 public static final int SYSTEM_UI_FLAG_ALLOW_OVERLAY = 0x00000800; 2373 2374 /** 2375 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 2376 */ 2377 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 2378 2379 /** 2380 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 2381 */ 2382 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 2383 2384 /** 2385 * @hide 2386 * 2387 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2388 * out of the public fields to keep the undefined bits out of the developer's way. 2389 * 2390 * Flag to make the status bar not expandable. Unless you also 2391 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 2392 */ 2393 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 2394 2395 /** 2396 * @hide 2397 * 2398 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2399 * out of the public fields to keep the undefined bits out of the developer's way. 2400 * 2401 * Flag to hide notification icons and scrolling ticker text. 2402 */ 2403 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 2404 2405 /** 2406 * @hide 2407 * 2408 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2409 * out of the public fields to keep the undefined bits out of the developer's way. 2410 * 2411 * Flag to disable incoming notification alerts. This will not block 2412 * icons, but it will block sound, vibrating and other visual or aural notifications. 2413 */ 2414 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 2415 2416 /** 2417 * @hide 2418 * 2419 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2420 * out of the public fields to keep the undefined bits out of the developer's way. 2421 * 2422 * Flag to hide only the scrolling ticker. Note that 2423 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 2424 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 2425 */ 2426 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 2427 2428 /** 2429 * @hide 2430 * 2431 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2432 * out of the public fields to keep the undefined bits out of the developer's way. 2433 * 2434 * Flag to hide the center system info area. 2435 */ 2436 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 2437 2438 /** 2439 * @hide 2440 * 2441 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2442 * out of the public fields to keep the undefined bits out of the developer's way. 2443 * 2444 * Flag to hide only the home button. Don't use this 2445 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2446 */ 2447 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 2448 2449 /** 2450 * @hide 2451 * 2452 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2453 * out of the public fields to keep the undefined bits out of the developer's way. 2454 * 2455 * Flag to hide only the back button. Don't use this 2456 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2457 */ 2458 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 2459 2460 /** 2461 * @hide 2462 * 2463 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2464 * out of the public fields to keep the undefined bits out of the developer's way. 2465 * 2466 * Flag to hide only the clock. You might use this if your activity has 2467 * its own clock making the status bar's clock redundant. 2468 */ 2469 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 2470 2471 /** 2472 * @hide 2473 * 2474 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2475 * out of the public fields to keep the undefined bits out of the developer's way. 2476 * 2477 * Flag to hide only the recent apps button. Don't use this 2478 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2479 */ 2480 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 2481 2482 /** 2483 * @hide 2484 * 2485 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2486 * out of the public fields to keep the undefined bits out of the developer's way. 2487 * 2488 * Flag to disable the global search gesture. Don't use this 2489 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2490 */ 2491 public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000; 2492 2493 /** 2494 * @hide 2495 * 2496 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2497 * out of the public fields to keep the undefined bits out of the developer's way. 2498 * 2499 * Flag to specify that the status bar should temporarily overlay underlying content 2500 * that is otherwise assuming the status bar is hidden. The status bar may 2501 * have some degree of transparency while in this temporary overlay mode. 2502 */ 2503 public static final int STATUS_BAR_OVERLAY = 0x04000000; 2504 2505 /** 2506 * @hide 2507 * 2508 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2509 * out of the public fields to keep the undefined bits out of the developer's way. 2510 * 2511 * Flag to specify that the navigation bar should temporarily overlay underlying content 2512 * that is otherwise assuming the navigation bar is hidden. The navigation bar mayu 2513 * have some degree of transparency while in this temporary overlay mode. 2514 */ 2515 public static final int NAVIGATION_BAR_OVERLAY = 0x08000000; 2516 2517 /** 2518 * @hide 2519 */ 2520 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF; 2521 2522 /** 2523 * These are the system UI flags that can be cleared by events outside 2524 * of an application. Currently this is just the ability to tap on the 2525 * screen while hiding the navigation bar to have it return. 2526 * @hide 2527 */ 2528 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 2529 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 2530 | SYSTEM_UI_FLAG_FULLSCREEN; 2531 2532 /** 2533 * Flags that can impact the layout in relation to system UI. 2534 */ 2535 public static final int SYSTEM_UI_LAYOUT_FLAGS = 2536 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 2537 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 2538 2539 /** 2540 * Find views that render the specified text. 2541 * 2542 * @see #findViewsWithText(ArrayList, CharSequence, int) 2543 */ 2544 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 2545 2546 /** 2547 * Find find views that contain the specified content description. 2548 * 2549 * @see #findViewsWithText(ArrayList, CharSequence, int) 2550 */ 2551 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 2552 2553 /** 2554 * Find views that contain {@link AccessibilityNodeProvider}. Such 2555 * a View is a root of virtual view hierarchy and may contain the searched 2556 * text. If this flag is set Views with providers are automatically 2557 * added and it is a responsibility of the client to call the APIs of 2558 * the provider to determine whether the virtual tree rooted at this View 2559 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 2560 * represeting the virtual views with this text. 2561 * 2562 * @see #findViewsWithText(ArrayList, CharSequence, int) 2563 * 2564 * @hide 2565 */ 2566 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 2567 2568 /** 2569 * The undefined cursor position. 2570 * 2571 * @hide 2572 */ 2573 public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1; 2574 2575 /** 2576 * Indicates that the screen has changed state and is now off. 2577 * 2578 * @see #onScreenStateChanged(int) 2579 */ 2580 public static final int SCREEN_STATE_OFF = 0x0; 2581 2582 /** 2583 * Indicates that the screen has changed state and is now on. 2584 * 2585 * @see #onScreenStateChanged(int) 2586 */ 2587 public static final int SCREEN_STATE_ON = 0x1; 2588 2589 /** 2590 * Controls the over-scroll mode for this view. 2591 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 2592 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 2593 * and {@link #OVER_SCROLL_NEVER}. 2594 */ 2595 private int mOverScrollMode; 2596 2597 /** 2598 * The parent this view is attached to. 2599 * {@hide} 2600 * 2601 * @see #getParent() 2602 */ 2603 protected ViewParent mParent; 2604 2605 /** 2606 * {@hide} 2607 */ 2608 AttachInfo mAttachInfo; 2609 2610 /** 2611 * {@hide} 2612 */ 2613 @ViewDebug.ExportedProperty(flagMapping = { 2614 @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT, 2615 name = "FORCE_LAYOUT"), 2616 @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED, 2617 name = "LAYOUT_REQUIRED"), 2618 @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID, 2619 name = "DRAWING_CACHE_INVALID", outputIf = false), 2620 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true), 2621 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false), 2622 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 2623 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY") 2624 }) 2625 int mPrivateFlags; 2626 int mPrivateFlags2; 2627 int mPrivateFlags3; 2628 2629 /** 2630 * This view's request for the visibility of the status bar. 2631 * @hide 2632 */ 2633 @ViewDebug.ExportedProperty(flagMapping = { 2634 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 2635 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 2636 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 2637 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2638 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2639 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 2640 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 2641 equals = SYSTEM_UI_FLAG_VISIBLE, 2642 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 2643 }) 2644 int mSystemUiVisibility; 2645 2646 /** 2647 * Reference count for transient state. 2648 * @see #setHasTransientState(boolean) 2649 */ 2650 int mTransientStateCount = 0; 2651 2652 /** 2653 * Count of how many windows this view has been attached to. 2654 */ 2655 int mWindowAttachCount; 2656 2657 /** 2658 * The layout parameters associated with this view and used by the parent 2659 * {@link android.view.ViewGroup} to determine how this view should be 2660 * laid out. 2661 * {@hide} 2662 */ 2663 protected ViewGroup.LayoutParams mLayoutParams; 2664 2665 /** 2666 * The view flags hold various views states. 2667 * {@hide} 2668 */ 2669 @ViewDebug.ExportedProperty 2670 int mViewFlags; 2671 2672 static class TransformationInfo { 2673 /** 2674 * The transform matrix for the View. This transform is calculated internally 2675 * based on the rotation, scaleX, and scaleY properties. The identity matrix 2676 * is used by default. Do *not* use this variable directly; instead call 2677 * getMatrix(), which will automatically recalculate the matrix if necessary 2678 * to get the correct matrix based on the latest rotation and scale properties. 2679 */ 2680 private final Matrix mMatrix = new Matrix(); 2681 2682 /** 2683 * The transform matrix for the View. This transform is calculated internally 2684 * based on the rotation, scaleX, and scaleY properties. The identity matrix 2685 * is used by default. Do *not* use this variable directly; instead call 2686 * getInverseMatrix(), which will automatically recalculate the matrix if necessary 2687 * to get the correct matrix based on the latest rotation and scale properties. 2688 */ 2689 private Matrix mInverseMatrix; 2690 2691 /** 2692 * An internal variable that tracks whether we need to recalculate the 2693 * transform matrix, based on whether the rotation or scaleX/Y properties 2694 * have changed since the matrix was last calculated. 2695 */ 2696 boolean mMatrixDirty = false; 2697 2698 /** 2699 * An internal variable that tracks whether we need to recalculate the 2700 * transform matrix, based on whether the rotation or scaleX/Y properties 2701 * have changed since the matrix was last calculated. 2702 */ 2703 private boolean mInverseMatrixDirty = true; 2704 2705 /** 2706 * A variable that tracks whether we need to recalculate the 2707 * transform matrix, based on whether the rotation or scaleX/Y properties 2708 * have changed since the matrix was last calculated. This variable 2709 * is only valid after a call to updateMatrix() or to a function that 2710 * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix(). 2711 */ 2712 private boolean mMatrixIsIdentity = true; 2713 2714 /** 2715 * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set. 2716 */ 2717 private Camera mCamera = null; 2718 2719 /** 2720 * This matrix is used when computing the matrix for 3D rotations. 2721 */ 2722 private Matrix matrix3D = null; 2723 2724 /** 2725 * These prev values are used to recalculate a centered pivot point when necessary. The 2726 * pivot point is only used in matrix operations (when rotation, scale, or translation are 2727 * set), so thes values are only used then as well. 2728 */ 2729 private int mPrevWidth = -1; 2730 private int mPrevHeight = -1; 2731 2732 /** 2733 * The degrees rotation around the vertical axis through the pivot point. 2734 */ 2735 @ViewDebug.ExportedProperty 2736 float mRotationY = 0f; 2737 2738 /** 2739 * The degrees rotation around the horizontal axis through the pivot point. 2740 */ 2741 @ViewDebug.ExportedProperty 2742 float mRotationX = 0f; 2743 2744 /** 2745 * The degrees rotation around the pivot point. 2746 */ 2747 @ViewDebug.ExportedProperty 2748 float mRotation = 0f; 2749 2750 /** 2751 * The amount of translation of the object away from its left property (post-layout). 2752 */ 2753 @ViewDebug.ExportedProperty 2754 float mTranslationX = 0f; 2755 2756 /** 2757 * The amount of translation of the object away from its top property (post-layout). 2758 */ 2759 @ViewDebug.ExportedProperty 2760 float mTranslationY = 0f; 2761 2762 /** 2763 * The amount of scale in the x direction around the pivot point. A 2764 * value of 1 means no scaling is applied. 2765 */ 2766 @ViewDebug.ExportedProperty 2767 float mScaleX = 1f; 2768 2769 /** 2770 * The amount of scale in the y direction around the pivot point. A 2771 * value of 1 means no scaling is applied. 2772 */ 2773 @ViewDebug.ExportedProperty 2774 float mScaleY = 1f; 2775 2776 /** 2777 * The x location of the point around which the view is rotated and scaled. 2778 */ 2779 @ViewDebug.ExportedProperty 2780 float mPivotX = 0f; 2781 2782 /** 2783 * The y location of the point around which the view is rotated and scaled. 2784 */ 2785 @ViewDebug.ExportedProperty 2786 float mPivotY = 0f; 2787 2788 /** 2789 * The opacity of the View. This is a value from 0 to 1, where 0 means 2790 * completely transparent and 1 means completely opaque. 2791 */ 2792 @ViewDebug.ExportedProperty 2793 float mAlpha = 1f; 2794 } 2795 2796 TransformationInfo mTransformationInfo; 2797 2798 /** 2799 * Current clip bounds. to which all drawing of this view are constrained. 2800 */ 2801 private Rect mClipBounds = null; 2802 2803 private boolean mLastIsOpaque; 2804 2805 /** 2806 * Convenience value to check for float values that are close enough to zero to be considered 2807 * zero. 2808 */ 2809 private static final float NONZERO_EPSILON = .001f; 2810 2811 /** 2812 * The distance in pixels from the left edge of this view's parent 2813 * to the left edge of this view. 2814 * {@hide} 2815 */ 2816 @ViewDebug.ExportedProperty(category = "layout") 2817 protected int mLeft; 2818 /** 2819 * The distance in pixels from the left edge of this view's parent 2820 * to the right edge of this view. 2821 * {@hide} 2822 */ 2823 @ViewDebug.ExportedProperty(category = "layout") 2824 protected int mRight; 2825 /** 2826 * The distance in pixels from the top edge of this view's parent 2827 * to the top edge of this view. 2828 * {@hide} 2829 */ 2830 @ViewDebug.ExportedProperty(category = "layout") 2831 protected int mTop; 2832 /** 2833 * The distance in pixels from the top edge of this view's parent 2834 * to the bottom edge of this view. 2835 * {@hide} 2836 */ 2837 @ViewDebug.ExportedProperty(category = "layout") 2838 protected int mBottom; 2839 2840 /** 2841 * The offset, in pixels, by which the content of this view is scrolled 2842 * horizontally. 2843 * {@hide} 2844 */ 2845 @ViewDebug.ExportedProperty(category = "scrolling") 2846 protected int mScrollX; 2847 /** 2848 * The offset, in pixels, by which the content of this view is scrolled 2849 * vertically. 2850 * {@hide} 2851 */ 2852 @ViewDebug.ExportedProperty(category = "scrolling") 2853 protected int mScrollY; 2854 2855 /** 2856 * The left padding in pixels, that is the distance in pixels between the 2857 * left edge of this view and the left edge of its content. 2858 * {@hide} 2859 */ 2860 @ViewDebug.ExportedProperty(category = "padding") 2861 protected int mPaddingLeft = 0; 2862 /** 2863 * The right padding in pixels, that is the distance in pixels between the 2864 * right edge of this view and the right edge of its content. 2865 * {@hide} 2866 */ 2867 @ViewDebug.ExportedProperty(category = "padding") 2868 protected int mPaddingRight = 0; 2869 /** 2870 * The top padding in pixels, that is the distance in pixels between the 2871 * top edge of this view and the top edge of its content. 2872 * {@hide} 2873 */ 2874 @ViewDebug.ExportedProperty(category = "padding") 2875 protected int mPaddingTop; 2876 /** 2877 * The bottom padding in pixels, that is the distance in pixels between the 2878 * bottom edge of this view and the bottom edge of its content. 2879 * {@hide} 2880 */ 2881 @ViewDebug.ExportedProperty(category = "padding") 2882 protected int mPaddingBottom; 2883 2884 /** 2885 * The layout insets in pixels, that is the distance in pixels between the 2886 * visible edges of this view its bounds. 2887 */ 2888 private Insets mLayoutInsets; 2889 2890 /** 2891 * Briefly describes the view and is primarily used for accessibility support. 2892 */ 2893 private CharSequence mContentDescription; 2894 2895 /** 2896 * Specifies the id of a view for which this view serves as a label for 2897 * accessibility purposes. 2898 */ 2899 private int mLabelForId = View.NO_ID; 2900 2901 /** 2902 * Predicate for matching labeled view id with its label for 2903 * accessibility purposes. 2904 */ 2905 private MatchLabelForPredicate mMatchLabelForPredicate; 2906 2907 /** 2908 * Predicate for matching a view by its id. 2909 */ 2910 private MatchIdPredicate mMatchIdPredicate; 2911 2912 /** 2913 * Cache the paddingRight set by the user to append to the scrollbar's size. 2914 * 2915 * @hide 2916 */ 2917 @ViewDebug.ExportedProperty(category = "padding") 2918 protected int mUserPaddingRight; 2919 2920 /** 2921 * Cache the paddingBottom set by the user to append to the scrollbar's size. 2922 * 2923 * @hide 2924 */ 2925 @ViewDebug.ExportedProperty(category = "padding") 2926 protected int mUserPaddingBottom; 2927 2928 /** 2929 * Cache the paddingLeft set by the user to append to the scrollbar's size. 2930 * 2931 * @hide 2932 */ 2933 @ViewDebug.ExportedProperty(category = "padding") 2934 protected int mUserPaddingLeft; 2935 2936 /** 2937 * Cache the paddingStart set by the user to append to the scrollbar's size. 2938 * 2939 */ 2940 @ViewDebug.ExportedProperty(category = "padding") 2941 int mUserPaddingStart; 2942 2943 /** 2944 * Cache the paddingEnd set by the user to append to the scrollbar's size. 2945 * 2946 */ 2947 @ViewDebug.ExportedProperty(category = "padding") 2948 int mUserPaddingEnd; 2949 2950 /** 2951 * Cache initial left padding. 2952 * 2953 * @hide 2954 */ 2955 int mUserPaddingLeftInitial; 2956 2957 /** 2958 * Cache initial right padding. 2959 * 2960 * @hide 2961 */ 2962 int mUserPaddingRightInitial; 2963 2964 /** 2965 * Default undefined padding 2966 */ 2967 private static final int UNDEFINED_PADDING = Integer.MIN_VALUE; 2968 2969 /** 2970 * @hide 2971 */ 2972 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 2973 /** 2974 * @hide 2975 */ 2976 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 2977 2978 @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_") 2979 private Drawable mBackground; 2980 2981 private int mBackgroundResource; 2982 private boolean mBackgroundSizeChanged; 2983 2984 static class ListenerInfo { 2985 /** 2986 * Listener used to dispatch focus change events. 2987 * This field should be made private, so it is hidden from the SDK. 2988 * {@hide} 2989 */ 2990 protected OnFocusChangeListener mOnFocusChangeListener; 2991 2992 /** 2993 * Listeners for layout change events. 2994 */ 2995 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 2996 2997 /** 2998 * Listeners for attach events. 2999 */ 3000 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 3001 3002 /** 3003 * Listener used to dispatch click events. 3004 * This field should be made private, so it is hidden from the SDK. 3005 * {@hide} 3006 */ 3007 public OnClickListener mOnClickListener; 3008 3009 /** 3010 * Listener used to dispatch long click events. 3011 * This field should be made private, so it is hidden from the SDK. 3012 * {@hide} 3013 */ 3014 protected OnLongClickListener mOnLongClickListener; 3015 3016 /** 3017 * Listener used to build the context menu. 3018 * This field should be made private, so it is hidden from the SDK. 3019 * {@hide} 3020 */ 3021 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 3022 3023 private OnKeyListener mOnKeyListener; 3024 3025 private OnTouchListener mOnTouchListener; 3026 3027 private OnHoverListener mOnHoverListener; 3028 3029 private OnGenericMotionListener mOnGenericMotionListener; 3030 3031 private OnDragListener mOnDragListener; 3032 3033 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 3034 } 3035 3036 ListenerInfo mListenerInfo; 3037 3038 /** 3039 * The application environment this view lives in. 3040 * This field should be made private, so it is hidden from the SDK. 3041 * {@hide} 3042 */ 3043 protected Context mContext; 3044 3045 private final Resources mResources; 3046 3047 private ScrollabilityCache mScrollCache; 3048 3049 private int[] mDrawableState = null; 3050 3051 /** 3052 * Set to true when drawing cache is enabled and cannot be created. 3053 * 3054 * @hide 3055 */ 3056 public boolean mCachingFailed; 3057 3058 private Bitmap mDrawingCache; 3059 private Bitmap mUnscaledDrawingCache; 3060 private HardwareLayer mHardwareLayer; 3061 DisplayList mDisplayList; 3062 3063 /** 3064 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 3065 * the user may specify which view to go to next. 3066 */ 3067 private int mNextFocusLeftId = View.NO_ID; 3068 3069 /** 3070 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 3071 * the user may specify which view to go to next. 3072 */ 3073 private int mNextFocusRightId = View.NO_ID; 3074 3075 /** 3076 * When this view has focus and the next focus is {@link #FOCUS_UP}, 3077 * the user may specify which view to go to next. 3078 */ 3079 private int mNextFocusUpId = View.NO_ID; 3080 3081 /** 3082 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 3083 * the user may specify which view to go to next. 3084 */ 3085 private int mNextFocusDownId = View.NO_ID; 3086 3087 /** 3088 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 3089 * the user may specify which view to go to next. 3090 */ 3091 int mNextFocusForwardId = View.NO_ID; 3092 3093 private CheckForLongPress mPendingCheckForLongPress; 3094 private CheckForTap mPendingCheckForTap = null; 3095 private PerformClick mPerformClick; 3096 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 3097 3098 private UnsetPressedState mUnsetPressedState; 3099 3100 /** 3101 * Whether the long press's action has been invoked. The tap's action is invoked on the 3102 * up event while a long press is invoked as soon as the long press duration is reached, so 3103 * a long press could be performed before the tap is checked, in which case the tap's action 3104 * should not be invoked. 3105 */ 3106 private boolean mHasPerformedLongPress; 3107 3108 /** 3109 * The minimum height of the view. We'll try our best to have the height 3110 * of this view to at least this amount. 3111 */ 3112 @ViewDebug.ExportedProperty(category = "measurement") 3113 private int mMinHeight; 3114 3115 /** 3116 * The minimum width of the view. We'll try our best to have the width 3117 * of this view to at least this amount. 3118 */ 3119 @ViewDebug.ExportedProperty(category = "measurement") 3120 private int mMinWidth; 3121 3122 /** 3123 * The delegate to handle touch events that are physically in this view 3124 * but should be handled by another view. 3125 */ 3126 private TouchDelegate mTouchDelegate = null; 3127 3128 /** 3129 * Solid color to use as a background when creating the drawing cache. Enables 3130 * the cache to use 16 bit bitmaps instead of 32 bit. 3131 */ 3132 private int mDrawingCacheBackgroundColor = 0; 3133 3134 /** 3135 * Special tree observer used when mAttachInfo is null. 3136 */ 3137 private ViewTreeObserver mFloatingTreeObserver; 3138 3139 /** 3140 * Cache the touch slop from the context that created the view. 3141 */ 3142 private int mTouchSlop; 3143 3144 /** 3145 * Object that handles automatic animation of view properties. 3146 */ 3147 private ViewPropertyAnimator mAnimator = null; 3148 3149 /** 3150 * Flag indicating that a drag can cross window boundaries. When 3151 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 3152 * with this flag set, all visible applications will be able to participate 3153 * in the drag operation and receive the dragged content. 3154 * 3155 * @hide 3156 */ 3157 public static final int DRAG_FLAG_GLOBAL = 1; 3158 3159 /** 3160 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 3161 */ 3162 private float mVerticalScrollFactor; 3163 3164 /** 3165 * Position of the vertical scroll bar. 3166 */ 3167 private int mVerticalScrollbarPosition; 3168 3169 /** 3170 * Position the scroll bar at the default position as determined by the system. 3171 */ 3172 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 3173 3174 /** 3175 * Position the scroll bar along the left edge. 3176 */ 3177 public static final int SCROLLBAR_POSITION_LEFT = 1; 3178 3179 /** 3180 * Position the scroll bar along the right edge. 3181 */ 3182 public static final int SCROLLBAR_POSITION_RIGHT = 2; 3183 3184 /** 3185 * Indicates that the view does not have a layer. 3186 * 3187 * @see #getLayerType() 3188 * @see #setLayerType(int, android.graphics.Paint) 3189 * @see #LAYER_TYPE_SOFTWARE 3190 * @see #LAYER_TYPE_HARDWARE 3191 */ 3192 public static final int LAYER_TYPE_NONE = 0; 3193 3194 /** 3195 * <p>Indicates that the view has a software layer. A software layer is backed 3196 * by a bitmap and causes the view to be rendered using Android's software 3197 * rendering pipeline, even if hardware acceleration is enabled.</p> 3198 * 3199 * <p>Software layers have various usages:</p> 3200 * <p>When the application is not using hardware acceleration, a software layer 3201 * is useful to apply a specific color filter and/or blending mode and/or 3202 * translucency to a view and all its children.</p> 3203 * <p>When the application is using hardware acceleration, a software layer 3204 * is useful to render drawing primitives not supported by the hardware 3205 * accelerated pipeline. It can also be used to cache a complex view tree 3206 * into a texture and reduce the complexity of drawing operations. For instance, 3207 * when animating a complex view tree with a translation, a software layer can 3208 * be used to render the view tree only once.</p> 3209 * <p>Software layers should be avoided when the affected view tree updates 3210 * often. Every update will require to re-render the software layer, which can 3211 * potentially be slow (particularly when hardware acceleration is turned on 3212 * since the layer will have to be uploaded into a hardware texture after every 3213 * update.)</p> 3214 * 3215 * @see #getLayerType() 3216 * @see #setLayerType(int, android.graphics.Paint) 3217 * @see #LAYER_TYPE_NONE 3218 * @see #LAYER_TYPE_HARDWARE 3219 */ 3220 public static final int LAYER_TYPE_SOFTWARE = 1; 3221 3222 /** 3223 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 3224 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 3225 * OpenGL hardware) and causes the view to be rendered using Android's hardware 3226 * rendering pipeline, but only if hardware acceleration is turned on for the 3227 * view hierarchy. When hardware acceleration is turned off, hardware layers 3228 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 3229 * 3230 * <p>A hardware layer is useful to apply a specific color filter and/or 3231 * blending mode and/or translucency to a view and all its children.</p> 3232 * <p>A hardware layer can be used to cache a complex view tree into a 3233 * texture and reduce the complexity of drawing operations. For instance, 3234 * when animating a complex view tree with a translation, a hardware layer can 3235 * be used to render the view tree only once.</p> 3236 * <p>A hardware layer can also be used to increase the rendering quality when 3237 * rotation transformations are applied on a view. It can also be used to 3238 * prevent potential clipping issues when applying 3D transforms on a view.</p> 3239 * 3240 * @see #getLayerType() 3241 * @see #setLayerType(int, android.graphics.Paint) 3242 * @see #LAYER_TYPE_NONE 3243 * @see #LAYER_TYPE_SOFTWARE 3244 */ 3245 public static final int LAYER_TYPE_HARDWARE = 2; 3246 3247 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 3248 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 3249 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 3250 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 3251 }) 3252 int mLayerType = LAYER_TYPE_NONE; 3253 Paint mLayerPaint; 3254 Rect mLocalDirtyRect; 3255 3256 /** 3257 * Set to true when the view is sending hover accessibility events because it 3258 * is the innermost hovered view. 3259 */ 3260 private boolean mSendingHoverAccessibilityEvents; 3261 3262 /** 3263 * Delegate for injecting accessibility functionality. 3264 */ 3265 AccessibilityDelegate mAccessibilityDelegate; 3266 3267 /** 3268 * The view's overlay layer. Developers get a reference to the overlay via getOverlay() 3269 * and add/remove objects to/from the overlay directly through the Overlay methods. 3270 */ 3271 ViewOverlay mOverlay; 3272 3273 /** 3274 * Consistency verifier for debugging purposes. 3275 * @hide 3276 */ 3277 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 3278 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 3279 new InputEventConsistencyVerifier(this, 0) : null; 3280 3281 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); 3282 3283 /** 3284 * Simple constructor to use when creating a view from code. 3285 * 3286 * @param context The Context the view is running in, through which it can 3287 * access the current theme, resources, etc. 3288 */ 3289 public View(Context context) { 3290 mContext = context; 3291 mResources = context != null ? context.getResources() : null; 3292 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 3293 // Set some flags defaults 3294 mPrivateFlags2 = 3295 (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) | 3296 (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) | 3297 (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) | 3298 (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) | 3299 (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) | 3300 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT); 3301 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 3302 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 3303 mUserPaddingStart = UNDEFINED_PADDING; 3304 mUserPaddingEnd = UNDEFINED_PADDING; 3305 3306 if (!sUseBrokenMakeMeasureSpec && context.getApplicationInfo().targetSdkVersion <= 3307 Build.VERSION_CODES.JELLY_BEAN_MR1 ) { 3308 // Older apps may need this compatibility hack for measurement. 3309 sUseBrokenMakeMeasureSpec = true; 3310 } 3311 } 3312 3313 /** 3314 * Constructor that is called when inflating a view from XML. This is called 3315 * when a view is being constructed from an XML file, supplying attributes 3316 * that were specified in the XML file. This version uses a default style of 3317 * 0, so the only attribute values applied are those in the Context's Theme 3318 * and the given AttributeSet. 3319 * 3320 * <p> 3321 * The method onFinishInflate() will be called after all children have been 3322 * added. 3323 * 3324 * @param context The Context the view is running in, through which it can 3325 * access the current theme, resources, etc. 3326 * @param attrs The attributes of the XML tag that is inflating the view. 3327 * @see #View(Context, AttributeSet, int) 3328 */ 3329 public View(Context context, AttributeSet attrs) { 3330 this(context, attrs, 0); 3331 } 3332 3333 /** 3334 * Perform inflation from XML and apply a class-specific base style. This 3335 * constructor of View allows subclasses to use their own base style when 3336 * they are inflating. For example, a Button class's constructor would call 3337 * this version of the super class constructor and supply 3338 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows 3339 * the theme's button style to modify all of the base view attributes (in 3340 * particular its background) as well as the Button class's attributes. 3341 * 3342 * @param context The Context the view is running in, through which it can 3343 * access the current theme, resources, etc. 3344 * @param attrs The attributes of the XML tag that is inflating the view. 3345 * @param defStyle The default style to apply to this view. If 0, no style 3346 * will be applied (beyond what is included in the theme). This may 3347 * either be an attribute resource, whose value will be retrieved 3348 * from the current theme, or an explicit style resource. 3349 * @see #View(Context, AttributeSet) 3350 */ 3351 public View(Context context, AttributeSet attrs, int defStyle) { 3352 this(context); 3353 3354 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View, 3355 defStyle, 0); 3356 3357 Drawable background = null; 3358 3359 int leftPadding = -1; 3360 int topPadding = -1; 3361 int rightPadding = -1; 3362 int bottomPadding = -1; 3363 int startPadding = UNDEFINED_PADDING; 3364 int endPadding = UNDEFINED_PADDING; 3365 3366 int padding = -1; 3367 3368 int viewFlagValues = 0; 3369 int viewFlagMasks = 0; 3370 3371 boolean setScrollContainer = false; 3372 3373 int x = 0; 3374 int y = 0; 3375 3376 float tx = 0; 3377 float ty = 0; 3378 float rotation = 0; 3379 float rotationX = 0; 3380 float rotationY = 0; 3381 float sx = 1f; 3382 float sy = 1f; 3383 boolean transformSet = false; 3384 3385 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 3386 int overScrollMode = mOverScrollMode; 3387 boolean initializeScrollbars = false; 3388 3389 boolean leftPaddingDefined = false; 3390 boolean rightPaddingDefined = false; 3391 boolean startPaddingDefined = false; 3392 boolean endPaddingDefined = false; 3393 3394 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3395 3396 final int N = a.getIndexCount(); 3397 for (int i = 0; i < N; i++) { 3398 int attr = a.getIndex(i); 3399 switch (attr) { 3400 case com.android.internal.R.styleable.View_background: 3401 background = a.getDrawable(attr); 3402 break; 3403 case com.android.internal.R.styleable.View_padding: 3404 padding = a.getDimensionPixelSize(attr, -1); 3405 mUserPaddingLeftInitial = padding; 3406 mUserPaddingRightInitial = padding; 3407 leftPaddingDefined = true; 3408 rightPaddingDefined = true; 3409 break; 3410 case com.android.internal.R.styleable.View_paddingLeft: 3411 leftPadding = a.getDimensionPixelSize(attr, -1); 3412 mUserPaddingLeftInitial = leftPadding; 3413 leftPaddingDefined = true; 3414 break; 3415 case com.android.internal.R.styleable.View_paddingTop: 3416 topPadding = a.getDimensionPixelSize(attr, -1); 3417 break; 3418 case com.android.internal.R.styleable.View_paddingRight: 3419 rightPadding = a.getDimensionPixelSize(attr, -1); 3420 mUserPaddingRightInitial = rightPadding; 3421 rightPaddingDefined = true; 3422 break; 3423 case com.android.internal.R.styleable.View_paddingBottom: 3424 bottomPadding = a.getDimensionPixelSize(attr, -1); 3425 break; 3426 case com.android.internal.R.styleable.View_paddingStart: 3427 startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3428 startPaddingDefined = (startPadding != UNDEFINED_PADDING); 3429 break; 3430 case com.android.internal.R.styleable.View_paddingEnd: 3431 endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3432 endPaddingDefined = (endPadding != UNDEFINED_PADDING); 3433 break; 3434 case com.android.internal.R.styleable.View_scrollX: 3435 x = a.getDimensionPixelOffset(attr, 0); 3436 break; 3437 case com.android.internal.R.styleable.View_scrollY: 3438 y = a.getDimensionPixelOffset(attr, 0); 3439 break; 3440 case com.android.internal.R.styleable.View_alpha: 3441 setAlpha(a.getFloat(attr, 1f)); 3442 break; 3443 case com.android.internal.R.styleable.View_transformPivotX: 3444 setPivotX(a.getDimensionPixelOffset(attr, 0)); 3445 break; 3446 case com.android.internal.R.styleable.View_transformPivotY: 3447 setPivotY(a.getDimensionPixelOffset(attr, 0)); 3448 break; 3449 case com.android.internal.R.styleable.View_translationX: 3450 tx = a.getDimensionPixelOffset(attr, 0); 3451 transformSet = true; 3452 break; 3453 case com.android.internal.R.styleable.View_translationY: 3454 ty = a.getDimensionPixelOffset(attr, 0); 3455 transformSet = true; 3456 break; 3457 case com.android.internal.R.styleable.View_rotation: 3458 rotation = a.getFloat(attr, 0); 3459 transformSet = true; 3460 break; 3461 case com.android.internal.R.styleable.View_rotationX: 3462 rotationX = a.getFloat(attr, 0); 3463 transformSet = true; 3464 break; 3465 case com.android.internal.R.styleable.View_rotationY: 3466 rotationY = a.getFloat(attr, 0); 3467 transformSet = true; 3468 break; 3469 case com.android.internal.R.styleable.View_scaleX: 3470 sx = a.getFloat(attr, 1f); 3471 transformSet = true; 3472 break; 3473 case com.android.internal.R.styleable.View_scaleY: 3474 sy = a.getFloat(attr, 1f); 3475 transformSet = true; 3476 break; 3477 case com.android.internal.R.styleable.View_id: 3478 mID = a.getResourceId(attr, NO_ID); 3479 break; 3480 case com.android.internal.R.styleable.View_tag: 3481 mTag = a.getText(attr); 3482 break; 3483 case com.android.internal.R.styleable.View_fitsSystemWindows: 3484 if (a.getBoolean(attr, false)) { 3485 viewFlagValues |= FITS_SYSTEM_WINDOWS; 3486 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 3487 } 3488 break; 3489 case com.android.internal.R.styleable.View_focusable: 3490 if (a.getBoolean(attr, false)) { 3491 viewFlagValues |= FOCUSABLE; 3492 viewFlagMasks |= FOCUSABLE_MASK; 3493 } 3494 break; 3495 case com.android.internal.R.styleable.View_focusableInTouchMode: 3496 if (a.getBoolean(attr, false)) { 3497 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 3498 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 3499 } 3500 break; 3501 case com.android.internal.R.styleable.View_clickable: 3502 if (a.getBoolean(attr, false)) { 3503 viewFlagValues |= CLICKABLE; 3504 viewFlagMasks |= CLICKABLE; 3505 } 3506 break; 3507 case com.android.internal.R.styleable.View_longClickable: 3508 if (a.getBoolean(attr, false)) { 3509 viewFlagValues |= LONG_CLICKABLE; 3510 viewFlagMasks |= LONG_CLICKABLE; 3511 } 3512 break; 3513 case com.android.internal.R.styleable.View_saveEnabled: 3514 if (!a.getBoolean(attr, true)) { 3515 viewFlagValues |= SAVE_DISABLED; 3516 viewFlagMasks |= SAVE_DISABLED_MASK; 3517 } 3518 break; 3519 case com.android.internal.R.styleable.View_duplicateParentState: 3520 if (a.getBoolean(attr, false)) { 3521 viewFlagValues |= DUPLICATE_PARENT_STATE; 3522 viewFlagMasks |= DUPLICATE_PARENT_STATE; 3523 } 3524 break; 3525 case com.android.internal.R.styleable.View_visibility: 3526 final int visibility = a.getInt(attr, 0); 3527 if (visibility != 0) { 3528 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 3529 viewFlagMasks |= VISIBILITY_MASK; 3530 } 3531 break; 3532 case com.android.internal.R.styleable.View_layoutDirection: 3533 // Clear any layout direction flags (included resolved bits) already set 3534 mPrivateFlags2 &= 3535 ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK); 3536 // Set the layout direction flags depending on the value of the attribute 3537 final int layoutDirection = a.getInt(attr, -1); 3538 final int value = (layoutDirection != -1) ? 3539 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 3540 mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT); 3541 break; 3542 case com.android.internal.R.styleable.View_drawingCacheQuality: 3543 final int cacheQuality = a.getInt(attr, 0); 3544 if (cacheQuality != 0) { 3545 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 3546 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 3547 } 3548 break; 3549 case com.android.internal.R.styleable.View_contentDescription: 3550 setContentDescription(a.getString(attr)); 3551 break; 3552 case com.android.internal.R.styleable.View_labelFor: 3553 setLabelFor(a.getResourceId(attr, NO_ID)); 3554 break; 3555 case com.android.internal.R.styleable.View_soundEffectsEnabled: 3556 if (!a.getBoolean(attr, true)) { 3557 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 3558 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 3559 } 3560 break; 3561 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 3562 if (!a.getBoolean(attr, true)) { 3563 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 3564 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 3565 } 3566 break; 3567 case R.styleable.View_scrollbars: 3568 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 3569 if (scrollbars != SCROLLBARS_NONE) { 3570 viewFlagValues |= scrollbars; 3571 viewFlagMasks |= SCROLLBARS_MASK; 3572 initializeScrollbars = true; 3573 } 3574 break; 3575 //noinspection deprecation 3576 case R.styleable.View_fadingEdge: 3577 if (targetSdkVersion >= ICE_CREAM_SANDWICH) { 3578 // Ignore the attribute starting with ICS 3579 break; 3580 } 3581 // With builds < ICS, fall through and apply fading edges 3582 case R.styleable.View_requiresFadingEdge: 3583 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 3584 if (fadingEdge != FADING_EDGE_NONE) { 3585 viewFlagValues |= fadingEdge; 3586 viewFlagMasks |= FADING_EDGE_MASK; 3587 initializeFadingEdge(a); 3588 } 3589 break; 3590 case R.styleable.View_scrollbarStyle: 3591 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 3592 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3593 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 3594 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 3595 } 3596 break; 3597 case R.styleable.View_isScrollContainer: 3598 setScrollContainer = true; 3599 if (a.getBoolean(attr, false)) { 3600 setScrollContainer(true); 3601 } 3602 break; 3603 case com.android.internal.R.styleable.View_keepScreenOn: 3604 if (a.getBoolean(attr, false)) { 3605 viewFlagValues |= KEEP_SCREEN_ON; 3606 viewFlagMasks |= KEEP_SCREEN_ON; 3607 } 3608 break; 3609 case R.styleable.View_filterTouchesWhenObscured: 3610 if (a.getBoolean(attr, false)) { 3611 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 3612 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 3613 } 3614 break; 3615 case R.styleable.View_nextFocusLeft: 3616 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 3617 break; 3618 case R.styleable.View_nextFocusRight: 3619 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 3620 break; 3621 case R.styleable.View_nextFocusUp: 3622 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 3623 break; 3624 case R.styleable.View_nextFocusDown: 3625 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 3626 break; 3627 case R.styleable.View_nextFocusForward: 3628 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 3629 break; 3630 case R.styleable.View_minWidth: 3631 mMinWidth = a.getDimensionPixelSize(attr, 0); 3632 break; 3633 case R.styleable.View_minHeight: 3634 mMinHeight = a.getDimensionPixelSize(attr, 0); 3635 break; 3636 case R.styleable.View_onClick: 3637 if (context.isRestricted()) { 3638 throw new IllegalStateException("The android:onClick attribute cannot " 3639 + "be used within a restricted context"); 3640 } 3641 3642 final String handlerName = a.getString(attr); 3643 if (handlerName != null) { 3644 setOnClickListener(new OnClickListener() { 3645 private Method mHandler; 3646 3647 public void onClick(View v) { 3648 if (mHandler == null) { 3649 try { 3650 mHandler = getContext().getClass().getMethod(handlerName, 3651 View.class); 3652 } catch (NoSuchMethodException e) { 3653 int id = getId(); 3654 String idText = id == NO_ID ? "" : " with id '" 3655 + getContext().getResources().getResourceEntryName( 3656 id) + "'"; 3657 throw new IllegalStateException("Could not find a method " + 3658 handlerName + "(View) in the activity " 3659 + getContext().getClass() + " for onClick handler" 3660 + " on view " + View.this.getClass() + idText, e); 3661 } 3662 } 3663 3664 try { 3665 mHandler.invoke(getContext(), View.this); 3666 } catch (IllegalAccessException e) { 3667 throw new IllegalStateException("Could not execute non " 3668 + "public method of the activity", e); 3669 } catch (InvocationTargetException e) { 3670 throw new IllegalStateException("Could not execute " 3671 + "method of the activity", e); 3672 } 3673 } 3674 }); 3675 } 3676 break; 3677 case R.styleable.View_overScrollMode: 3678 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 3679 break; 3680 case R.styleable.View_verticalScrollbarPosition: 3681 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 3682 break; 3683 case R.styleable.View_layerType: 3684 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 3685 break; 3686 case R.styleable.View_textDirection: 3687 // Clear any text direction flag already set 3688 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 3689 // Set the text direction flags depending on the value of the attribute 3690 final int textDirection = a.getInt(attr, -1); 3691 if (textDirection != -1) { 3692 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection]; 3693 } 3694 break; 3695 case R.styleable.View_textAlignment: 3696 // Clear any text alignment flag already set 3697 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 3698 // Set the text alignment flag depending on the value of the attribute 3699 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); 3700 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment]; 3701 break; 3702 case R.styleable.View_importantForAccessibility: 3703 setImportantForAccessibility(a.getInt(attr, 3704 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); 3705 break; 3706 } 3707 } 3708 3709 setOverScrollMode(overScrollMode); 3710 3711 // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet 3712 // the resolved layout direction). Those cached values will be used later during padding 3713 // resolution. 3714 mUserPaddingStart = startPadding; 3715 mUserPaddingEnd = endPadding; 3716 3717 if (background != null) { 3718 setBackground(background); 3719 } 3720 3721 if (padding >= 0) { 3722 leftPadding = padding; 3723 topPadding = padding; 3724 rightPadding = padding; 3725 bottomPadding = padding; 3726 mUserPaddingLeftInitial = padding; 3727 mUserPaddingRightInitial = padding; 3728 } 3729 3730 if (isRtlCompatibilityMode()) { 3731 // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case. 3732 // left / right padding are used if defined (meaning here nothing to do). If they are not 3733 // defined and start / end padding are defined (e.g. in Frameworks resources), then we use 3734 // start / end and resolve them as left / right (layout direction is not taken into account). 3735 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 3736 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 3737 // defined. 3738 if (!leftPaddingDefined && startPaddingDefined) { 3739 leftPadding = startPadding; 3740 } 3741 mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial; 3742 if (!rightPaddingDefined && endPaddingDefined) { 3743 rightPadding = endPadding; 3744 } 3745 mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial; 3746 } else { 3747 // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right 3748 // values defined. Otherwise, left /right values are used. 3749 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 3750 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 3751 // defined. 3752 final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined; 3753 3754 if (leftPaddingDefined && !hasRelativePadding) { 3755 mUserPaddingLeftInitial = leftPadding; 3756 } 3757 if (rightPaddingDefined && !hasRelativePadding) { 3758 mUserPaddingRightInitial = rightPadding; 3759 } 3760 } 3761 3762 internalSetPadding( 3763 mUserPaddingLeftInitial, 3764 topPadding >= 0 ? topPadding : mPaddingTop, 3765 mUserPaddingRightInitial, 3766 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 3767 3768 if (viewFlagMasks != 0) { 3769 setFlags(viewFlagValues, viewFlagMasks); 3770 } 3771 3772 if (initializeScrollbars) { 3773 initializeScrollbars(a); 3774 } 3775 3776 a.recycle(); 3777 3778 // Needs to be called after mViewFlags is set 3779 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3780 recomputePadding(); 3781 } 3782 3783 if (x != 0 || y != 0) { 3784 scrollTo(x, y); 3785 } 3786 3787 if (transformSet) { 3788 setTranslationX(tx); 3789 setTranslationY(ty); 3790 setRotation(rotation); 3791 setRotationX(rotationX); 3792 setRotationY(rotationY); 3793 setScaleX(sx); 3794 setScaleY(sy); 3795 } 3796 3797 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 3798 setScrollContainer(true); 3799 } 3800 3801 computeOpaqueFlags(); 3802 } 3803 3804 /** 3805 * Non-public constructor for use in testing 3806 */ 3807 View() { 3808 mResources = null; 3809 } 3810 3811 public String toString() { 3812 StringBuilder out = new StringBuilder(128); 3813 out.append(getClass().getName()); 3814 out.append('{'); 3815 out.append(Integer.toHexString(System.identityHashCode(this))); 3816 out.append(' '); 3817 switch (mViewFlags&VISIBILITY_MASK) { 3818 case VISIBLE: out.append('V'); break; 3819 case INVISIBLE: out.append('I'); break; 3820 case GONE: out.append('G'); break; 3821 default: out.append('.'); break; 3822 } 3823 out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.'); 3824 out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.'); 3825 out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D'); 3826 out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.'); 3827 out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.'); 3828 out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.'); 3829 out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.'); 3830 out.append(' '); 3831 out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.'); 3832 out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.'); 3833 out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.'); 3834 if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) { 3835 out.append('p'); 3836 } else { 3837 out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.'); 3838 } 3839 out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.'); 3840 out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.'); 3841 out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.'); 3842 out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.'); 3843 out.append(' '); 3844 out.append(mLeft); 3845 out.append(','); 3846 out.append(mTop); 3847 out.append('-'); 3848 out.append(mRight); 3849 out.append(','); 3850 out.append(mBottom); 3851 final int id = getId(); 3852 if (id != NO_ID) { 3853 out.append(" #"); 3854 out.append(Integer.toHexString(id)); 3855 final Resources r = mResources; 3856 if (id != 0 && r != null) { 3857 try { 3858 String pkgname; 3859 switch (id&0xff000000) { 3860 case 0x7f000000: 3861 pkgname="app"; 3862 break; 3863 case 0x01000000: 3864 pkgname="android"; 3865 break; 3866 default: 3867 pkgname = r.getResourcePackageName(id); 3868 break; 3869 } 3870 String typename = r.getResourceTypeName(id); 3871 String entryname = r.getResourceEntryName(id); 3872 out.append(" "); 3873 out.append(pkgname); 3874 out.append(":"); 3875 out.append(typename); 3876 out.append("/"); 3877 out.append(entryname); 3878 } catch (Resources.NotFoundException e) { 3879 } 3880 } 3881 } 3882 out.append("}"); 3883 return out.toString(); 3884 } 3885 3886 /** 3887 * <p> 3888 * Initializes the fading edges from a given set of styled attributes. This 3889 * method should be called by subclasses that need fading edges and when an 3890 * instance of these subclasses is created programmatically rather than 3891 * being inflated from XML. This method is automatically called when the XML 3892 * is inflated. 3893 * </p> 3894 * 3895 * @param a the styled attributes set to initialize the fading edges from 3896 */ 3897 protected void initializeFadingEdge(TypedArray a) { 3898 initScrollCache(); 3899 3900 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 3901 R.styleable.View_fadingEdgeLength, 3902 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 3903 } 3904 3905 /** 3906 * Returns the size of the vertical faded edges used to indicate that more 3907 * content in this view is visible. 3908 * 3909 * @return The size in pixels of the vertical faded edge or 0 if vertical 3910 * faded edges are not enabled for this view. 3911 * @attr ref android.R.styleable#View_fadingEdgeLength 3912 */ 3913 public int getVerticalFadingEdgeLength() { 3914 if (isVerticalFadingEdgeEnabled()) { 3915 ScrollabilityCache cache = mScrollCache; 3916 if (cache != null) { 3917 return cache.fadingEdgeLength; 3918 } 3919 } 3920 return 0; 3921 } 3922 3923 /** 3924 * Set the size of the faded edge used to indicate that more content in this 3925 * view is available. Will not change whether the fading edge is enabled; use 3926 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 3927 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 3928 * for the vertical or horizontal fading edges. 3929 * 3930 * @param length The size in pixels of the faded edge used to indicate that more 3931 * content in this view is visible. 3932 */ 3933 public void setFadingEdgeLength(int length) { 3934 initScrollCache(); 3935 mScrollCache.fadingEdgeLength = length; 3936 } 3937 3938 /** 3939 * Returns the size of the horizontal faded edges used to indicate that more 3940 * content in this view is visible. 3941 * 3942 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 3943 * faded edges are not enabled for this view. 3944 * @attr ref android.R.styleable#View_fadingEdgeLength 3945 */ 3946 public int getHorizontalFadingEdgeLength() { 3947 if (isHorizontalFadingEdgeEnabled()) { 3948 ScrollabilityCache cache = mScrollCache; 3949 if (cache != null) { 3950 return cache.fadingEdgeLength; 3951 } 3952 } 3953 return 0; 3954 } 3955 3956 /** 3957 * Returns the width of the vertical scrollbar. 3958 * 3959 * @return The width in pixels of the vertical scrollbar or 0 if there 3960 * is no vertical scrollbar. 3961 */ 3962 public int getVerticalScrollbarWidth() { 3963 ScrollabilityCache cache = mScrollCache; 3964 if (cache != null) { 3965 ScrollBarDrawable scrollBar = cache.scrollBar; 3966 if (scrollBar != null) { 3967 int size = scrollBar.getSize(true); 3968 if (size <= 0) { 3969 size = cache.scrollBarSize; 3970 } 3971 return size; 3972 } 3973 return 0; 3974 } 3975 return 0; 3976 } 3977 3978 /** 3979 * Returns the height of the horizontal scrollbar. 3980 * 3981 * @return The height in pixels of the horizontal scrollbar or 0 if 3982 * there is no horizontal scrollbar. 3983 */ 3984 protected int getHorizontalScrollbarHeight() { 3985 ScrollabilityCache cache = mScrollCache; 3986 if (cache != null) { 3987 ScrollBarDrawable scrollBar = cache.scrollBar; 3988 if (scrollBar != null) { 3989 int size = scrollBar.getSize(false); 3990 if (size <= 0) { 3991 size = cache.scrollBarSize; 3992 } 3993 return size; 3994 } 3995 return 0; 3996 } 3997 return 0; 3998 } 3999 4000 /** 4001 * <p> 4002 * Initializes the scrollbars from a given set of styled attributes. This 4003 * method should be called by subclasses that need scrollbars and when an 4004 * instance of these subclasses is created programmatically rather than 4005 * being inflated from XML. This method is automatically called when the XML 4006 * is inflated. 4007 * </p> 4008 * 4009 * @param a the styled attributes set to initialize the scrollbars from 4010 */ 4011 protected void initializeScrollbars(TypedArray a) { 4012 initScrollCache(); 4013 4014 final ScrollabilityCache scrollabilityCache = mScrollCache; 4015 4016 if (scrollabilityCache.scrollBar == null) { 4017 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 4018 } 4019 4020 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 4021 4022 if (!fadeScrollbars) { 4023 scrollabilityCache.state = ScrollabilityCache.ON; 4024 } 4025 scrollabilityCache.fadeScrollBars = fadeScrollbars; 4026 4027 4028 scrollabilityCache.scrollBarFadeDuration = a.getInt( 4029 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 4030 .getScrollBarFadeDuration()); 4031 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 4032 R.styleable.View_scrollbarDefaultDelayBeforeFade, 4033 ViewConfiguration.getScrollDefaultDelay()); 4034 4035 4036 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 4037 com.android.internal.R.styleable.View_scrollbarSize, 4038 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 4039 4040 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 4041 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 4042 4043 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 4044 if (thumb != null) { 4045 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 4046 } 4047 4048 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 4049 false); 4050 if (alwaysDraw) { 4051 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 4052 } 4053 4054 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 4055 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 4056 4057 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 4058 if (thumb != null) { 4059 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 4060 } 4061 4062 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 4063 false); 4064 if (alwaysDraw) { 4065 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 4066 } 4067 4068 // Apply layout direction to the new Drawables if needed 4069 final int layoutDirection = getLayoutDirection(); 4070 if (track != null) { 4071 track.setLayoutDirection(layoutDirection); 4072 } 4073 if (thumb != null) { 4074 thumb.setLayoutDirection(layoutDirection); 4075 } 4076 4077 // Re-apply user/background padding so that scrollbar(s) get added 4078 resolvePadding(); 4079 } 4080 4081 /** 4082 * <p> 4083 * Initalizes the scrollability cache if necessary. 4084 * </p> 4085 */ 4086 private void initScrollCache() { 4087 if (mScrollCache == null) { 4088 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 4089 } 4090 } 4091 4092 private ScrollabilityCache getScrollCache() { 4093 initScrollCache(); 4094 return mScrollCache; 4095 } 4096 4097 /** 4098 * Set the position of the vertical scroll bar. Should be one of 4099 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 4100 * {@link #SCROLLBAR_POSITION_RIGHT}. 4101 * 4102 * @param position Where the vertical scroll bar should be positioned. 4103 */ 4104 public void setVerticalScrollbarPosition(int position) { 4105 if (mVerticalScrollbarPosition != position) { 4106 mVerticalScrollbarPosition = position; 4107 computeOpaqueFlags(); 4108 resolvePadding(); 4109 } 4110 } 4111 4112 /** 4113 * @return The position where the vertical scroll bar will show, if applicable. 4114 * @see #setVerticalScrollbarPosition(int) 4115 */ 4116 public int getVerticalScrollbarPosition() { 4117 return mVerticalScrollbarPosition; 4118 } 4119 4120 ListenerInfo getListenerInfo() { 4121 if (mListenerInfo != null) { 4122 return mListenerInfo; 4123 } 4124 mListenerInfo = new ListenerInfo(); 4125 return mListenerInfo; 4126 } 4127 4128 /** 4129 * Register a callback to be invoked when focus of this view changed. 4130 * 4131 * @param l The callback that will run. 4132 */ 4133 public void setOnFocusChangeListener(OnFocusChangeListener l) { 4134 getListenerInfo().mOnFocusChangeListener = l; 4135 } 4136 4137 /** 4138 * Add a listener that will be called when the bounds of the view change due to 4139 * layout processing. 4140 * 4141 * @param listener The listener that will be called when layout bounds change. 4142 */ 4143 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 4144 ListenerInfo li = getListenerInfo(); 4145 if (li.mOnLayoutChangeListeners == null) { 4146 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 4147 } 4148 if (!li.mOnLayoutChangeListeners.contains(listener)) { 4149 li.mOnLayoutChangeListeners.add(listener); 4150 } 4151 } 4152 4153 /** 4154 * Remove a listener for layout changes. 4155 * 4156 * @param listener The listener for layout bounds change. 4157 */ 4158 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 4159 ListenerInfo li = mListenerInfo; 4160 if (li == null || li.mOnLayoutChangeListeners == null) { 4161 return; 4162 } 4163 li.mOnLayoutChangeListeners.remove(listener); 4164 } 4165 4166 /** 4167 * Add a listener for attach state changes. 4168 * 4169 * This listener will be called whenever this view is attached or detached 4170 * from a window. Remove the listener using 4171 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 4172 * 4173 * @param listener Listener to attach 4174 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 4175 */ 4176 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4177 ListenerInfo li = getListenerInfo(); 4178 if (li.mOnAttachStateChangeListeners == null) { 4179 li.mOnAttachStateChangeListeners 4180 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 4181 } 4182 li.mOnAttachStateChangeListeners.add(listener); 4183 } 4184 4185 /** 4186 * Remove a listener for attach state changes. The listener will receive no further 4187 * notification of window attach/detach events. 4188 * 4189 * @param listener Listener to remove 4190 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 4191 */ 4192 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4193 ListenerInfo li = mListenerInfo; 4194 if (li == null || li.mOnAttachStateChangeListeners == null) { 4195 return; 4196 } 4197 li.mOnAttachStateChangeListeners.remove(listener); 4198 } 4199 4200 /** 4201 * Returns the focus-change callback registered for this view. 4202 * 4203 * @return The callback, or null if one is not registered. 4204 */ 4205 public OnFocusChangeListener getOnFocusChangeListener() { 4206 ListenerInfo li = mListenerInfo; 4207 return li != null ? li.mOnFocusChangeListener : null; 4208 } 4209 4210 /** 4211 * Register a callback to be invoked when this view is clicked. If this view is not 4212 * clickable, it becomes clickable. 4213 * 4214 * @param l The callback that will run 4215 * 4216 * @see #setClickable(boolean) 4217 */ 4218 public void setOnClickListener(OnClickListener l) { 4219 if (!isClickable()) { 4220 setClickable(true); 4221 } 4222 getListenerInfo().mOnClickListener = l; 4223 } 4224 4225 /** 4226 * Return whether this view has an attached OnClickListener. Returns 4227 * true if there is a listener, false if there is none. 4228 */ 4229 public boolean hasOnClickListeners() { 4230 ListenerInfo li = mListenerInfo; 4231 return (li != null && li.mOnClickListener != null); 4232 } 4233 4234 /** 4235 * Register a callback to be invoked when this view is clicked and held. If this view is not 4236 * long clickable, it becomes long clickable. 4237 * 4238 * @param l The callback that will run 4239 * 4240 * @see #setLongClickable(boolean) 4241 */ 4242 public void setOnLongClickListener(OnLongClickListener l) { 4243 if (!isLongClickable()) { 4244 setLongClickable(true); 4245 } 4246 getListenerInfo().mOnLongClickListener = l; 4247 } 4248 4249 /** 4250 * Register a callback to be invoked when the context menu for this view is 4251 * being built. If this view is not long clickable, it becomes long clickable. 4252 * 4253 * @param l The callback that will run 4254 * 4255 */ 4256 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 4257 if (!isLongClickable()) { 4258 setLongClickable(true); 4259 } 4260 getListenerInfo().mOnCreateContextMenuListener = l; 4261 } 4262 4263 /** 4264 * Call this view's OnClickListener, if it is defined. Performs all normal 4265 * actions associated with clicking: reporting accessibility event, playing 4266 * a sound, etc. 4267 * 4268 * @return True there was an assigned OnClickListener that was called, false 4269 * otherwise is returned. 4270 */ 4271 public boolean performClick() { 4272 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 4273 4274 ListenerInfo li = mListenerInfo; 4275 if (li != null && li.mOnClickListener != null) { 4276 playSoundEffect(SoundEffectConstants.CLICK); 4277 li.mOnClickListener.onClick(this); 4278 return true; 4279 } 4280 4281 return false; 4282 } 4283 4284 /** 4285 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 4286 * this only calls the listener, and does not do any associated clicking 4287 * actions like reporting an accessibility event. 4288 * 4289 * @return True there was an assigned OnClickListener that was called, false 4290 * otherwise is returned. 4291 */ 4292 public boolean callOnClick() { 4293 ListenerInfo li = mListenerInfo; 4294 if (li != null && li.mOnClickListener != null) { 4295 li.mOnClickListener.onClick(this); 4296 return true; 4297 } 4298 return false; 4299 } 4300 4301 /** 4302 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 4303 * OnLongClickListener did not consume the event. 4304 * 4305 * @return True if one of the above receivers consumed the event, false otherwise. 4306 */ 4307 public boolean performLongClick() { 4308 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 4309 4310 boolean handled = false; 4311 ListenerInfo li = mListenerInfo; 4312 if (li != null && li.mOnLongClickListener != null) { 4313 handled = li.mOnLongClickListener.onLongClick(View.this); 4314 } 4315 if (!handled) { 4316 handled = showContextMenu(); 4317 } 4318 if (handled) { 4319 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 4320 } 4321 return handled; 4322 } 4323 4324 /** 4325 * Performs button-related actions during a touch down event. 4326 * 4327 * @param event The event. 4328 * @return True if the down was consumed. 4329 * 4330 * @hide 4331 */ 4332 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 4333 if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 4334 if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) { 4335 return true; 4336 } 4337 } 4338 return false; 4339 } 4340 4341 /** 4342 * Bring up the context menu for this view. 4343 * 4344 * @return Whether a context menu was displayed. 4345 */ 4346 public boolean showContextMenu() { 4347 return getParent().showContextMenuForChild(this); 4348 } 4349 4350 /** 4351 * Bring up the context menu for this view, referring to the item under the specified point. 4352 * 4353 * @param x The referenced x coordinate. 4354 * @param y The referenced y coordinate. 4355 * @param metaState The keyboard modifiers that were pressed. 4356 * @return Whether a context menu was displayed. 4357 * 4358 * @hide 4359 */ 4360 public boolean showContextMenu(float x, float y, int metaState) { 4361 return showContextMenu(); 4362 } 4363 4364 /** 4365 * Start an action mode. 4366 * 4367 * @param callback Callback that will control the lifecycle of the action mode 4368 * @return The new action mode if it is started, null otherwise 4369 * 4370 * @see ActionMode 4371 */ 4372 public ActionMode startActionMode(ActionMode.Callback callback) { 4373 ViewParent parent = getParent(); 4374 if (parent == null) return null; 4375 return parent.startActionModeForChild(this, callback); 4376 } 4377 4378 /** 4379 * Register a callback to be invoked when a hardware key is pressed in this view. 4380 * Key presses in software input methods will generally not trigger the methods of 4381 * this listener. 4382 * @param l the key listener to attach to this view 4383 */ 4384 public void setOnKeyListener(OnKeyListener l) { 4385 getListenerInfo().mOnKeyListener = l; 4386 } 4387 4388 /** 4389 * Register a callback to be invoked when a touch event is sent to this view. 4390 * @param l the touch listener to attach to this view 4391 */ 4392 public void setOnTouchListener(OnTouchListener l) { 4393 getListenerInfo().mOnTouchListener = l; 4394 } 4395 4396 /** 4397 * Register a callback to be invoked when a generic motion event is sent to this view. 4398 * @param l the generic motion listener to attach to this view 4399 */ 4400 public void setOnGenericMotionListener(OnGenericMotionListener l) { 4401 getListenerInfo().mOnGenericMotionListener = l; 4402 } 4403 4404 /** 4405 * Register a callback to be invoked when a hover event is sent to this view. 4406 * @param l the hover listener to attach to this view 4407 */ 4408 public void setOnHoverListener(OnHoverListener l) { 4409 getListenerInfo().mOnHoverListener = l; 4410 } 4411 4412 /** 4413 * Register a drag event listener callback object for this View. The parameter is 4414 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 4415 * View, the system calls the 4416 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 4417 * @param l An implementation of {@link android.view.View.OnDragListener}. 4418 */ 4419 public void setOnDragListener(OnDragListener l) { 4420 getListenerInfo().mOnDragListener = l; 4421 } 4422 4423 /** 4424 * Give this view focus. This will cause 4425 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 4426 * 4427 * Note: this does not check whether this {@link View} should get focus, it just 4428 * gives it focus no matter what. It should only be called internally by framework 4429 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 4430 * 4431 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 4432 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 4433 * focus moved when requestFocus() is called. It may not always 4434 * apply, in which case use the default View.FOCUS_DOWN. 4435 * @param previouslyFocusedRect The rectangle of the view that had focus 4436 * prior in this View's coordinate system. 4437 */ 4438 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) { 4439 if (DBG) { 4440 System.out.println(this + " requestFocus()"); 4441 } 4442 4443 if ((mPrivateFlags & PFLAG_FOCUSED) == 0) { 4444 mPrivateFlags |= PFLAG_FOCUSED; 4445 4446 View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null; 4447 4448 if (mParent != null) { 4449 mParent.requestChildFocus(this, this); 4450 } 4451 4452 if (mAttachInfo != null) { 4453 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this); 4454 } 4455 4456 onFocusChanged(true, direction, previouslyFocusedRect); 4457 refreshDrawableState(); 4458 } 4459 } 4460 4461 /** 4462 * Request that a rectangle of this view be visible on the screen, 4463 * scrolling if necessary just enough. 4464 * 4465 * <p>A View should call this if it maintains some notion of which part 4466 * of its content is interesting. For example, a text editing view 4467 * should call this when its cursor moves. 4468 * 4469 * @param rectangle The rectangle. 4470 * @return Whether any parent scrolled. 4471 */ 4472 public boolean requestRectangleOnScreen(Rect rectangle) { 4473 return requestRectangleOnScreen(rectangle, false); 4474 } 4475 4476 /** 4477 * Request that a rectangle of this view be visible on the screen, 4478 * scrolling if necessary just enough. 4479 * 4480 * <p>A View should call this if it maintains some notion of which part 4481 * of its content is interesting. For example, a text editing view 4482 * should call this when its cursor moves. 4483 * 4484 * <p>When <code>immediate</code> is set to true, scrolling will not be 4485 * animated. 4486 * 4487 * @param rectangle The rectangle. 4488 * @param immediate True to forbid animated scrolling, false otherwise 4489 * @return Whether any parent scrolled. 4490 */ 4491 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 4492 if (mParent == null) { 4493 return false; 4494 } 4495 4496 View child = this; 4497 4498 RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF(); 4499 position.set(rectangle); 4500 4501 ViewParent parent = mParent; 4502 boolean scrolled = false; 4503 while (parent != null) { 4504 rectangle.set((int) position.left, (int) position.top, 4505 (int) position.right, (int) position.bottom); 4506 4507 scrolled |= parent.requestChildRectangleOnScreen(child, 4508 rectangle, immediate); 4509 4510 if (!child.hasIdentityMatrix()) { 4511 child.getMatrix().mapRect(position); 4512 } 4513 4514 position.offset(child.mLeft, child.mTop); 4515 4516 if (!(parent instanceof View)) { 4517 break; 4518 } 4519 4520 View parentView = (View) parent; 4521 4522 position.offset(-parentView.getScrollX(), -parentView.getScrollY()); 4523 4524 child = parentView; 4525 parent = child.getParent(); 4526 } 4527 4528 return scrolled; 4529 } 4530 4531 /** 4532 * Called when this view wants to give up focus. If focus is cleared 4533 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 4534 * <p> 4535 * <strong>Note:</strong> When a View clears focus the framework is trying 4536 * to give focus to the first focusable View from the top. Hence, if this 4537 * View is the first from the top that can take focus, then all callbacks 4538 * related to clearing focus will be invoked after wich the framework will 4539 * give focus to this view. 4540 * </p> 4541 */ 4542 public void clearFocus() { 4543 if (DBG) { 4544 System.out.println(this + " clearFocus()"); 4545 } 4546 4547 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 4548 mPrivateFlags &= ~PFLAG_FOCUSED; 4549 4550 if (mParent != null) { 4551 mParent.clearChildFocus(this); 4552 } 4553 4554 onFocusChanged(false, 0, null); 4555 4556 refreshDrawableState(); 4557 4558 if (!rootViewRequestFocus()) { 4559 notifyGlobalFocusCleared(this); 4560 } 4561 } 4562 } 4563 4564 void notifyGlobalFocusCleared(View oldFocus) { 4565 if (oldFocus != null && mAttachInfo != null) { 4566 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null); 4567 } 4568 } 4569 4570 boolean rootViewRequestFocus() { 4571 View root = getRootView(); 4572 if (root != null) { 4573 return root.requestFocus(); 4574 } 4575 return false; 4576 } 4577 4578 /** 4579 * Called internally by the view system when a new view is getting focus. 4580 * This is what clears the old focus. 4581 */ 4582 void unFocus() { 4583 if (DBG) { 4584 System.out.println(this + " unFocus()"); 4585 } 4586 4587 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 4588 mPrivateFlags &= ~PFLAG_FOCUSED; 4589 4590 onFocusChanged(false, 0, null); 4591 refreshDrawableState(); 4592 } 4593 } 4594 4595 /** 4596 * Returns true if this view has focus iteself, or is the ancestor of the 4597 * view that has focus. 4598 * 4599 * @return True if this view has or contains focus, false otherwise. 4600 */ 4601 @ViewDebug.ExportedProperty(category = "focus") 4602 public boolean hasFocus() { 4603 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 4604 } 4605 4606 /** 4607 * Returns true if this view is focusable or if it contains a reachable View 4608 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 4609 * is a View whose parents do not block descendants focus. 4610 * 4611 * Only {@link #VISIBLE} views are considered focusable. 4612 * 4613 * @return True if the view is focusable or if the view contains a focusable 4614 * View, false otherwise. 4615 * 4616 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 4617 */ 4618 public boolean hasFocusable() { 4619 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 4620 } 4621 4622 /** 4623 * Called by the view system when the focus state of this view changes. 4624 * When the focus change event is caused by directional navigation, direction 4625 * and previouslyFocusedRect provide insight into where the focus is coming from. 4626 * When overriding, be sure to call up through to the super class so that 4627 * the standard focus handling will occur. 4628 * 4629 * @param gainFocus True if the View has focus; false otherwise. 4630 * @param direction The direction focus has moved when requestFocus() 4631 * is called to give this view focus. Values are 4632 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 4633 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 4634 * It may not always apply, in which case use the default. 4635 * @param previouslyFocusedRect The rectangle, in this view's coordinate 4636 * system, of the previously focused view. If applicable, this will be 4637 * passed in as finer grained information about where the focus is coming 4638 * from (in addition to direction). Will be <code>null</code> otherwise. 4639 */ 4640 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) { 4641 if (gainFocus) { 4642 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 4643 } else { 4644 notifyViewAccessibilityStateChangedIfNeeded(); 4645 } 4646 4647 InputMethodManager imm = InputMethodManager.peekInstance(); 4648 if (!gainFocus) { 4649 if (isPressed()) { 4650 setPressed(false); 4651 } 4652 if (imm != null && mAttachInfo != null 4653 && mAttachInfo.mHasWindowFocus) { 4654 imm.focusOut(this); 4655 } 4656 onFocusLost(); 4657 } else if (imm != null && mAttachInfo != null 4658 && mAttachInfo.mHasWindowFocus) { 4659 imm.focusIn(this); 4660 } 4661 4662 invalidate(true); 4663 ListenerInfo li = mListenerInfo; 4664 if (li != null && li.mOnFocusChangeListener != null) { 4665 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 4666 } 4667 4668 if (mAttachInfo != null) { 4669 mAttachInfo.mKeyDispatchState.reset(this); 4670 } 4671 } 4672 4673 /** 4674 * Sends an accessibility event of the given type. If accessibility is 4675 * not enabled this method has no effect. The default implementation calls 4676 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 4677 * to populate information about the event source (this View), then calls 4678 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 4679 * populate the text content of the event source including its descendants, 4680 * and last calls 4681 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 4682 * on its parent to resuest sending of the event to interested parties. 4683 * <p> 4684 * If an {@link AccessibilityDelegate} has been specified via calling 4685 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4686 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 4687 * responsible for handling this call. 4688 * </p> 4689 * 4690 * @param eventType The type of the event to send, as defined by several types from 4691 * {@link android.view.accessibility.AccessibilityEvent}, such as 4692 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 4693 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 4694 * 4695 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 4696 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4697 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 4698 * @see AccessibilityDelegate 4699 */ 4700 public void sendAccessibilityEvent(int eventType) { 4701 // Excluded views do not send accessibility events. 4702 if (!includeForAccessibility()) { 4703 return; 4704 } 4705 if (mAccessibilityDelegate != null) { 4706 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 4707 } else { 4708 sendAccessibilityEventInternal(eventType); 4709 } 4710 } 4711 4712 /** 4713 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 4714 * {@link AccessibilityEvent} to make an announcement which is related to some 4715 * sort of a context change for which none of the events representing UI transitions 4716 * is a good fit. For example, announcing a new page in a book. If accessibility 4717 * is not enabled this method does nothing. 4718 * 4719 * @param text The announcement text. 4720 */ 4721 public void announceForAccessibility(CharSequence text) { 4722 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) { 4723 AccessibilityEvent event = AccessibilityEvent.obtain( 4724 AccessibilityEvent.TYPE_ANNOUNCEMENT); 4725 onInitializeAccessibilityEvent(event); 4726 event.getText().add(text); 4727 event.setContentDescription(null); 4728 mParent.requestSendAccessibilityEvent(this, event); 4729 } 4730 } 4731 4732 /** 4733 * @see #sendAccessibilityEvent(int) 4734 * 4735 * Note: Called from the default {@link AccessibilityDelegate}. 4736 */ 4737 void sendAccessibilityEventInternal(int eventType) { 4738 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 4739 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 4740 } 4741 } 4742 4743 /** 4744 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 4745 * takes as an argument an empty {@link AccessibilityEvent} and does not 4746 * perform a check whether accessibility is enabled. 4747 * <p> 4748 * If an {@link AccessibilityDelegate} has been specified via calling 4749 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4750 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 4751 * is responsible for handling this call. 4752 * </p> 4753 * 4754 * @param event The event to send. 4755 * 4756 * @see #sendAccessibilityEvent(int) 4757 */ 4758 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 4759 if (mAccessibilityDelegate != null) { 4760 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 4761 } else { 4762 sendAccessibilityEventUncheckedInternal(event); 4763 } 4764 } 4765 4766 /** 4767 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 4768 * 4769 * Note: Called from the default {@link AccessibilityDelegate}. 4770 */ 4771 void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 4772 if (!isShown()) { 4773 return; 4774 } 4775 onInitializeAccessibilityEvent(event); 4776 // Only a subset of accessibility events populates text content. 4777 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 4778 dispatchPopulateAccessibilityEvent(event); 4779 } 4780 // In the beginning we called #isShown(), so we know that getParent() is not null. 4781 getParent().requestSendAccessibilityEvent(this, event); 4782 } 4783 4784 /** 4785 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 4786 * to its children for adding their text content to the event. Note that the 4787 * event text is populated in a separate dispatch path since we add to the 4788 * event not only the text of the source but also the text of all its descendants. 4789 * A typical implementation will call 4790 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 4791 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 4792 * on each child. Override this method if custom population of the event text 4793 * content is required. 4794 * <p> 4795 * If an {@link AccessibilityDelegate} has been specified via calling 4796 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4797 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 4798 * is responsible for handling this call. 4799 * </p> 4800 * <p> 4801 * <em>Note:</em> Accessibility events of certain types are not dispatched for 4802 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 4803 * </p> 4804 * 4805 * @param event The event. 4806 * 4807 * @return True if the event population was completed. 4808 */ 4809 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 4810 if (mAccessibilityDelegate != null) { 4811 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 4812 } else { 4813 return dispatchPopulateAccessibilityEventInternal(event); 4814 } 4815 } 4816 4817 /** 4818 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4819 * 4820 * Note: Called from the default {@link AccessibilityDelegate}. 4821 */ 4822 boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 4823 onPopulateAccessibilityEvent(event); 4824 return false; 4825 } 4826 4827 /** 4828 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 4829 * giving a chance to this View to populate the accessibility event with its 4830 * text content. While this method is free to modify event 4831 * attributes other than text content, doing so should normally be performed in 4832 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 4833 * <p> 4834 * Example: Adding formatted date string to an accessibility event in addition 4835 * to the text added by the super implementation: 4836 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 4837 * super.onPopulateAccessibilityEvent(event); 4838 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 4839 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 4840 * mCurrentDate.getTimeInMillis(), flags); 4841 * event.getText().add(selectedDateUtterance); 4842 * }</pre> 4843 * <p> 4844 * If an {@link AccessibilityDelegate} has been specified via calling 4845 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4846 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 4847 * is responsible for handling this call. 4848 * </p> 4849 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 4850 * information to the event, in case the default implementation has basic information to add. 4851 * </p> 4852 * 4853 * @param event The accessibility event which to populate. 4854 * 4855 * @see #sendAccessibilityEvent(int) 4856 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4857 */ 4858 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 4859 if (mAccessibilityDelegate != null) { 4860 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 4861 } else { 4862 onPopulateAccessibilityEventInternal(event); 4863 } 4864 } 4865 4866 /** 4867 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 4868 * 4869 * Note: Called from the default {@link AccessibilityDelegate}. 4870 */ 4871 void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 4872 4873 } 4874 4875 /** 4876 * Initializes an {@link AccessibilityEvent} with information about 4877 * this View which is the event source. In other words, the source of 4878 * an accessibility event is the view whose state change triggered firing 4879 * the event. 4880 * <p> 4881 * Example: Setting the password property of an event in addition 4882 * to properties set by the super implementation: 4883 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 4884 * super.onInitializeAccessibilityEvent(event); 4885 * event.setPassword(true); 4886 * }</pre> 4887 * <p> 4888 * If an {@link AccessibilityDelegate} has been specified via calling 4889 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4890 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 4891 * is responsible for handling this call. 4892 * </p> 4893 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 4894 * information to the event, in case the default implementation has basic information to add. 4895 * </p> 4896 * @param event The event to initialize. 4897 * 4898 * @see #sendAccessibilityEvent(int) 4899 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4900 */ 4901 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 4902 if (mAccessibilityDelegate != null) { 4903 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 4904 } else { 4905 onInitializeAccessibilityEventInternal(event); 4906 } 4907 } 4908 4909 /** 4910 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 4911 * 4912 * Note: Called from the default {@link AccessibilityDelegate}. 4913 */ 4914 void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 4915 event.setSource(this); 4916 event.setClassName(View.class.getName()); 4917 event.setPackageName(getContext().getPackageName()); 4918 event.setEnabled(isEnabled()); 4919 event.setContentDescription(mContentDescription); 4920 4921 switch (event.getEventType()) { 4922 case AccessibilityEvent.TYPE_VIEW_FOCUSED: { 4923 ArrayList<View> focusablesTempList = (mAttachInfo != null) 4924 ? mAttachInfo.mTempArrayList : new ArrayList<View>(); 4925 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL); 4926 event.setItemCount(focusablesTempList.size()); 4927 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 4928 if (mAttachInfo != null) { 4929 focusablesTempList.clear(); 4930 } 4931 } break; 4932 case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: { 4933 CharSequence text = getIterableTextForAccessibility(); 4934 if (text != null && text.length() > 0) { 4935 event.setFromIndex(getAccessibilitySelectionStart()); 4936 event.setToIndex(getAccessibilitySelectionEnd()); 4937 event.setItemCount(text.length()); 4938 } 4939 } break; 4940 } 4941 } 4942 4943 /** 4944 * Returns an {@link AccessibilityNodeInfo} representing this view from the 4945 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 4946 * This method is responsible for obtaining an accessibility node info from a 4947 * pool of reusable instances and calling 4948 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 4949 * initialize the former. 4950 * <p> 4951 * Note: The client is responsible for recycling the obtained instance by calling 4952 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 4953 * </p> 4954 * 4955 * @return A populated {@link AccessibilityNodeInfo}. 4956 * 4957 * @see AccessibilityNodeInfo 4958 */ 4959 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 4960 if (mAccessibilityDelegate != null) { 4961 return mAccessibilityDelegate.createAccessibilityNodeInfo(this); 4962 } else { 4963 return createAccessibilityNodeInfoInternal(); 4964 } 4965 } 4966 4967 /** 4968 * @see #createAccessibilityNodeInfo() 4969 */ 4970 AccessibilityNodeInfo createAccessibilityNodeInfoInternal() { 4971 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 4972 if (provider != null) { 4973 return provider.createAccessibilityNodeInfo(View.NO_ID); 4974 } else { 4975 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 4976 onInitializeAccessibilityNodeInfo(info); 4977 return info; 4978 } 4979 } 4980 4981 /** 4982 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 4983 * The base implementation sets: 4984 * <ul> 4985 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 4986 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 4987 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 4988 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 4989 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 4990 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 4991 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 4992 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 4993 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 4994 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 4995 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 4996 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 4997 * </ul> 4998 * <p> 4999 * Subclasses should override this method, call the super implementation, 5000 * and set additional attributes. 5001 * </p> 5002 * <p> 5003 * If an {@link AccessibilityDelegate} has been specified via calling 5004 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5005 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 5006 * is responsible for handling this call. 5007 * </p> 5008 * 5009 * @param info The instance to initialize. 5010 */ 5011 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 5012 if (mAccessibilityDelegate != null) { 5013 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 5014 } else { 5015 onInitializeAccessibilityNodeInfoInternal(info); 5016 } 5017 } 5018 5019 /** 5020 * Gets the location of this view in screen coordintates. 5021 * 5022 * @param outRect The output location 5023 */ 5024 void getBoundsOnScreen(Rect outRect) { 5025 if (mAttachInfo == null) { 5026 return; 5027 } 5028 5029 RectF position = mAttachInfo.mTmpTransformRect; 5030 position.set(0, 0, mRight - mLeft, mBottom - mTop); 5031 5032 if (!hasIdentityMatrix()) { 5033 getMatrix().mapRect(position); 5034 } 5035 5036 position.offset(mLeft, mTop); 5037 5038 ViewParent parent = mParent; 5039 while (parent instanceof View) { 5040 View parentView = (View) parent; 5041 5042 position.offset(-parentView.mScrollX, -parentView.mScrollY); 5043 5044 if (!parentView.hasIdentityMatrix()) { 5045 parentView.getMatrix().mapRect(position); 5046 } 5047 5048 position.offset(parentView.mLeft, parentView.mTop); 5049 5050 parent = parentView.mParent; 5051 } 5052 5053 if (parent instanceof ViewRootImpl) { 5054 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 5055 position.offset(0, -viewRootImpl.mCurScrollY); 5056 } 5057 5058 position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 5059 5060 outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f), 5061 (int) (position.right + 0.5f), (int) (position.bottom + 0.5f)); 5062 } 5063 5064 /** 5065 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 5066 * 5067 * Note: Called from the default {@link AccessibilityDelegate}. 5068 */ 5069 void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 5070 Rect bounds = mAttachInfo.mTmpInvalRect; 5071 5072 getDrawingRect(bounds); 5073 info.setBoundsInParent(bounds); 5074 5075 getBoundsOnScreen(bounds); 5076 info.setBoundsInScreen(bounds); 5077 5078 ViewParent parent = getParentForAccessibility(); 5079 if (parent instanceof View) { 5080 info.setParent((View) parent); 5081 } 5082 5083 if (mID != View.NO_ID) { 5084 View rootView = getRootView(); 5085 if (rootView == null) { 5086 rootView = this; 5087 } 5088 View label = rootView.findLabelForView(this, mID); 5089 if (label != null) { 5090 info.setLabeledBy(label); 5091 } 5092 5093 if ((mAttachInfo.mAccessibilityFetchFlags 5094 & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0 5095 && Resources.resourceHasPackage(mID)) { 5096 try { 5097 String viewId = getResources().getResourceName(mID); 5098 info.setViewIdResourceName(viewId); 5099 } catch (Resources.NotFoundException nfe) { 5100 /* ignore */ 5101 } 5102 } 5103 } 5104 5105 if (mLabelForId != View.NO_ID) { 5106 View rootView = getRootView(); 5107 if (rootView == null) { 5108 rootView = this; 5109 } 5110 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId); 5111 if (labeled != null) { 5112 info.setLabelFor(labeled); 5113 } 5114 } 5115 5116 info.setVisibleToUser(isVisibleToUser()); 5117 5118 info.setPackageName(mContext.getPackageName()); 5119 info.setClassName(View.class.getName()); 5120 info.setContentDescription(getContentDescription()); 5121 5122 info.setEnabled(isEnabled()); 5123 info.setClickable(isClickable()); 5124 info.setFocusable(isFocusable()); 5125 info.setFocused(isFocused()); 5126 info.setAccessibilityFocused(isAccessibilityFocused()); 5127 info.setSelected(isSelected()); 5128 info.setLongClickable(isLongClickable()); 5129 5130 // TODO: These make sense only if we are in an AdapterView but all 5131 // views can be selected. Maybe from accessibility perspective 5132 // we should report as selectable view in an AdapterView. 5133 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 5134 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 5135 5136 if (isFocusable()) { 5137 if (isFocused()) { 5138 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 5139 } else { 5140 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 5141 } 5142 } 5143 5144 if (!isAccessibilityFocused()) { 5145 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 5146 } else { 5147 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 5148 } 5149 5150 if (isClickable() && isEnabled()) { 5151 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 5152 } 5153 5154 if (isLongClickable() && isEnabled()) { 5155 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 5156 } 5157 5158 CharSequence text = getIterableTextForAccessibility(); 5159 if (text != null && text.length() > 0) { 5160 info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd()); 5161 5162 info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); 5163 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 5164 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 5165 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 5166 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 5167 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 5168 } 5169 } 5170 5171 private View findLabelForView(View view, int labeledId) { 5172 if (mMatchLabelForPredicate == null) { 5173 mMatchLabelForPredicate = new MatchLabelForPredicate(); 5174 } 5175 mMatchLabelForPredicate.mLabeledId = labeledId; 5176 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 5177 } 5178 5179 /** 5180 * Computes whether this view is visible to the user. Such a view is 5181 * attached, visible, all its predecessors are visible, it is not clipped 5182 * entirely by its predecessors, and has an alpha greater than zero. 5183 * 5184 * @return Whether the view is visible on the screen. 5185 * 5186 * @hide 5187 */ 5188 protected boolean isVisibleToUser() { 5189 return isVisibleToUser(null); 5190 } 5191 5192 /** 5193 * Computes whether the given portion of this view is visible to the user. 5194 * Such a view is attached, visible, all its predecessors are visible, 5195 * has an alpha greater than zero, and the specified portion is not 5196 * clipped entirely by its predecessors. 5197 * 5198 * @param boundInView the portion of the view to test; coordinates should be relative; may be 5199 * <code>null</code>, and the entire view will be tested in this case. 5200 * When <code>true</code> is returned by the function, the actual visible 5201 * region will be stored in this parameter; that is, if boundInView is fully 5202 * contained within the view, no modification will be made, otherwise regions 5203 * outside of the visible area of the view will be clipped. 5204 * 5205 * @return Whether the specified portion of the view is visible on the screen. 5206 * 5207 * @hide 5208 */ 5209 protected boolean isVisibleToUser(Rect boundInView) { 5210 if (mAttachInfo != null) { 5211 // Attached to invisible window means this view is not visible. 5212 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 5213 return false; 5214 } 5215 // An invisible predecessor or one with alpha zero means 5216 // that this view is not visible to the user. 5217 Object current = this; 5218 while (current instanceof View) { 5219 View view = (View) current; 5220 // We have attach info so this view is attached and there is no 5221 // need to check whether we reach to ViewRootImpl on the way up. 5222 if (view.getAlpha() <= 0 || view.getVisibility() != VISIBLE) { 5223 return false; 5224 } 5225 current = view.mParent; 5226 } 5227 // Check if the view is entirely covered by its predecessors. 5228 Rect visibleRect = mAttachInfo.mTmpInvalRect; 5229 Point offset = mAttachInfo.mPoint; 5230 if (!getGlobalVisibleRect(visibleRect, offset)) { 5231 return false; 5232 } 5233 // Check if the visible portion intersects the rectangle of interest. 5234 if (boundInView != null) { 5235 visibleRect.offset(-offset.x, -offset.y); 5236 return boundInView.intersect(visibleRect); 5237 } 5238 return true; 5239 } 5240 return false; 5241 } 5242 5243 /** 5244 * Returns the delegate for implementing accessibility support via 5245 * composition. For more details see {@link AccessibilityDelegate}. 5246 * 5247 * @return The delegate, or null if none set. 5248 * 5249 * @hide 5250 */ 5251 public AccessibilityDelegate getAccessibilityDelegate() { 5252 return mAccessibilityDelegate; 5253 } 5254 5255 /** 5256 * Sets a delegate for implementing accessibility support via composition as 5257 * opposed to inheritance. The delegate's primary use is for implementing 5258 * backwards compatible widgets. For more details see {@link AccessibilityDelegate}. 5259 * 5260 * @param delegate The delegate instance. 5261 * 5262 * @see AccessibilityDelegate 5263 */ 5264 public void setAccessibilityDelegate(AccessibilityDelegate delegate) { 5265 mAccessibilityDelegate = delegate; 5266 } 5267 5268 /** 5269 * Gets the provider for managing a virtual view hierarchy rooted at this View 5270 * and reported to {@link android.accessibilityservice.AccessibilityService}s 5271 * that explore the window content. 5272 * <p> 5273 * If this method returns an instance, this instance is responsible for managing 5274 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 5275 * View including the one representing the View itself. Similarly the returned 5276 * instance is responsible for performing accessibility actions on any virtual 5277 * view or the root view itself. 5278 * </p> 5279 * <p> 5280 * If an {@link AccessibilityDelegate} has been specified via calling 5281 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5282 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 5283 * is responsible for handling this call. 5284 * </p> 5285 * 5286 * @return The provider. 5287 * 5288 * @see AccessibilityNodeProvider 5289 */ 5290 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 5291 if (mAccessibilityDelegate != null) { 5292 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 5293 } else { 5294 return null; 5295 } 5296 } 5297 5298 /** 5299 * Gets the unique identifier of this view on the screen for accessibility purposes. 5300 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 5301 * 5302 * @return The view accessibility id. 5303 * 5304 * @hide 5305 */ 5306 public int getAccessibilityViewId() { 5307 if (mAccessibilityViewId == NO_ID) { 5308 mAccessibilityViewId = sNextAccessibilityViewId++; 5309 } 5310 return mAccessibilityViewId; 5311 } 5312 5313 /** 5314 * Gets the unique identifier of the window in which this View reseides. 5315 * 5316 * @return The window accessibility id. 5317 * 5318 * @hide 5319 */ 5320 public int getAccessibilityWindowId() { 5321 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID; 5322 } 5323 5324 /** 5325 * Gets the {@link View} description. It briefly describes the view and is 5326 * primarily used for accessibility support. Set this property to enable 5327 * better accessibility support for your application. This is especially 5328 * true for views that do not have textual representation (For example, 5329 * ImageButton). 5330 * 5331 * @return The content description. 5332 * 5333 * @attr ref android.R.styleable#View_contentDescription 5334 */ 5335 @ViewDebug.ExportedProperty(category = "accessibility") 5336 public CharSequence getContentDescription() { 5337 return mContentDescription; 5338 } 5339 5340 /** 5341 * Sets the {@link View} description. It briefly describes the view and is 5342 * primarily used for accessibility support. Set this property to enable 5343 * better accessibility support for your application. This is especially 5344 * true for views that do not have textual representation (For example, 5345 * ImageButton). 5346 * 5347 * @param contentDescription The content description. 5348 * 5349 * @attr ref android.R.styleable#View_contentDescription 5350 */ 5351 @RemotableViewMethod 5352 public void setContentDescription(CharSequence contentDescription) { 5353 if (mContentDescription == null) { 5354 if (contentDescription == null) { 5355 return; 5356 } 5357 } else if (mContentDescription.equals(contentDescription)) { 5358 return; 5359 } 5360 mContentDescription = contentDescription; 5361 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 5362 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 5363 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 5364 notifySubtreeAccessibilityStateChangedIfNeeded(); 5365 } else { 5366 notifyViewAccessibilityStateChangedIfNeeded(); 5367 } 5368 } 5369 5370 /** 5371 * Gets the id of a view for which this view serves as a label for 5372 * accessibility purposes. 5373 * 5374 * @return The labeled view id. 5375 */ 5376 @ViewDebug.ExportedProperty(category = "accessibility") 5377 public int getLabelFor() { 5378 return mLabelForId; 5379 } 5380 5381 /** 5382 * Sets the id of a view for which this view serves as a label for 5383 * accessibility purposes. 5384 * 5385 * @param id The labeled view id. 5386 */ 5387 @RemotableViewMethod 5388 public void setLabelFor(int id) { 5389 mLabelForId = id; 5390 if (mLabelForId != View.NO_ID 5391 && mID == View.NO_ID) { 5392 mID = generateViewId(); 5393 } 5394 } 5395 5396 /** 5397 * Invoked whenever this view loses focus, either by losing window focus or by losing 5398 * focus within its window. This method can be used to clear any state tied to the 5399 * focus. For instance, if a button is held pressed with the trackball and the window 5400 * loses focus, this method can be used to cancel the press. 5401 * 5402 * Subclasses of View overriding this method should always call super.onFocusLost(). 5403 * 5404 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 5405 * @see #onWindowFocusChanged(boolean) 5406 * 5407 * @hide pending API council approval 5408 */ 5409 protected void onFocusLost() { 5410 resetPressedState(); 5411 } 5412 5413 private void resetPressedState() { 5414 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 5415 return; 5416 } 5417 5418 if (isPressed()) { 5419 setPressed(false); 5420 5421 if (!mHasPerformedLongPress) { 5422 removeLongPressCallback(); 5423 } 5424 } 5425 } 5426 5427 /** 5428 * Returns true if this view has focus 5429 * 5430 * @return True if this view has focus, false otherwise. 5431 */ 5432 @ViewDebug.ExportedProperty(category = "focus") 5433 public boolean isFocused() { 5434 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 5435 } 5436 5437 /** 5438 * Find the view in the hierarchy rooted at this view that currently has 5439 * focus. 5440 * 5441 * @return The view that currently has focus, or null if no focused view can 5442 * be found. 5443 */ 5444 public View findFocus() { 5445 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 5446 } 5447 5448 /** 5449 * Indicates whether this view is one of the set of scrollable containers in 5450 * its window. 5451 * 5452 * @return whether this view is one of the set of scrollable containers in 5453 * its window 5454 * 5455 * @attr ref android.R.styleable#View_isScrollContainer 5456 */ 5457 public boolean isScrollContainer() { 5458 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 5459 } 5460 5461 /** 5462 * Change whether this view is one of the set of scrollable containers in 5463 * its window. This will be used to determine whether the window can 5464 * resize or must pan when a soft input area is open -- scrollable 5465 * containers allow the window to use resize mode since the container 5466 * will appropriately shrink. 5467 * 5468 * @attr ref android.R.styleable#View_isScrollContainer 5469 */ 5470 public void setScrollContainer(boolean isScrollContainer) { 5471 if (isScrollContainer) { 5472 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 5473 mAttachInfo.mScrollContainers.add(this); 5474 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 5475 } 5476 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 5477 } else { 5478 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 5479 mAttachInfo.mScrollContainers.remove(this); 5480 } 5481 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 5482 } 5483 } 5484 5485 /** 5486 * Returns the quality of the drawing cache. 5487 * 5488 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5489 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5490 * 5491 * @see #setDrawingCacheQuality(int) 5492 * @see #setDrawingCacheEnabled(boolean) 5493 * @see #isDrawingCacheEnabled() 5494 * 5495 * @attr ref android.R.styleable#View_drawingCacheQuality 5496 */ 5497 public int getDrawingCacheQuality() { 5498 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 5499 } 5500 5501 /** 5502 * Set the drawing cache quality of this view. This value is used only when the 5503 * drawing cache is enabled 5504 * 5505 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5506 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5507 * 5508 * @see #getDrawingCacheQuality() 5509 * @see #setDrawingCacheEnabled(boolean) 5510 * @see #isDrawingCacheEnabled() 5511 * 5512 * @attr ref android.R.styleable#View_drawingCacheQuality 5513 */ 5514 public void setDrawingCacheQuality(int quality) { 5515 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 5516 } 5517 5518 /** 5519 * Returns whether the screen should remain on, corresponding to the current 5520 * value of {@link #KEEP_SCREEN_ON}. 5521 * 5522 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 5523 * 5524 * @see #setKeepScreenOn(boolean) 5525 * 5526 * @attr ref android.R.styleable#View_keepScreenOn 5527 */ 5528 public boolean getKeepScreenOn() { 5529 return (mViewFlags & KEEP_SCREEN_ON) != 0; 5530 } 5531 5532 /** 5533 * Controls whether the screen should remain on, modifying the 5534 * value of {@link #KEEP_SCREEN_ON}. 5535 * 5536 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 5537 * 5538 * @see #getKeepScreenOn() 5539 * 5540 * @attr ref android.R.styleable#View_keepScreenOn 5541 */ 5542 public void setKeepScreenOn(boolean keepScreenOn) { 5543 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 5544 } 5545 5546 /** 5547 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5548 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5549 * 5550 * @attr ref android.R.styleable#View_nextFocusLeft 5551 */ 5552 public int getNextFocusLeftId() { 5553 return mNextFocusLeftId; 5554 } 5555 5556 /** 5557 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5558 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 5559 * decide automatically. 5560 * 5561 * @attr ref android.R.styleable#View_nextFocusLeft 5562 */ 5563 public void setNextFocusLeftId(int nextFocusLeftId) { 5564 mNextFocusLeftId = nextFocusLeftId; 5565 } 5566 5567 /** 5568 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5569 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5570 * 5571 * @attr ref android.R.styleable#View_nextFocusRight 5572 */ 5573 public int getNextFocusRightId() { 5574 return mNextFocusRightId; 5575 } 5576 5577 /** 5578 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5579 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 5580 * decide automatically. 5581 * 5582 * @attr ref android.R.styleable#View_nextFocusRight 5583 */ 5584 public void setNextFocusRightId(int nextFocusRightId) { 5585 mNextFocusRightId = nextFocusRightId; 5586 } 5587 5588 /** 5589 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 5590 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5591 * 5592 * @attr ref android.R.styleable#View_nextFocusUp 5593 */ 5594 public int getNextFocusUpId() { 5595 return mNextFocusUpId; 5596 } 5597 5598 /** 5599 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 5600 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 5601 * decide automatically. 5602 * 5603 * @attr ref android.R.styleable#View_nextFocusUp 5604 */ 5605 public void setNextFocusUpId(int nextFocusUpId) { 5606 mNextFocusUpId = nextFocusUpId; 5607 } 5608 5609 /** 5610 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 5611 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5612 * 5613 * @attr ref android.R.styleable#View_nextFocusDown 5614 */ 5615 public int getNextFocusDownId() { 5616 return mNextFocusDownId; 5617 } 5618 5619 /** 5620 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 5621 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 5622 * decide automatically. 5623 * 5624 * @attr ref android.R.styleable#View_nextFocusDown 5625 */ 5626 public void setNextFocusDownId(int nextFocusDownId) { 5627 mNextFocusDownId = nextFocusDownId; 5628 } 5629 5630 /** 5631 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 5632 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5633 * 5634 * @attr ref android.R.styleable#View_nextFocusForward 5635 */ 5636 public int getNextFocusForwardId() { 5637 return mNextFocusForwardId; 5638 } 5639 5640 /** 5641 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 5642 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 5643 * decide automatically. 5644 * 5645 * @attr ref android.R.styleable#View_nextFocusForward 5646 */ 5647 public void setNextFocusForwardId(int nextFocusForwardId) { 5648 mNextFocusForwardId = nextFocusForwardId; 5649 } 5650 5651 /** 5652 * Returns the visibility of this view and all of its ancestors 5653 * 5654 * @return True if this view and all of its ancestors are {@link #VISIBLE} 5655 */ 5656 public boolean isShown() { 5657 View current = this; 5658 //noinspection ConstantConditions 5659 do { 5660 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 5661 return false; 5662 } 5663 ViewParent parent = current.mParent; 5664 if (parent == null) { 5665 return false; // We are not attached to the view root 5666 } 5667 if (!(parent instanceof View)) { 5668 return true; 5669 } 5670 current = (View) parent; 5671 } while (current != null); 5672 5673 return false; 5674 } 5675 5676 /** 5677 * Called by the view hierarchy when the content insets for a window have 5678 * changed, to allow it to adjust its content to fit within those windows. 5679 * The content insets tell you the space that the status bar, input method, 5680 * and other system windows infringe on the application's window. 5681 * 5682 * <p>You do not normally need to deal with this function, since the default 5683 * window decoration given to applications takes care of applying it to the 5684 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 5685 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 5686 * and your content can be placed under those system elements. You can then 5687 * use this method within your view hierarchy if you have parts of your UI 5688 * which you would like to ensure are not being covered. 5689 * 5690 * <p>The default implementation of this method simply applies the content 5691 * inset's to the view's padding, consuming that content (modifying the 5692 * insets to be 0), and returning true. This behavior is off by default, but can 5693 * be enabled through {@link #setFitsSystemWindows(boolean)}. 5694 * 5695 * <p>This function's traversal down the hierarchy is depth-first. The same content 5696 * insets object is propagated down the hierarchy, so any changes made to it will 5697 * be seen by all following views (including potentially ones above in 5698 * the hierarchy since this is a depth-first traversal). The first view 5699 * that returns true will abort the entire traversal. 5700 * 5701 * <p>The default implementation works well for a situation where it is 5702 * used with a container that covers the entire window, allowing it to 5703 * apply the appropriate insets to its content on all edges. If you need 5704 * a more complicated layout (such as two different views fitting system 5705 * windows, one on the top of the window, and one on the bottom), 5706 * you can override the method and handle the insets however you would like. 5707 * Note that the insets provided by the framework are always relative to the 5708 * far edges of the window, not accounting for the location of the called view 5709 * within that window. (In fact when this method is called you do not yet know 5710 * where the layout will place the view, as it is done before layout happens.) 5711 * 5712 * <p>Note: unlike many View methods, there is no dispatch phase to this 5713 * call. If you are overriding it in a ViewGroup and want to allow the 5714 * call to continue to your children, you must be sure to call the super 5715 * implementation. 5716 * 5717 * <p>Here is a sample layout that makes use of fitting system windows 5718 * to have controls for a video view placed inside of the window decorations 5719 * that it hides and shows. This can be used with code like the second 5720 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 5721 * 5722 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 5723 * 5724 * @param insets Current content insets of the window. Prior to 5725 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 5726 * the insets or else you and Android will be unhappy. 5727 * 5728 * @return Return true if this view applied the insets and it should not 5729 * continue propagating further down the hierarchy, false otherwise. 5730 * @see #getFitsSystemWindows() 5731 * @see #setFitsSystemWindows(boolean) 5732 * @see #setSystemUiVisibility(int) 5733 */ 5734 protected boolean fitSystemWindows(Rect insets) { 5735 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 5736 mUserPaddingStart = UNDEFINED_PADDING; 5737 mUserPaddingEnd = UNDEFINED_PADDING; 5738 Rect localInsets = sThreadLocal.get(); 5739 if (localInsets == null) { 5740 localInsets = new Rect(); 5741 sThreadLocal.set(localInsets); 5742 } 5743 boolean res = computeFitSystemWindows(insets, localInsets); 5744 internalSetPadding(localInsets.left, localInsets.top, 5745 localInsets.right, localInsets.bottom); 5746 return res; 5747 } 5748 return false; 5749 } 5750 5751 /** 5752 * @hide Compute the insets that should be consumed by this view and the ones 5753 * that should propagate to those under it. 5754 */ 5755 protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) { 5756 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 5757 || mAttachInfo == null 5758 || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0 5759 && !mAttachInfo.mOverscanRequested)) { 5760 outLocalInsets.set(inoutInsets); 5761 inoutInsets.set(0, 0, 0, 0); 5762 return true; 5763 } else { 5764 // The application wants to take care of fitting system window for 5765 // the content... however we still need to take care of any overscan here. 5766 final Rect overscan = mAttachInfo.mOverscanInsets; 5767 outLocalInsets.set(overscan); 5768 inoutInsets.left -= overscan.left; 5769 inoutInsets.top -= overscan.top; 5770 inoutInsets.right -= overscan.right; 5771 inoutInsets.bottom -= overscan.bottom; 5772 return false; 5773 } 5774 } 5775 5776 /** 5777 * Sets whether or not this view should account for system screen decorations 5778 * such as the status bar and inset its content; that is, controlling whether 5779 * the default implementation of {@link #fitSystemWindows(Rect)} will be 5780 * executed. See that method for more details. 5781 * 5782 * <p>Note that if you are providing your own implementation of 5783 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 5784 * flag to true -- your implementation will be overriding the default 5785 * implementation that checks this flag. 5786 * 5787 * @param fitSystemWindows If true, then the default implementation of 5788 * {@link #fitSystemWindows(Rect)} will be executed. 5789 * 5790 * @attr ref android.R.styleable#View_fitsSystemWindows 5791 * @see #getFitsSystemWindows() 5792 * @see #fitSystemWindows(Rect) 5793 * @see #setSystemUiVisibility(int) 5794 */ 5795 public void setFitsSystemWindows(boolean fitSystemWindows) { 5796 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 5797 } 5798 5799 /** 5800 * Check for state of {@link #setFitsSystemWindows(boolean). If this method 5801 * returns true, the default implementation of {@link #fitSystemWindows(Rect)} 5802 * will be executed. 5803 * 5804 * @return Returns true if the default implementation of 5805 * {@link #fitSystemWindows(Rect)} will be executed. 5806 * 5807 * @attr ref android.R.styleable#View_fitsSystemWindows 5808 * @see #setFitsSystemWindows() 5809 * @see #fitSystemWindows(Rect) 5810 * @see #setSystemUiVisibility(int) 5811 */ 5812 public boolean getFitsSystemWindows() { 5813 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 5814 } 5815 5816 /** @hide */ 5817 public boolean fitsSystemWindows() { 5818 return getFitsSystemWindows(); 5819 } 5820 5821 /** 5822 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 5823 */ 5824 public void requestFitSystemWindows() { 5825 if (mParent != null) { 5826 mParent.requestFitSystemWindows(); 5827 } 5828 } 5829 5830 /** 5831 * For use by PhoneWindow to make its own system window fitting optional. 5832 * @hide 5833 */ 5834 public void makeOptionalFitsSystemWindows() { 5835 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 5836 } 5837 5838 /** 5839 * Returns the visibility status for this view. 5840 * 5841 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 5842 * @attr ref android.R.styleable#View_visibility 5843 */ 5844 @ViewDebug.ExportedProperty(mapping = { 5845 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 5846 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 5847 @ViewDebug.IntToString(from = GONE, to = "GONE") 5848 }) 5849 public int getVisibility() { 5850 return mViewFlags & VISIBILITY_MASK; 5851 } 5852 5853 /** 5854 * Set the enabled state of this view. 5855 * 5856 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 5857 * @attr ref android.R.styleable#View_visibility 5858 */ 5859 @RemotableViewMethod 5860 public void setVisibility(int visibility) { 5861 setFlags(visibility, VISIBILITY_MASK); 5862 if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false); 5863 } 5864 5865 /** 5866 * Returns the enabled status for this view. The interpretation of the 5867 * enabled state varies by subclass. 5868 * 5869 * @return True if this view is enabled, false otherwise. 5870 */ 5871 @ViewDebug.ExportedProperty 5872 public boolean isEnabled() { 5873 return (mViewFlags & ENABLED_MASK) == ENABLED; 5874 } 5875 5876 /** 5877 * Set the enabled state of this view. The interpretation of the enabled 5878 * state varies by subclass. 5879 * 5880 * @param enabled True if this view is enabled, false otherwise. 5881 */ 5882 @RemotableViewMethod 5883 public void setEnabled(boolean enabled) { 5884 if (enabled == isEnabled()) return; 5885 5886 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 5887 5888 /* 5889 * The View most likely has to change its appearance, so refresh 5890 * the drawable state. 5891 */ 5892 refreshDrawableState(); 5893 5894 // Invalidate too, since the default behavior for views is to be 5895 // be drawn at 50% alpha rather than to change the drawable. 5896 invalidate(true); 5897 } 5898 5899 /** 5900 * Set whether this view can receive the focus. 5901 * 5902 * Setting this to false will also ensure that this view is not focusable 5903 * in touch mode. 5904 * 5905 * @param focusable If true, this view can receive the focus. 5906 * 5907 * @see #setFocusableInTouchMode(boolean) 5908 * @attr ref android.R.styleable#View_focusable 5909 */ 5910 public void setFocusable(boolean focusable) { 5911 if (!focusable) { 5912 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 5913 } 5914 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 5915 } 5916 5917 /** 5918 * Set whether this view can receive focus while in touch mode. 5919 * 5920 * Setting this to true will also ensure that this view is focusable. 5921 * 5922 * @param focusableInTouchMode If true, this view can receive the focus while 5923 * in touch mode. 5924 * 5925 * @see #setFocusable(boolean) 5926 * @attr ref android.R.styleable#View_focusableInTouchMode 5927 */ 5928 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 5929 // Focusable in touch mode should always be set before the focusable flag 5930 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 5931 // which, in touch mode, will not successfully request focus on this view 5932 // because the focusable in touch mode flag is not set 5933 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 5934 if (focusableInTouchMode) { 5935 setFlags(FOCUSABLE, FOCUSABLE_MASK); 5936 } 5937 } 5938 5939 /** 5940 * Set whether this view should have sound effects enabled for events such as 5941 * clicking and touching. 5942 * 5943 * <p>You may wish to disable sound effects for a view if you already play sounds, 5944 * for instance, a dial key that plays dtmf tones. 5945 * 5946 * @param soundEffectsEnabled whether sound effects are enabled for this view. 5947 * @see #isSoundEffectsEnabled() 5948 * @see #playSoundEffect(int) 5949 * @attr ref android.R.styleable#View_soundEffectsEnabled 5950 */ 5951 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 5952 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 5953 } 5954 5955 /** 5956 * @return whether this view should have sound effects enabled for events such as 5957 * clicking and touching. 5958 * 5959 * @see #setSoundEffectsEnabled(boolean) 5960 * @see #playSoundEffect(int) 5961 * @attr ref android.R.styleable#View_soundEffectsEnabled 5962 */ 5963 @ViewDebug.ExportedProperty 5964 public boolean isSoundEffectsEnabled() { 5965 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 5966 } 5967 5968 /** 5969 * Set whether this view should have haptic feedback for events such as 5970 * long presses. 5971 * 5972 * <p>You may wish to disable haptic feedback if your view already controls 5973 * its own haptic feedback. 5974 * 5975 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 5976 * @see #isHapticFeedbackEnabled() 5977 * @see #performHapticFeedback(int) 5978 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 5979 */ 5980 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 5981 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 5982 } 5983 5984 /** 5985 * @return whether this view should have haptic feedback enabled for events 5986 * long presses. 5987 * 5988 * @see #setHapticFeedbackEnabled(boolean) 5989 * @see #performHapticFeedback(int) 5990 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 5991 */ 5992 @ViewDebug.ExportedProperty 5993 public boolean isHapticFeedbackEnabled() { 5994 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 5995 } 5996 5997 /** 5998 * Returns the layout direction for this view. 5999 * 6000 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 6001 * {@link #LAYOUT_DIRECTION_RTL}, 6002 * {@link #LAYOUT_DIRECTION_INHERIT} or 6003 * {@link #LAYOUT_DIRECTION_LOCALE}. 6004 * 6005 * @attr ref android.R.styleable#View_layoutDirection 6006 * 6007 * @hide 6008 */ 6009 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6010 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 6011 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 6012 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 6013 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 6014 }) 6015 public int getRawLayoutDirection() { 6016 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 6017 } 6018 6019 /** 6020 * Set the layout direction for this view. This will propagate a reset of layout direction 6021 * resolution to the view's children and resolve layout direction for this view. 6022 * 6023 * @param layoutDirection the layout direction to set. Should be one of: 6024 * 6025 * {@link #LAYOUT_DIRECTION_LTR}, 6026 * {@link #LAYOUT_DIRECTION_RTL}, 6027 * {@link #LAYOUT_DIRECTION_INHERIT}, 6028 * {@link #LAYOUT_DIRECTION_LOCALE}. 6029 * 6030 * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution 6031 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 6032 * will return the default {@link #LAYOUT_DIRECTION_LTR}. 6033 * 6034 * @attr ref android.R.styleable#View_layoutDirection 6035 */ 6036 @RemotableViewMethod 6037 public void setLayoutDirection(int layoutDirection) { 6038 if (getRawLayoutDirection() != layoutDirection) { 6039 // Reset the current layout direction and the resolved one 6040 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 6041 resetRtlProperties(); 6042 // Set the new layout direction (filtered) 6043 mPrivateFlags2 |= 6044 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 6045 // We need to resolve all RTL properties as they all depend on layout direction 6046 resolveRtlPropertiesIfNeeded(); 6047 requestLayout(); 6048 invalidate(true); 6049 } 6050 } 6051 6052 /** 6053 * Returns the resolved layout direction for this view. 6054 * 6055 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 6056 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 6057 * 6058 * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version 6059 * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}. 6060 * 6061 * @attr ref android.R.styleable#View_layoutDirection 6062 */ 6063 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6064 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 6065 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 6066 }) 6067 public int getLayoutDirection() { 6068 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 6069 if (targetSdkVersion < JELLY_BEAN_MR1) { 6070 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 6071 return LAYOUT_DIRECTION_RESOLVED_DEFAULT; 6072 } 6073 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == 6074 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 6075 } 6076 6077 /** 6078 * Indicates whether or not this view's layout is right-to-left. This is resolved from 6079 * layout attribute and/or the inherited value from the parent 6080 * 6081 * @return true if the layout is right-to-left. 6082 * 6083 * @hide 6084 */ 6085 @ViewDebug.ExportedProperty(category = "layout") 6086 public boolean isLayoutRtl() { 6087 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 6088 } 6089 6090 /** 6091 * Indicates whether the view is currently tracking transient state that the 6092 * app should not need to concern itself with saving and restoring, but that 6093 * the framework should take special note to preserve when possible. 6094 * 6095 * <p>A view with transient state cannot be trivially rebound from an external 6096 * data source, such as an adapter binding item views in a list. This may be 6097 * because the view is performing an animation, tracking user selection 6098 * of content, or similar.</p> 6099 * 6100 * @return true if the view has transient state 6101 */ 6102 @ViewDebug.ExportedProperty(category = "layout") 6103 public boolean hasTransientState() { 6104 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 6105 } 6106 6107 /** 6108 * Set whether this view is currently tracking transient state that the 6109 * framework should attempt to preserve when possible. This flag is reference counted, 6110 * so every call to setHasTransientState(true) should be paired with a later call 6111 * to setHasTransientState(false). 6112 * 6113 * <p>A view with transient state cannot be trivially rebound from an external 6114 * data source, such as an adapter binding item views in a list. This may be 6115 * because the view is performing an animation, tracking user selection 6116 * of content, or similar.</p> 6117 * 6118 * @param hasTransientState true if this view has transient state 6119 */ 6120 public void setHasTransientState(boolean hasTransientState) { 6121 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 6122 mTransientStateCount - 1; 6123 if (mTransientStateCount < 0) { 6124 mTransientStateCount = 0; 6125 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 6126 "unmatched pair of setHasTransientState calls"); 6127 } else if ((hasTransientState && mTransientStateCount == 1) || 6128 (!hasTransientState && mTransientStateCount == 0)) { 6129 // update flag if we've just incremented up from 0 or decremented down to 0 6130 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 6131 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 6132 if (mParent != null) { 6133 try { 6134 mParent.childHasTransientStateChanged(this, hasTransientState); 6135 } catch (AbstractMethodError e) { 6136 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 6137 " does not fully implement ViewParent", e); 6138 } 6139 } 6140 } 6141 } 6142 6143 /** 6144 * If this view doesn't do any drawing on its own, set this flag to 6145 * allow further optimizations. By default, this flag is not set on 6146 * View, but could be set on some View subclasses such as ViewGroup. 6147 * 6148 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 6149 * you should clear this flag. 6150 * 6151 * @param willNotDraw whether or not this View draw on its own 6152 */ 6153 public void setWillNotDraw(boolean willNotDraw) { 6154 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 6155 } 6156 6157 /** 6158 * Returns whether or not this View draws on its own. 6159 * 6160 * @return true if this view has nothing to draw, false otherwise 6161 */ 6162 @ViewDebug.ExportedProperty(category = "drawing") 6163 public boolean willNotDraw() { 6164 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 6165 } 6166 6167 /** 6168 * When a View's drawing cache is enabled, drawing is redirected to an 6169 * offscreen bitmap. Some views, like an ImageView, must be able to 6170 * bypass this mechanism if they already draw a single bitmap, to avoid 6171 * unnecessary usage of the memory. 6172 * 6173 * @param willNotCacheDrawing true if this view does not cache its 6174 * drawing, false otherwise 6175 */ 6176 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 6177 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 6178 } 6179 6180 /** 6181 * Returns whether or not this View can cache its drawing or not. 6182 * 6183 * @return true if this view does not cache its drawing, false otherwise 6184 */ 6185 @ViewDebug.ExportedProperty(category = "drawing") 6186 public boolean willNotCacheDrawing() { 6187 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 6188 } 6189 6190 /** 6191 * Indicates whether this view reacts to click events or not. 6192 * 6193 * @return true if the view is clickable, false otherwise 6194 * 6195 * @see #setClickable(boolean) 6196 * @attr ref android.R.styleable#View_clickable 6197 */ 6198 @ViewDebug.ExportedProperty 6199 public boolean isClickable() { 6200 return (mViewFlags & CLICKABLE) == CLICKABLE; 6201 } 6202 6203 /** 6204 * Enables or disables click events for this view. When a view 6205 * is clickable it will change its state to "pressed" on every click. 6206 * Subclasses should set the view clickable to visually react to 6207 * user's clicks. 6208 * 6209 * @param clickable true to make the view clickable, false otherwise 6210 * 6211 * @see #isClickable() 6212 * @attr ref android.R.styleable#View_clickable 6213 */ 6214 public void setClickable(boolean clickable) { 6215 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 6216 } 6217 6218 /** 6219 * Indicates whether this view reacts to long click events or not. 6220 * 6221 * @return true if the view is long clickable, false otherwise 6222 * 6223 * @see #setLongClickable(boolean) 6224 * @attr ref android.R.styleable#View_longClickable 6225 */ 6226 public boolean isLongClickable() { 6227 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 6228 } 6229 6230 /** 6231 * Enables or disables long click events for this view. When a view is long 6232 * clickable it reacts to the user holding down the button for a longer 6233 * duration than a tap. This event can either launch the listener or a 6234 * context menu. 6235 * 6236 * @param longClickable true to make the view long clickable, false otherwise 6237 * @see #isLongClickable() 6238 * @attr ref android.R.styleable#View_longClickable 6239 */ 6240 public void setLongClickable(boolean longClickable) { 6241 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 6242 } 6243 6244 /** 6245 * Sets the pressed state for this view. 6246 * 6247 * @see #isClickable() 6248 * @see #setClickable(boolean) 6249 * 6250 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 6251 * the View's internal state from a previously set "pressed" state. 6252 */ 6253 public void setPressed(boolean pressed) { 6254 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 6255 6256 if (pressed) { 6257 mPrivateFlags |= PFLAG_PRESSED; 6258 } else { 6259 mPrivateFlags &= ~PFLAG_PRESSED; 6260 } 6261 6262 if (needsRefresh) { 6263 refreshDrawableState(); 6264 } 6265 dispatchSetPressed(pressed); 6266 } 6267 6268 /** 6269 * Dispatch setPressed to all of this View's children. 6270 * 6271 * @see #setPressed(boolean) 6272 * 6273 * @param pressed The new pressed state 6274 */ 6275 protected void dispatchSetPressed(boolean pressed) { 6276 } 6277 6278 /** 6279 * Indicates whether the view is currently in pressed state. Unless 6280 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 6281 * the pressed state. 6282 * 6283 * @see #setPressed(boolean) 6284 * @see #isClickable() 6285 * @see #setClickable(boolean) 6286 * 6287 * @return true if the view is currently pressed, false otherwise 6288 */ 6289 public boolean isPressed() { 6290 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 6291 } 6292 6293 /** 6294 * Indicates whether this view will save its state (that is, 6295 * whether its {@link #onSaveInstanceState} method will be called). 6296 * 6297 * @return Returns true if the view state saving is enabled, else false. 6298 * 6299 * @see #setSaveEnabled(boolean) 6300 * @attr ref android.R.styleable#View_saveEnabled 6301 */ 6302 public boolean isSaveEnabled() { 6303 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 6304 } 6305 6306 /** 6307 * Controls whether the saving of this view's state is 6308 * enabled (that is, whether its {@link #onSaveInstanceState} method 6309 * will be called). Note that even if freezing is enabled, the 6310 * view still must have an id assigned to it (via {@link #setId(int)}) 6311 * for its state to be saved. This flag can only disable the 6312 * saving of this view; any child views may still have their state saved. 6313 * 6314 * @param enabled Set to false to <em>disable</em> state saving, or true 6315 * (the default) to allow it. 6316 * 6317 * @see #isSaveEnabled() 6318 * @see #setId(int) 6319 * @see #onSaveInstanceState() 6320 * @attr ref android.R.styleable#View_saveEnabled 6321 */ 6322 public void setSaveEnabled(boolean enabled) { 6323 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 6324 } 6325 6326 /** 6327 * Gets whether the framework should discard touches when the view's 6328 * window is obscured by another visible window. 6329 * Refer to the {@link View} security documentation for more details. 6330 * 6331 * @return True if touch filtering is enabled. 6332 * 6333 * @see #setFilterTouchesWhenObscured(boolean) 6334 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6335 */ 6336 @ViewDebug.ExportedProperty 6337 public boolean getFilterTouchesWhenObscured() { 6338 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 6339 } 6340 6341 /** 6342 * Sets whether the framework should discard touches when the view's 6343 * window is obscured by another visible window. 6344 * Refer to the {@link View} security documentation for more details. 6345 * 6346 * @param enabled True if touch filtering should be enabled. 6347 * 6348 * @see #getFilterTouchesWhenObscured 6349 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6350 */ 6351 public void setFilterTouchesWhenObscured(boolean enabled) { 6352 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED, 6353 FILTER_TOUCHES_WHEN_OBSCURED); 6354 } 6355 6356 /** 6357 * Indicates whether the entire hierarchy under this view will save its 6358 * state when a state saving traversal occurs from its parent. The default 6359 * is true; if false, these views will not be saved unless 6360 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6361 * 6362 * @return Returns true if the view state saving from parent is enabled, else false. 6363 * 6364 * @see #setSaveFromParentEnabled(boolean) 6365 */ 6366 public boolean isSaveFromParentEnabled() { 6367 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 6368 } 6369 6370 /** 6371 * Controls whether the entire hierarchy under this view will save its 6372 * state when a state saving traversal occurs from its parent. The default 6373 * is true; if false, these views will not be saved unless 6374 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6375 * 6376 * @param enabled Set to false to <em>disable</em> state saving, or true 6377 * (the default) to allow it. 6378 * 6379 * @see #isSaveFromParentEnabled() 6380 * @see #setId(int) 6381 * @see #onSaveInstanceState() 6382 */ 6383 public void setSaveFromParentEnabled(boolean enabled) { 6384 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 6385 } 6386 6387 6388 /** 6389 * Returns whether this View is able to take focus. 6390 * 6391 * @return True if this view can take focus, or false otherwise. 6392 * @attr ref android.R.styleable#View_focusable 6393 */ 6394 @ViewDebug.ExportedProperty(category = "focus") 6395 public final boolean isFocusable() { 6396 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 6397 } 6398 6399 /** 6400 * When a view is focusable, it may not want to take focus when in touch mode. 6401 * For example, a button would like focus when the user is navigating via a D-pad 6402 * so that the user can click on it, but once the user starts touching the screen, 6403 * the button shouldn't take focus 6404 * @return Whether the view is focusable in touch mode. 6405 * @attr ref android.R.styleable#View_focusableInTouchMode 6406 */ 6407 @ViewDebug.ExportedProperty 6408 public final boolean isFocusableInTouchMode() { 6409 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 6410 } 6411 6412 /** 6413 * Find the nearest view in the specified direction that can take focus. 6414 * This does not actually give focus to that view. 6415 * 6416 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 6417 * 6418 * @return The nearest focusable in the specified direction, or null if none 6419 * can be found. 6420 */ 6421 public View focusSearch(int direction) { 6422 if (mParent != null) { 6423 return mParent.focusSearch(this, direction); 6424 } else { 6425 return null; 6426 } 6427 } 6428 6429 /** 6430 * This method is the last chance for the focused view and its ancestors to 6431 * respond to an arrow key. This is called when the focused view did not 6432 * consume the key internally, nor could the view system find a new view in 6433 * the requested direction to give focus to. 6434 * 6435 * @param focused The currently focused view. 6436 * @param direction The direction focus wants to move. One of FOCUS_UP, 6437 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 6438 * @return True if the this view consumed this unhandled move. 6439 */ 6440 public boolean dispatchUnhandledMove(View focused, int direction) { 6441 return false; 6442 } 6443 6444 /** 6445 * If a user manually specified the next view id for a particular direction, 6446 * use the root to look up the view. 6447 * @param root The root view of the hierarchy containing this view. 6448 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 6449 * or FOCUS_BACKWARD. 6450 * @return The user specified next view, or null if there is none. 6451 */ 6452 View findUserSetNextFocus(View root, int direction) { 6453 switch (direction) { 6454 case FOCUS_LEFT: 6455 if (mNextFocusLeftId == View.NO_ID) return null; 6456 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 6457 case FOCUS_RIGHT: 6458 if (mNextFocusRightId == View.NO_ID) return null; 6459 return findViewInsideOutShouldExist(root, mNextFocusRightId); 6460 case FOCUS_UP: 6461 if (mNextFocusUpId == View.NO_ID) return null; 6462 return findViewInsideOutShouldExist(root, mNextFocusUpId); 6463 case FOCUS_DOWN: 6464 if (mNextFocusDownId == View.NO_ID) return null; 6465 return findViewInsideOutShouldExist(root, mNextFocusDownId); 6466 case FOCUS_FORWARD: 6467 if (mNextFocusForwardId == View.NO_ID) return null; 6468 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 6469 case FOCUS_BACKWARD: { 6470 if (mID == View.NO_ID) return null; 6471 final int id = mID; 6472 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 6473 @Override 6474 public boolean apply(View t) { 6475 return t.mNextFocusForwardId == id; 6476 } 6477 }); 6478 } 6479 } 6480 return null; 6481 } 6482 6483 private View findViewInsideOutShouldExist(View root, int id) { 6484 if (mMatchIdPredicate == null) { 6485 mMatchIdPredicate = new MatchIdPredicate(); 6486 } 6487 mMatchIdPredicate.mId = id; 6488 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 6489 if (result == null) { 6490 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 6491 } 6492 return result; 6493 } 6494 6495 /** 6496 * Find and return all focusable views that are descendants of this view, 6497 * possibly including this view if it is focusable itself. 6498 * 6499 * @param direction The direction of the focus 6500 * @return A list of focusable views 6501 */ 6502 public ArrayList<View> getFocusables(int direction) { 6503 ArrayList<View> result = new ArrayList<View>(24); 6504 addFocusables(result, direction); 6505 return result; 6506 } 6507 6508 /** 6509 * Add any focusable views that are descendants of this view (possibly 6510 * including this view if it is focusable itself) to views. If we are in touch mode, 6511 * only add views that are also focusable in touch mode. 6512 * 6513 * @param views Focusable views found so far 6514 * @param direction The direction of the focus 6515 */ 6516 public void addFocusables(ArrayList<View> views, int direction) { 6517 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 6518 } 6519 6520 /** 6521 * Adds any focusable views that are descendants of this view (possibly 6522 * including this view if it is focusable itself) to views. This method 6523 * adds all focusable views regardless if we are in touch mode or 6524 * only views focusable in touch mode if we are in touch mode or 6525 * only views that can take accessibility focus if accessibility is enabeld 6526 * depending on the focusable mode paramater. 6527 * 6528 * @param views Focusable views found so far or null if all we are interested is 6529 * the number of focusables. 6530 * @param direction The direction of the focus. 6531 * @param focusableMode The type of focusables to be added. 6532 * 6533 * @see #FOCUSABLES_ALL 6534 * @see #FOCUSABLES_TOUCH_MODE 6535 */ 6536 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { 6537 if (views == null) { 6538 return; 6539 } 6540 if (!isFocusable()) { 6541 return; 6542 } 6543 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 6544 && isInTouchMode() && !isFocusableInTouchMode()) { 6545 return; 6546 } 6547 views.add(this); 6548 } 6549 6550 /** 6551 * Finds the Views that contain given text. The containment is case insensitive. 6552 * The search is performed by either the text that the View renders or the content 6553 * description that describes the view for accessibility purposes and the view does 6554 * not render or both. Clients can specify how the search is to be performed via 6555 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 6556 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 6557 * 6558 * @param outViews The output list of matching Views. 6559 * @param searched The text to match against. 6560 * 6561 * @see #FIND_VIEWS_WITH_TEXT 6562 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 6563 * @see #setContentDescription(CharSequence) 6564 */ 6565 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) { 6566 if (getAccessibilityNodeProvider() != null) { 6567 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 6568 outViews.add(this); 6569 } 6570 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 6571 && (searched != null && searched.length() > 0) 6572 && (mContentDescription != null && mContentDescription.length() > 0)) { 6573 String searchedLowerCase = searched.toString().toLowerCase(); 6574 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 6575 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 6576 outViews.add(this); 6577 } 6578 } 6579 } 6580 6581 /** 6582 * Find and return all touchable views that are descendants of this view, 6583 * possibly including this view if it is touchable itself. 6584 * 6585 * @return A list of touchable views 6586 */ 6587 public ArrayList<View> getTouchables() { 6588 ArrayList<View> result = new ArrayList<View>(); 6589 addTouchables(result); 6590 return result; 6591 } 6592 6593 /** 6594 * Add any touchable views that are descendants of this view (possibly 6595 * including this view if it is touchable itself) to views. 6596 * 6597 * @param views Touchable views found so far 6598 */ 6599 public void addTouchables(ArrayList<View> views) { 6600 final int viewFlags = mViewFlags; 6601 6602 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 6603 && (viewFlags & ENABLED_MASK) == ENABLED) { 6604 views.add(this); 6605 } 6606 } 6607 6608 /** 6609 * Returns whether this View is accessibility focused. 6610 * 6611 * @return True if this View is accessibility focused. 6612 */ 6613 boolean isAccessibilityFocused() { 6614 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 6615 } 6616 6617 /** 6618 * Call this to try to give accessibility focus to this view. 6619 * 6620 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 6621 * returns false or the view is no visible or the view already has accessibility 6622 * focus. 6623 * 6624 * See also {@link #focusSearch(int)}, which is what you call to say that you 6625 * have focus, and you want your parent to look for the next one. 6626 * 6627 * @return Whether this view actually took accessibility focus. 6628 * 6629 * @hide 6630 */ 6631 public boolean requestAccessibilityFocus() { 6632 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 6633 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 6634 return false; 6635 } 6636 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 6637 return false; 6638 } 6639 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 6640 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 6641 ViewRootImpl viewRootImpl = getViewRootImpl(); 6642 if (viewRootImpl != null) { 6643 viewRootImpl.setAccessibilityFocus(this, null); 6644 } 6645 invalidate(); 6646 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 6647 return true; 6648 } 6649 return false; 6650 } 6651 6652 /** 6653 * Call this to try to clear accessibility focus of this view. 6654 * 6655 * See also {@link #focusSearch(int)}, which is what you call to say that you 6656 * have focus, and you want your parent to look for the next one. 6657 * 6658 * @hide 6659 */ 6660 public void clearAccessibilityFocus() { 6661 clearAccessibilityFocusNoCallbacks(); 6662 // Clear the global reference of accessibility focus if this 6663 // view or any of its descendants had accessibility focus. 6664 ViewRootImpl viewRootImpl = getViewRootImpl(); 6665 if (viewRootImpl != null) { 6666 View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 6667 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 6668 viewRootImpl.setAccessibilityFocus(null, null); 6669 } 6670 } 6671 } 6672 6673 private void sendAccessibilityHoverEvent(int eventType) { 6674 // Since we are not delivering to a client accessibility events from not 6675 // important views (unless the clinet request that) we need to fire the 6676 // event from the deepest view exposed to the client. As a consequence if 6677 // the user crosses a not exposed view the client will see enter and exit 6678 // of the exposed predecessor followed by and enter and exit of that same 6679 // predecessor when entering and exiting the not exposed descendant. This 6680 // is fine since the client has a clear idea which view is hovered at the 6681 // price of a couple more events being sent. This is a simple and 6682 // working solution. 6683 View source = this; 6684 while (true) { 6685 if (source.includeForAccessibility()) { 6686 source.sendAccessibilityEvent(eventType); 6687 return; 6688 } 6689 ViewParent parent = source.getParent(); 6690 if (parent instanceof View) { 6691 source = (View) parent; 6692 } else { 6693 return; 6694 } 6695 } 6696 } 6697 6698 /** 6699 * Clears accessibility focus without calling any callback methods 6700 * normally invoked in {@link #clearAccessibilityFocus()}. This method 6701 * is used for clearing accessibility focus when giving this focus to 6702 * another view. 6703 */ 6704 void clearAccessibilityFocusNoCallbacks() { 6705 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 6706 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 6707 invalidate(); 6708 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 6709 } 6710 } 6711 6712 /** 6713 * Call this to try to give focus to a specific view or to one of its 6714 * descendants. 6715 * 6716 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 6717 * false), or if it is focusable and it is not focusable in touch mode 6718 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 6719 * 6720 * See also {@link #focusSearch(int)}, which is what you call to say that you 6721 * have focus, and you want your parent to look for the next one. 6722 * 6723 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 6724 * {@link #FOCUS_DOWN} and <code>null</code>. 6725 * 6726 * @return Whether this view or one of its descendants actually took focus. 6727 */ 6728 public final boolean requestFocus() { 6729 return requestFocus(View.FOCUS_DOWN); 6730 } 6731 6732 /** 6733 * Call this to try to give focus to a specific view or to one of its 6734 * descendants and give it a hint about what direction focus is heading. 6735 * 6736 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 6737 * false), or if it is focusable and it is not focusable in touch mode 6738 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 6739 * 6740 * See also {@link #focusSearch(int)}, which is what you call to say that you 6741 * have focus, and you want your parent to look for the next one. 6742 * 6743 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 6744 * <code>null</code> set for the previously focused rectangle. 6745 * 6746 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 6747 * @return Whether this view or one of its descendants actually took focus. 6748 */ 6749 public final boolean requestFocus(int direction) { 6750 return requestFocus(direction, null); 6751 } 6752 6753 /** 6754 * Call this to try to give focus to a specific view or to one of its descendants 6755 * and give it hints about the direction and a specific rectangle that the focus 6756 * is coming from. The rectangle can help give larger views a finer grained hint 6757 * about where focus is coming from, and therefore, where to show selection, or 6758 * forward focus change internally. 6759 * 6760 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 6761 * false), or if it is focusable and it is not focusable in touch mode 6762 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 6763 * 6764 * A View will not take focus if it is not visible. 6765 * 6766 * A View will not take focus if one of its parents has 6767 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 6768 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 6769 * 6770 * See also {@link #focusSearch(int)}, which is what you call to say that you 6771 * have focus, and you want your parent to look for the next one. 6772 * 6773 * You may wish to override this method if your custom {@link View} has an internal 6774 * {@link View} that it wishes to forward the request to. 6775 * 6776 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 6777 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 6778 * to give a finer grained hint about where focus is coming from. May be null 6779 * if there is no hint. 6780 * @return Whether this view or one of its descendants actually took focus. 6781 */ 6782 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 6783 return requestFocusNoSearch(direction, previouslyFocusedRect); 6784 } 6785 6786 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 6787 // need to be focusable 6788 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 6789 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 6790 return false; 6791 } 6792 6793 // need to be focusable in touch mode if in touch mode 6794 if (isInTouchMode() && 6795 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 6796 return false; 6797 } 6798 6799 // need to not have any parents blocking us 6800 if (hasAncestorThatBlocksDescendantFocus()) { 6801 return false; 6802 } 6803 6804 handleFocusGainInternal(direction, previouslyFocusedRect); 6805 return true; 6806 } 6807 6808 /** 6809 * Call this to try to give focus to a specific view or to one of its descendants. This is a 6810 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 6811 * touch mode to request focus when they are touched. 6812 * 6813 * @return Whether this view or one of its descendants actually took focus. 6814 * 6815 * @see #isInTouchMode() 6816 * 6817 */ 6818 public final boolean requestFocusFromTouch() { 6819 // Leave touch mode if we need to 6820 if (isInTouchMode()) { 6821 ViewRootImpl viewRoot = getViewRootImpl(); 6822 if (viewRoot != null) { 6823 viewRoot.ensureTouchMode(false); 6824 } 6825 } 6826 return requestFocus(View.FOCUS_DOWN); 6827 } 6828 6829 /** 6830 * @return Whether any ancestor of this view blocks descendant focus. 6831 */ 6832 private boolean hasAncestorThatBlocksDescendantFocus() { 6833 ViewParent ancestor = mParent; 6834 while (ancestor instanceof ViewGroup) { 6835 final ViewGroup vgAncestor = (ViewGroup) ancestor; 6836 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) { 6837 return true; 6838 } else { 6839 ancestor = vgAncestor.getParent(); 6840 } 6841 } 6842 return false; 6843 } 6844 6845 /** 6846 * Gets the mode for determining whether this View is important for accessibility 6847 * which is if it fires accessibility events and if it is reported to 6848 * accessibility services that query the screen. 6849 * 6850 * @return The mode for determining whether a View is important for accessibility. 6851 * 6852 * @attr ref android.R.styleable#View_importantForAccessibility 6853 * 6854 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 6855 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 6856 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 6857 */ 6858 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 6859 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 6860 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 6861 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no") 6862 }) 6863 public int getImportantForAccessibility() { 6864 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 6865 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 6866 } 6867 6868 /** 6869 * Sets how to determine whether this view is important for accessibility 6870 * which is if it fires accessibility events and if it is reported to 6871 * accessibility services that query the screen. 6872 * 6873 * @param mode How to determine whether this view is important for accessibility. 6874 * 6875 * @attr ref android.R.styleable#View_importantForAccessibility 6876 * 6877 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 6878 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 6879 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 6880 */ 6881 public void setImportantForAccessibility(int mode) { 6882 final boolean oldIncludeForAccessibility = includeForAccessibility(); 6883 if (mode != getImportantForAccessibility()) { 6884 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 6885 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 6886 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 6887 if (oldIncludeForAccessibility != includeForAccessibility()) { 6888 notifySubtreeAccessibilityStateChangedIfNeeded(); 6889 } else { 6890 notifyViewAccessibilityStateChangedIfNeeded(); 6891 } 6892 } 6893 } 6894 6895 /** 6896 * Gets whether this view should be exposed for accessibility. 6897 * 6898 * @return Whether the view is exposed for accessibility. 6899 * 6900 * @hide 6901 */ 6902 public boolean isImportantForAccessibility() { 6903 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 6904 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 6905 switch (mode) { 6906 case IMPORTANT_FOR_ACCESSIBILITY_YES: 6907 return true; 6908 case IMPORTANT_FOR_ACCESSIBILITY_NO: 6909 return false; 6910 case IMPORTANT_FOR_ACCESSIBILITY_AUTO: 6911 return isActionableForAccessibility() || hasListenersForAccessibility() 6912 || getAccessibilityNodeProvider() != null; 6913 default: 6914 throw new IllegalArgumentException("Unknow important for accessibility mode: " 6915 + mode); 6916 } 6917 } 6918 6919 /** 6920 * Gets the parent for accessibility purposes. Note that the parent for 6921 * accessibility is not necessary the immediate parent. It is the first 6922 * predecessor that is important for accessibility. 6923 * 6924 * @return The parent for accessibility purposes. 6925 */ 6926 public ViewParent getParentForAccessibility() { 6927 if (mParent instanceof View) { 6928 View parentView = (View) mParent; 6929 if (parentView.includeForAccessibility()) { 6930 return mParent; 6931 } else { 6932 return mParent.getParentForAccessibility(); 6933 } 6934 } 6935 return null; 6936 } 6937 6938 /** 6939 * Adds the children of a given View for accessibility. Since some Views are 6940 * not important for accessibility the children for accessibility are not 6941 * necessarily direct children of the view, rather they are the first level of 6942 * descendants important for accessibility. 6943 * 6944 * @param children The list of children for accessibility. 6945 */ 6946 public void addChildrenForAccessibility(ArrayList<View> children) { 6947 if (includeForAccessibility()) { 6948 children.add(this); 6949 } 6950 } 6951 6952 /** 6953 * Whether to regard this view for accessibility. A view is regarded for 6954 * accessibility if it is important for accessibility or the querying 6955 * accessibility service has explicitly requested that view not 6956 * important for accessibility are regarded. 6957 * 6958 * @return Whether to regard the view for accessibility. 6959 * 6960 * @hide 6961 */ 6962 public boolean includeForAccessibility() { 6963 if (mAttachInfo != null) { 6964 return (mAttachInfo.mAccessibilityFetchFlags 6965 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0 6966 || isImportantForAccessibility(); 6967 } 6968 return false; 6969 } 6970 6971 /** 6972 * Returns whether the View is considered actionable from 6973 * accessibility perspective. Such view are important for 6974 * accessibility. 6975 * 6976 * @return True if the view is actionable for accessibility. 6977 * 6978 * @hide 6979 */ 6980 public boolean isActionableForAccessibility() { 6981 return (isClickable() || isLongClickable() || isFocusable()); 6982 } 6983 6984 /** 6985 * Returns whether the View has registered callbacks wich makes it 6986 * important for accessibility. 6987 * 6988 * @return True if the view is actionable for accessibility. 6989 */ 6990 private boolean hasListenersForAccessibility() { 6991 ListenerInfo info = getListenerInfo(); 6992 return mTouchDelegate != null || info.mOnKeyListener != null 6993 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 6994 || info.mOnHoverListener != null || info.mOnDragListener != null; 6995 } 6996 6997 /** 6998 * Notifies that the accessibility state of this view changed. The change 6999 * is local to this view and does not represent structural changes such 7000 * as children and parent. For example, the view became focusable. The 7001 * notification is at at most once every 7002 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7003 * to avoid unnecessary load to the system. Also once a view has a pending 7004 * notifucation this method is a NOP until the notification has been sent. 7005 * 7006 * @hide 7007 */ 7008 public void notifyViewAccessibilityStateChangedIfNeeded() { 7009 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7010 return; 7011 } 7012 if (mSendViewStateChangedAccessibilityEvent == null) { 7013 mSendViewStateChangedAccessibilityEvent = 7014 new SendViewStateChangedAccessibilityEvent(); 7015 } 7016 mSendViewStateChangedAccessibilityEvent.runOrPost(); 7017 } 7018 7019 /** 7020 * Notifies that the accessibility state of this view changed. The change 7021 * is *not* local to this view and does represent structural changes such 7022 * as children and parent. For example, the view size changed. The 7023 * notification is at at most once every 7024 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7025 * to avoid unnecessary load to the system. Also once a view has a pending 7026 * notifucation this method is a NOP until the notification has been sent. 7027 * 7028 * @hide 7029 */ 7030 private void notifySubtreeAccessibilityStateChangedIfNeeded() { 7031 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7032 return; 7033 } 7034 if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) { 7035 mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 7036 if (mParent != null) { 7037 mParent.childAccessibilityStateChanged(this); 7038 } 7039 } 7040 } 7041 7042 /** 7043 * Reset the flag indicating the accessibility state of the subtree rooted 7044 * at this view changed. 7045 */ 7046 void resetSubtreeAccessibilityStateChanged() { 7047 mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 7048 } 7049 7050 /** 7051 * Performs the specified accessibility action on the view. For 7052 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 7053 * <p> 7054 * If an {@link AccessibilityDelegate} has been specified via calling 7055 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 7056 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 7057 * is responsible for handling this call. 7058 * </p> 7059 * 7060 * @param action The action to perform. 7061 * @param arguments Optional action arguments. 7062 * @return Whether the action was performed. 7063 */ 7064 public boolean performAccessibilityAction(int action, Bundle arguments) { 7065 if (mAccessibilityDelegate != null) { 7066 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 7067 } else { 7068 return performAccessibilityActionInternal(action, arguments); 7069 } 7070 } 7071 7072 /** 7073 * @see #performAccessibilityAction(int, Bundle) 7074 * 7075 * Note: Called from the default {@link AccessibilityDelegate}. 7076 */ 7077 boolean performAccessibilityActionInternal(int action, Bundle arguments) { 7078 switch (action) { 7079 case AccessibilityNodeInfo.ACTION_CLICK: { 7080 if (isClickable()) { 7081 performClick(); 7082 return true; 7083 } 7084 } break; 7085 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 7086 if (isLongClickable()) { 7087 performLongClick(); 7088 return true; 7089 } 7090 } break; 7091 case AccessibilityNodeInfo.ACTION_FOCUS: { 7092 if (!hasFocus()) { 7093 // Get out of touch mode since accessibility 7094 // wants to move focus around. 7095 getViewRootImpl().ensureTouchMode(false); 7096 return requestFocus(); 7097 } 7098 } break; 7099 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 7100 if (hasFocus()) { 7101 clearFocus(); 7102 return !isFocused(); 7103 } 7104 } break; 7105 case AccessibilityNodeInfo.ACTION_SELECT: { 7106 if (!isSelected()) { 7107 setSelected(true); 7108 return isSelected(); 7109 } 7110 } break; 7111 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 7112 if (isSelected()) { 7113 setSelected(false); 7114 return !isSelected(); 7115 } 7116 } break; 7117 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 7118 if (!isAccessibilityFocused()) { 7119 return requestAccessibilityFocus(); 7120 } 7121 } break; 7122 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 7123 if (isAccessibilityFocused()) { 7124 clearAccessibilityFocus(); 7125 return true; 7126 } 7127 } break; 7128 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 7129 if (arguments != null) { 7130 final int granularity = arguments.getInt( 7131 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 7132 final boolean extendSelection = arguments.getBoolean( 7133 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 7134 return traverseAtGranularity(granularity, true, extendSelection); 7135 } 7136 } break; 7137 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 7138 if (arguments != null) { 7139 final int granularity = arguments.getInt( 7140 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 7141 final boolean extendSelection = arguments.getBoolean( 7142 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 7143 return traverseAtGranularity(granularity, false, extendSelection); 7144 } 7145 } break; 7146 case AccessibilityNodeInfo.ACTION_SET_SELECTION: { 7147 CharSequence text = getIterableTextForAccessibility(); 7148 if (text == null) { 7149 return false; 7150 } 7151 final int start = (arguments != null) ? arguments.getInt( 7152 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1; 7153 final int end = (arguments != null) ? arguments.getInt( 7154 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1; 7155 // Only cursor position can be specified (selection length == 0) 7156 if ((getAccessibilitySelectionStart() != start 7157 || getAccessibilitySelectionEnd() != end) 7158 && (start == end)) { 7159 setAccessibilitySelection(start, end); 7160 notifyViewAccessibilityStateChangedIfNeeded(); 7161 return true; 7162 } 7163 } break; 7164 } 7165 return false; 7166 } 7167 7168 private boolean traverseAtGranularity(int granularity, boolean forward, 7169 boolean extendSelection) { 7170 CharSequence text = getIterableTextForAccessibility(); 7171 if (text == null || text.length() == 0) { 7172 return false; 7173 } 7174 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 7175 if (iterator == null) { 7176 return false; 7177 } 7178 int current = getAccessibilitySelectionEnd(); 7179 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 7180 current = forward ? 0 : text.length(); 7181 } 7182 final int[] range = forward ? iterator.following(current) : iterator.preceding(current); 7183 if (range == null) { 7184 return false; 7185 } 7186 final int segmentStart = range[0]; 7187 final int segmentEnd = range[1]; 7188 int selectionStart; 7189 int selectionEnd; 7190 if (extendSelection && isAccessibilitySelectionExtendable()) { 7191 selectionStart = getAccessibilitySelectionStart(); 7192 if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 7193 selectionStart = forward ? segmentStart : segmentEnd; 7194 } 7195 selectionEnd = forward ? segmentEnd : segmentStart; 7196 } else { 7197 selectionStart = selectionEnd= forward ? segmentEnd : segmentStart; 7198 } 7199 setAccessibilitySelection(selectionStart, selectionEnd); 7200 final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY 7201 : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY; 7202 sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd); 7203 return true; 7204 } 7205 7206 /** 7207 * Gets the text reported for accessibility purposes. 7208 * 7209 * @return The accessibility text. 7210 * 7211 * @hide 7212 */ 7213 public CharSequence getIterableTextForAccessibility() { 7214 return getContentDescription(); 7215 } 7216 7217 /** 7218 * Gets whether accessibility selection can be extended. 7219 * 7220 * @return If selection is extensible. 7221 * 7222 * @hide 7223 */ 7224 public boolean isAccessibilitySelectionExtendable() { 7225 return false; 7226 } 7227 7228 /** 7229 * @hide 7230 */ 7231 public int getAccessibilitySelectionStart() { 7232 return mAccessibilityCursorPosition; 7233 } 7234 7235 /** 7236 * @hide 7237 */ 7238 public int getAccessibilitySelectionEnd() { 7239 return getAccessibilitySelectionStart(); 7240 } 7241 7242 /** 7243 * @hide 7244 */ 7245 public void setAccessibilitySelection(int start, int end) { 7246 if (start == end && end == mAccessibilityCursorPosition) { 7247 return; 7248 } 7249 if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) { 7250 mAccessibilityCursorPosition = start; 7251 } else { 7252 mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 7253 } 7254 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 7255 } 7256 7257 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 7258 int fromIndex, int toIndex) { 7259 if (mParent == null) { 7260 return; 7261 } 7262 AccessibilityEvent event = AccessibilityEvent.obtain( 7263 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 7264 onInitializeAccessibilityEvent(event); 7265 onPopulateAccessibilityEvent(event); 7266 event.setFromIndex(fromIndex); 7267 event.setToIndex(toIndex); 7268 event.setAction(action); 7269 event.setMovementGranularity(granularity); 7270 mParent.requestSendAccessibilityEvent(this, event); 7271 } 7272 7273 /** 7274 * @hide 7275 */ 7276 public TextSegmentIterator getIteratorForGranularity(int granularity) { 7277 switch (granularity) { 7278 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 7279 CharSequence text = getIterableTextForAccessibility(); 7280 if (text != null && text.length() > 0) { 7281 CharacterTextSegmentIterator iterator = 7282 CharacterTextSegmentIterator.getInstance( 7283 mContext.getResources().getConfiguration().locale); 7284 iterator.initialize(text.toString()); 7285 return iterator; 7286 } 7287 } break; 7288 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 7289 CharSequence text = getIterableTextForAccessibility(); 7290 if (text != null && text.length() > 0) { 7291 WordTextSegmentIterator iterator = 7292 WordTextSegmentIterator.getInstance( 7293 mContext.getResources().getConfiguration().locale); 7294 iterator.initialize(text.toString()); 7295 return iterator; 7296 } 7297 } break; 7298 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 7299 CharSequence text = getIterableTextForAccessibility(); 7300 if (text != null && text.length() > 0) { 7301 ParagraphTextSegmentIterator iterator = 7302 ParagraphTextSegmentIterator.getInstance(); 7303 iterator.initialize(text.toString()); 7304 return iterator; 7305 } 7306 } break; 7307 } 7308 return null; 7309 } 7310 7311 /** 7312 * @hide 7313 */ 7314 public void dispatchStartTemporaryDetach() { 7315 clearAccessibilityFocus(); 7316 clearDisplayList(); 7317 7318 onStartTemporaryDetach(); 7319 } 7320 7321 /** 7322 * This is called when a container is going to temporarily detach a child, with 7323 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 7324 * It will either be followed by {@link #onFinishTemporaryDetach()} or 7325 * {@link #onDetachedFromWindow()} when the container is done. 7326 */ 7327 public void onStartTemporaryDetach() { 7328 removeUnsetPressCallback(); 7329 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 7330 } 7331 7332 /** 7333 * @hide 7334 */ 7335 public void dispatchFinishTemporaryDetach() { 7336 onFinishTemporaryDetach(); 7337 } 7338 7339 /** 7340 * Called after {@link #onStartTemporaryDetach} when the container is done 7341 * changing the view. 7342 */ 7343 public void onFinishTemporaryDetach() { 7344 } 7345 7346 /** 7347 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 7348 * for this view's window. Returns null if the view is not currently attached 7349 * to the window. Normally you will not need to use this directly, but 7350 * just use the standard high-level event callbacks like 7351 * {@link #onKeyDown(int, KeyEvent)}. 7352 */ 7353 public KeyEvent.DispatcherState getKeyDispatcherState() { 7354 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 7355 } 7356 7357 /** 7358 * Dispatch a key event before it is processed by any input method 7359 * associated with the view hierarchy. This can be used to intercept 7360 * key events in special situations before the IME consumes them; a 7361 * typical example would be handling the BACK key to update the application's 7362 * UI instead of allowing the IME to see it and close itself. 7363 * 7364 * @param event The key event to be dispatched. 7365 * @return True if the event was handled, false otherwise. 7366 */ 7367 public boolean dispatchKeyEventPreIme(KeyEvent event) { 7368 return onKeyPreIme(event.getKeyCode(), event); 7369 } 7370 7371 /** 7372 * Dispatch a key event to the next view on the focus path. This path runs 7373 * from the top of the view tree down to the currently focused view. If this 7374 * view has focus, it will dispatch to itself. Otherwise it will dispatch 7375 * the next node down the focus path. This method also fires any key 7376 * listeners. 7377 * 7378 * @param event The key event to be dispatched. 7379 * @return True if the event was handled, false otherwise. 7380 */ 7381 public boolean dispatchKeyEvent(KeyEvent event) { 7382 if (mInputEventConsistencyVerifier != null) { 7383 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 7384 } 7385 7386 // Give any attached key listener a first crack at the event. 7387 //noinspection SimplifiableIfStatement 7388 ListenerInfo li = mListenerInfo; 7389 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 7390 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 7391 return true; 7392 } 7393 7394 if (event.dispatch(this, mAttachInfo != null 7395 ? mAttachInfo.mKeyDispatchState : null, this)) { 7396 return true; 7397 } 7398 7399 if (mInputEventConsistencyVerifier != null) { 7400 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7401 } 7402 return false; 7403 } 7404 7405 /** 7406 * Dispatches a key shortcut event. 7407 * 7408 * @param event The key event to be dispatched. 7409 * @return True if the event was handled by the view, false otherwise. 7410 */ 7411 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 7412 return onKeyShortcut(event.getKeyCode(), event); 7413 } 7414 7415 /** 7416 * Pass the touch screen motion event down to the target view, or this 7417 * view if it is the target. 7418 * 7419 * @param event The motion event to be dispatched. 7420 * @return True if the event was handled by the view, false otherwise. 7421 */ 7422 public boolean dispatchTouchEvent(MotionEvent event) { 7423 if (mInputEventConsistencyVerifier != null) { 7424 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 7425 } 7426 7427 if (onFilterTouchEventForSecurity(event)) { 7428 //noinspection SimplifiableIfStatement 7429 ListenerInfo li = mListenerInfo; 7430 if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 7431 && li.mOnTouchListener.onTouch(this, event)) { 7432 return true; 7433 } 7434 7435 if (onTouchEvent(event)) { 7436 return true; 7437 } 7438 } 7439 7440 if (mInputEventConsistencyVerifier != null) { 7441 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7442 } 7443 return false; 7444 } 7445 7446 /** 7447 * Filter the touch event to apply security policies. 7448 * 7449 * @param event The motion event to be filtered. 7450 * @return True if the event should be dispatched, false if the event should be dropped. 7451 * 7452 * @see #getFilterTouchesWhenObscured 7453 */ 7454 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 7455 //noinspection RedundantIfStatement 7456 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 7457 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 7458 // Window is obscured, drop this touch. 7459 return false; 7460 } 7461 return true; 7462 } 7463 7464 /** 7465 * Pass a trackball motion event down to the focused view. 7466 * 7467 * @param event The motion event to be dispatched. 7468 * @return True if the event was handled by the view, false otherwise. 7469 */ 7470 public boolean dispatchTrackballEvent(MotionEvent event) { 7471 if (mInputEventConsistencyVerifier != null) { 7472 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 7473 } 7474 7475 return onTrackballEvent(event); 7476 } 7477 7478 /** 7479 * Dispatch a generic motion event. 7480 * <p> 7481 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 7482 * are delivered to the view under the pointer. All other generic motion events are 7483 * delivered to the focused view. Hover events are handled specially and are delivered 7484 * to {@link #onHoverEvent(MotionEvent)}. 7485 * </p> 7486 * 7487 * @param event The motion event to be dispatched. 7488 * @return True if the event was handled by the view, false otherwise. 7489 */ 7490 public boolean dispatchGenericMotionEvent(MotionEvent event) { 7491 if (mInputEventConsistencyVerifier != null) { 7492 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 7493 } 7494 7495 final int source = event.getSource(); 7496 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 7497 final int action = event.getAction(); 7498 if (action == MotionEvent.ACTION_HOVER_ENTER 7499 || action == MotionEvent.ACTION_HOVER_MOVE 7500 || action == MotionEvent.ACTION_HOVER_EXIT) { 7501 if (dispatchHoverEvent(event)) { 7502 return true; 7503 } 7504 } else if (dispatchGenericPointerEvent(event)) { 7505 return true; 7506 } 7507 } else if (dispatchGenericFocusedEvent(event)) { 7508 return true; 7509 } 7510 7511 if (dispatchGenericMotionEventInternal(event)) { 7512 return true; 7513 } 7514 7515 if (mInputEventConsistencyVerifier != null) { 7516 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7517 } 7518 return false; 7519 } 7520 7521 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 7522 //noinspection SimplifiableIfStatement 7523 ListenerInfo li = mListenerInfo; 7524 if (li != null && li.mOnGenericMotionListener != null 7525 && (mViewFlags & ENABLED_MASK) == ENABLED 7526 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 7527 return true; 7528 } 7529 7530 if (onGenericMotionEvent(event)) { 7531 return true; 7532 } 7533 7534 if (mInputEventConsistencyVerifier != null) { 7535 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7536 } 7537 return false; 7538 } 7539 7540 /** 7541 * Dispatch a hover event. 7542 * <p> 7543 * Do not call this method directly. 7544 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 7545 * </p> 7546 * 7547 * @param event The motion event to be dispatched. 7548 * @return True if the event was handled by the view, false otherwise. 7549 */ 7550 protected boolean dispatchHoverEvent(MotionEvent event) { 7551 //noinspection SimplifiableIfStatement 7552 ListenerInfo li = mListenerInfo; 7553 if (li != null && li.mOnHoverListener != null 7554 && (mViewFlags & ENABLED_MASK) == ENABLED 7555 && li.mOnHoverListener.onHover(this, event)) { 7556 return true; 7557 } 7558 7559 return onHoverEvent(event); 7560 } 7561 7562 /** 7563 * Returns true if the view has a child to which it has recently sent 7564 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 7565 * it does not have a hovered child, then it must be the innermost hovered view. 7566 * @hide 7567 */ 7568 protected boolean hasHoveredChild() { 7569 return false; 7570 } 7571 7572 /** 7573 * Dispatch a generic motion event to the view under the first pointer. 7574 * <p> 7575 * Do not call this method directly. 7576 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 7577 * </p> 7578 * 7579 * @param event The motion event to be dispatched. 7580 * @return True if the event was handled by the view, false otherwise. 7581 */ 7582 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 7583 return false; 7584 } 7585 7586 /** 7587 * Dispatch a generic motion event to the currently focused view. 7588 * <p> 7589 * Do not call this method directly. 7590 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 7591 * </p> 7592 * 7593 * @param event The motion event to be dispatched. 7594 * @return True if the event was handled by the view, false otherwise. 7595 */ 7596 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 7597 return false; 7598 } 7599 7600 /** 7601 * Dispatch a pointer event. 7602 * <p> 7603 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 7604 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 7605 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 7606 * and should not be expected to handle other pointing device features. 7607 * </p> 7608 * 7609 * @param event The motion event to be dispatched. 7610 * @return True if the event was handled by the view, false otherwise. 7611 * @hide 7612 */ 7613 public final boolean dispatchPointerEvent(MotionEvent event) { 7614 if (event.isTouchEvent()) { 7615 return dispatchTouchEvent(event); 7616 } else { 7617 return dispatchGenericMotionEvent(event); 7618 } 7619 } 7620 7621 /** 7622 * Called when the window containing this view gains or loses window focus. 7623 * ViewGroups should override to route to their children. 7624 * 7625 * @param hasFocus True if the window containing this view now has focus, 7626 * false otherwise. 7627 */ 7628 public void dispatchWindowFocusChanged(boolean hasFocus) { 7629 onWindowFocusChanged(hasFocus); 7630 } 7631 7632 /** 7633 * Called when the window containing this view gains or loses focus. Note 7634 * that this is separate from view focus: to receive key events, both 7635 * your view and its window must have focus. If a window is displayed 7636 * on top of yours that takes input focus, then your own window will lose 7637 * focus but the view focus will remain unchanged. 7638 * 7639 * @param hasWindowFocus True if the window containing this view now has 7640 * focus, false otherwise. 7641 */ 7642 public void onWindowFocusChanged(boolean hasWindowFocus) { 7643 InputMethodManager imm = InputMethodManager.peekInstance(); 7644 if (!hasWindowFocus) { 7645 if (isPressed()) { 7646 setPressed(false); 7647 } 7648 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 7649 imm.focusOut(this); 7650 } 7651 removeLongPressCallback(); 7652 removeTapCallback(); 7653 onFocusLost(); 7654 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 7655 imm.focusIn(this); 7656 } 7657 refreshDrawableState(); 7658 } 7659 7660 /** 7661 * Returns true if this view is in a window that currently has window focus. 7662 * Note that this is not the same as the view itself having focus. 7663 * 7664 * @return True if this view is in a window that currently has window focus. 7665 */ 7666 public boolean hasWindowFocus() { 7667 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 7668 } 7669 7670 /** 7671 * Dispatch a view visibility change down the view hierarchy. 7672 * ViewGroups should override to route to their children. 7673 * @param changedView The view whose visibility changed. Could be 'this' or 7674 * an ancestor view. 7675 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 7676 * {@link #INVISIBLE} or {@link #GONE}. 7677 */ 7678 protected void dispatchVisibilityChanged(View changedView, int visibility) { 7679 onVisibilityChanged(changedView, visibility); 7680 } 7681 7682 /** 7683 * Called when the visibility of the view or an ancestor of the view is changed. 7684 * @param changedView The view whose visibility changed. Could be 'this' or 7685 * an ancestor view. 7686 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 7687 * {@link #INVISIBLE} or {@link #GONE}. 7688 */ 7689 protected void onVisibilityChanged(View changedView, int visibility) { 7690 if (visibility == VISIBLE) { 7691 if (mAttachInfo != null) { 7692 initialAwakenScrollBars(); 7693 } else { 7694 mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 7695 } 7696 } 7697 } 7698 7699 /** 7700 * Dispatch a hint about whether this view is displayed. For instance, when 7701 * a View moves out of the screen, it might receives a display hint indicating 7702 * the view is not displayed. Applications should not <em>rely</em> on this hint 7703 * as there is no guarantee that they will receive one. 7704 * 7705 * @param hint A hint about whether or not this view is displayed: 7706 * {@link #VISIBLE} or {@link #INVISIBLE}. 7707 */ 7708 public void dispatchDisplayHint(int hint) { 7709 onDisplayHint(hint); 7710 } 7711 7712 /** 7713 * Gives this view a hint about whether is displayed or not. For instance, when 7714 * a View moves out of the screen, it might receives a display hint indicating 7715 * the view is not displayed. Applications should not <em>rely</em> on this hint 7716 * as there is no guarantee that they will receive one. 7717 * 7718 * @param hint A hint about whether or not this view is displayed: 7719 * {@link #VISIBLE} or {@link #INVISIBLE}. 7720 */ 7721 protected void onDisplayHint(int hint) { 7722 } 7723 7724 /** 7725 * Dispatch a window visibility change down the view hierarchy. 7726 * ViewGroups should override to route to their children. 7727 * 7728 * @param visibility The new visibility of the window. 7729 * 7730 * @see #onWindowVisibilityChanged(int) 7731 */ 7732 public void dispatchWindowVisibilityChanged(int visibility) { 7733 onWindowVisibilityChanged(visibility); 7734 } 7735 7736 /** 7737 * Called when the window containing has change its visibility 7738 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 7739 * that this tells you whether or not your window is being made visible 7740 * to the window manager; this does <em>not</em> tell you whether or not 7741 * your window is obscured by other windows on the screen, even if it 7742 * is itself visible. 7743 * 7744 * @param visibility The new visibility of the window. 7745 */ 7746 protected void onWindowVisibilityChanged(int visibility) { 7747 if (visibility == VISIBLE) { 7748 initialAwakenScrollBars(); 7749 } 7750 } 7751 7752 /** 7753 * Returns the current visibility of the window this view is attached to 7754 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 7755 * 7756 * @return Returns the current visibility of the view's window. 7757 */ 7758 public int getWindowVisibility() { 7759 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 7760 } 7761 7762 /** 7763 * Retrieve the overall visible display size in which the window this view is 7764 * attached to has been positioned in. This takes into account screen 7765 * decorations above the window, for both cases where the window itself 7766 * is being position inside of them or the window is being placed under 7767 * then and covered insets are used for the window to position its content 7768 * inside. In effect, this tells you the available area where content can 7769 * be placed and remain visible to users. 7770 * 7771 * <p>This function requires an IPC back to the window manager to retrieve 7772 * the requested information, so should not be used in performance critical 7773 * code like drawing. 7774 * 7775 * @param outRect Filled in with the visible display frame. If the view 7776 * is not attached to a window, this is simply the raw display size. 7777 */ 7778 public void getWindowVisibleDisplayFrame(Rect outRect) { 7779 if (mAttachInfo != null) { 7780 try { 7781 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 7782 } catch (RemoteException e) { 7783 return; 7784 } 7785 // XXX This is really broken, and probably all needs to be done 7786 // in the window manager, and we need to know more about whether 7787 // we want the area behind or in front of the IME. 7788 final Rect insets = mAttachInfo.mVisibleInsets; 7789 outRect.left += insets.left; 7790 outRect.top += insets.top; 7791 outRect.right -= insets.right; 7792 outRect.bottom -= insets.bottom; 7793 return; 7794 } 7795 // The view is not attached to a display so we don't have a context. 7796 // Make a best guess about the display size. 7797 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 7798 d.getRectSize(outRect); 7799 } 7800 7801 /** 7802 * Dispatch a notification about a resource configuration change down 7803 * the view hierarchy. 7804 * ViewGroups should override to route to their children. 7805 * 7806 * @param newConfig The new resource configuration. 7807 * 7808 * @see #onConfigurationChanged(android.content.res.Configuration) 7809 */ 7810 public void dispatchConfigurationChanged(Configuration newConfig) { 7811 onConfigurationChanged(newConfig); 7812 } 7813 7814 /** 7815 * Called when the current configuration of the resources being used 7816 * by the application have changed. You can use this to decide when 7817 * to reload resources that can changed based on orientation and other 7818 * configuration characterstics. You only need to use this if you are 7819 * not relying on the normal {@link android.app.Activity} mechanism of 7820 * recreating the activity instance upon a configuration change. 7821 * 7822 * @param newConfig The new resource configuration. 7823 */ 7824 protected void onConfigurationChanged(Configuration newConfig) { 7825 } 7826 7827 /** 7828 * Private function to aggregate all per-view attributes in to the view 7829 * root. 7830 */ 7831 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 7832 performCollectViewAttributes(attachInfo, visibility); 7833 } 7834 7835 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 7836 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 7837 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 7838 attachInfo.mKeepScreenOn = true; 7839 } 7840 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 7841 ListenerInfo li = mListenerInfo; 7842 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 7843 attachInfo.mHasSystemUiListeners = true; 7844 } 7845 } 7846 } 7847 7848 void needGlobalAttributesUpdate(boolean force) { 7849 final AttachInfo ai = mAttachInfo; 7850 if (ai != null && !ai.mRecomputeGlobalAttributes) { 7851 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 7852 || ai.mHasSystemUiListeners) { 7853 ai.mRecomputeGlobalAttributes = true; 7854 } 7855 } 7856 } 7857 7858 /** 7859 * Returns whether the device is currently in touch mode. Touch mode is entered 7860 * once the user begins interacting with the device by touch, and affects various 7861 * things like whether focus is always visible to the user. 7862 * 7863 * @return Whether the device is in touch mode. 7864 */ 7865 @ViewDebug.ExportedProperty 7866 public boolean isInTouchMode() { 7867 if (mAttachInfo != null) { 7868 return mAttachInfo.mInTouchMode; 7869 } else { 7870 return ViewRootImpl.isInTouchMode(); 7871 } 7872 } 7873 7874 /** 7875 * Returns the context the view is running in, through which it can 7876 * access the current theme, resources, etc. 7877 * 7878 * @return The view's Context. 7879 */ 7880 @ViewDebug.CapturedViewProperty 7881 public final Context getContext() { 7882 return mContext; 7883 } 7884 7885 /** 7886 * Handle a key event before it is processed by any input method 7887 * associated with the view hierarchy. This can be used to intercept 7888 * key events in special situations before the IME consumes them; a 7889 * typical example would be handling the BACK key to update the application's 7890 * UI instead of allowing the IME to see it and close itself. 7891 * 7892 * @param keyCode The value in event.getKeyCode(). 7893 * @param event Description of the key event. 7894 * @return If you handled the event, return true. If you want to allow the 7895 * event to be handled by the next receiver, return false. 7896 */ 7897 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 7898 return false; 7899 } 7900 7901 /** 7902 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 7903 * KeyEvent.Callback.onKeyDown()}: perform press of the view 7904 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 7905 * is released, if the view is enabled and clickable. 7906 * 7907 * <p>Key presses in software keyboards will generally NOT trigger this listener, 7908 * although some may elect to do so in some situations. Do not rely on this to 7909 * catch software key presses. 7910 * 7911 * @param keyCode A key code that represents the button pressed, from 7912 * {@link android.view.KeyEvent}. 7913 * @param event The KeyEvent object that defines the button action. 7914 */ 7915 public boolean onKeyDown(int keyCode, KeyEvent event) { 7916 boolean result = false; 7917 7918 switch (keyCode) { 7919 case KeyEvent.KEYCODE_DPAD_CENTER: 7920 case KeyEvent.KEYCODE_ENTER: { 7921 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 7922 return true; 7923 } 7924 // Long clickable items don't necessarily have to be clickable 7925 if (((mViewFlags & CLICKABLE) == CLICKABLE || 7926 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 7927 (event.getRepeatCount() == 0)) { 7928 setPressed(true); 7929 checkForLongClick(0); 7930 return true; 7931 } 7932 break; 7933 } 7934 } 7935 return result; 7936 } 7937 7938 /** 7939 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 7940 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 7941 * the event). 7942 * <p>Key presses in software keyboards will generally NOT trigger this listener, 7943 * although some may elect to do so in some situations. Do not rely on this to 7944 * catch software key presses. 7945 */ 7946 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 7947 return false; 7948 } 7949 7950 /** 7951 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 7952 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 7953 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 7954 * {@link KeyEvent#KEYCODE_ENTER} is released. 7955 * <p>Key presses in software keyboards will generally NOT trigger this listener, 7956 * although some may elect to do so in some situations. Do not rely on this to 7957 * catch software key presses. 7958 * 7959 * @param keyCode A key code that represents the button pressed, from 7960 * {@link android.view.KeyEvent}. 7961 * @param event The KeyEvent object that defines the button action. 7962 */ 7963 public boolean onKeyUp(int keyCode, KeyEvent event) { 7964 boolean result = false; 7965 7966 switch (keyCode) { 7967 case KeyEvent.KEYCODE_DPAD_CENTER: 7968 case KeyEvent.KEYCODE_ENTER: { 7969 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 7970 return true; 7971 } 7972 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 7973 setPressed(false); 7974 7975 if (!mHasPerformedLongPress) { 7976 // This is a tap, so remove the longpress check 7977 removeLongPressCallback(); 7978 7979 result = performClick(); 7980 } 7981 } 7982 break; 7983 } 7984 } 7985 return result; 7986 } 7987 7988 /** 7989 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 7990 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 7991 * the event). 7992 * <p>Key presses in software keyboards will generally NOT trigger this listener, 7993 * although some may elect to do so in some situations. Do not rely on this to 7994 * catch software key presses. 7995 * 7996 * @param keyCode A key code that represents the button pressed, from 7997 * {@link android.view.KeyEvent}. 7998 * @param repeatCount The number of times the action was made. 7999 * @param event The KeyEvent object that defines the button action. 8000 */ 8001 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 8002 return false; 8003 } 8004 8005 /** 8006 * Called on the focused view when a key shortcut event is not handled. 8007 * Override this method to implement local key shortcuts for the View. 8008 * Key shortcuts can also be implemented by setting the 8009 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 8010 * 8011 * @param keyCode The value in event.getKeyCode(). 8012 * @param event Description of the key event. 8013 * @return If you handled the event, return true. If you want to allow the 8014 * event to be handled by the next receiver, return false. 8015 */ 8016 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 8017 return false; 8018 } 8019 8020 /** 8021 * Check whether the called view is a text editor, in which case it 8022 * would make sense to automatically display a soft input window for 8023 * it. Subclasses should override this if they implement 8024 * {@link #onCreateInputConnection(EditorInfo)} to return true if 8025 * a call on that method would return a non-null InputConnection, and 8026 * they are really a first-class editor that the user would normally 8027 * start typing on when the go into a window containing your view. 8028 * 8029 * <p>The default implementation always returns false. This does 8030 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 8031 * will not be called or the user can not otherwise perform edits on your 8032 * view; it is just a hint to the system that this is not the primary 8033 * purpose of this view. 8034 * 8035 * @return Returns true if this view is a text editor, else false. 8036 */ 8037 public boolean onCheckIsTextEditor() { 8038 return false; 8039 } 8040 8041 /** 8042 * Create a new InputConnection for an InputMethod to interact 8043 * with the view. The default implementation returns null, since it doesn't 8044 * support input methods. You can override this to implement such support. 8045 * This is only needed for views that take focus and text input. 8046 * 8047 * <p>When implementing this, you probably also want to implement 8048 * {@link #onCheckIsTextEditor()} to indicate you will return a 8049 * non-null InputConnection. 8050 * 8051 * @param outAttrs Fill in with attribute information about the connection. 8052 */ 8053 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 8054 return null; 8055 } 8056 8057 /** 8058 * Called by the {@link android.view.inputmethod.InputMethodManager} 8059 * when a view who is not the current 8060 * input connection target is trying to make a call on the manager. The 8061 * default implementation returns false; you can override this to return 8062 * true for certain views if you are performing InputConnection proxying 8063 * to them. 8064 * @param view The View that is making the InputMethodManager call. 8065 * @return Return true to allow the call, false to reject. 8066 */ 8067 public boolean checkInputConnectionProxy(View view) { 8068 return false; 8069 } 8070 8071 /** 8072 * Show the context menu for this view. It is not safe to hold on to the 8073 * menu after returning from this method. 8074 * 8075 * You should normally not overload this method. Overload 8076 * {@link #onCreateContextMenu(ContextMenu)} or define an 8077 * {@link OnCreateContextMenuListener} to add items to the context menu. 8078 * 8079 * @param menu The context menu to populate 8080 */ 8081 public void createContextMenu(ContextMenu menu) { 8082 ContextMenuInfo menuInfo = getContextMenuInfo(); 8083 8084 // Sets the current menu info so all items added to menu will have 8085 // my extra info set. 8086 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 8087 8088 onCreateContextMenu(menu); 8089 ListenerInfo li = mListenerInfo; 8090 if (li != null && li.mOnCreateContextMenuListener != null) { 8091 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 8092 } 8093 8094 // Clear the extra information so subsequent items that aren't mine don't 8095 // have my extra info. 8096 ((MenuBuilder)menu).setCurrentMenuInfo(null); 8097 8098 if (mParent != null) { 8099 mParent.createContextMenu(menu); 8100 } 8101 } 8102 8103 /** 8104 * Views should implement this if they have extra information to associate 8105 * with the context menu. The return result is supplied as a parameter to 8106 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 8107 * callback. 8108 * 8109 * @return Extra information about the item for which the context menu 8110 * should be shown. This information will vary across different 8111 * subclasses of View. 8112 */ 8113 protected ContextMenuInfo getContextMenuInfo() { 8114 return null; 8115 } 8116 8117 /** 8118 * Views should implement this if the view itself is going to add items to 8119 * the context menu. 8120 * 8121 * @param menu the context menu to populate 8122 */ 8123 protected void onCreateContextMenu(ContextMenu menu) { 8124 } 8125 8126 /** 8127 * Implement this method to handle trackball motion events. The 8128 * <em>relative</em> movement of the trackball since the last event 8129 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 8130 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 8131 * that a movement of 1 corresponds to the user pressing one DPAD key (so 8132 * they will often be fractional values, representing the more fine-grained 8133 * movement information available from a trackball). 8134 * 8135 * @param event The motion event. 8136 * @return True if the event was handled, false otherwise. 8137 */ 8138 public boolean onTrackballEvent(MotionEvent event) { 8139 return false; 8140 } 8141 8142 /** 8143 * Implement this method to handle generic motion events. 8144 * <p> 8145 * Generic motion events describe joystick movements, mouse hovers, track pad 8146 * touches, scroll wheel movements and other input events. The 8147 * {@link MotionEvent#getSource() source} of the motion event specifies 8148 * the class of input that was received. Implementations of this method 8149 * must examine the bits in the source before processing the event. 8150 * The following code example shows how this is done. 8151 * </p><p> 8152 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 8153 * are delivered to the view under the pointer. All other generic motion events are 8154 * delivered to the focused view. 8155 * </p> 8156 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 8157 * if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) { 8158 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 8159 * // process the joystick movement... 8160 * return true; 8161 * } 8162 * } 8163 * if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { 8164 * switch (event.getAction()) { 8165 * case MotionEvent.ACTION_HOVER_MOVE: 8166 * // process the mouse hover movement... 8167 * return true; 8168 * case MotionEvent.ACTION_SCROLL: 8169 * // process the scroll wheel movement... 8170 * return true; 8171 * } 8172 * } 8173 * return super.onGenericMotionEvent(event); 8174 * }</pre> 8175 * 8176 * @param event The generic motion event being processed. 8177 * @return True if the event was handled, false otherwise. 8178 */ 8179 public boolean onGenericMotionEvent(MotionEvent event) { 8180 return false; 8181 } 8182 8183 /** 8184 * Implement this method to handle hover events. 8185 * <p> 8186 * This method is called whenever a pointer is hovering into, over, or out of the 8187 * bounds of a view and the view is not currently being touched. 8188 * Hover events are represented as pointer events with action 8189 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 8190 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 8191 * </p> 8192 * <ul> 8193 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 8194 * when the pointer enters the bounds of the view.</li> 8195 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 8196 * when the pointer has already entered the bounds of the view and has moved.</li> 8197 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 8198 * when the pointer has exited the bounds of the view or when the pointer is 8199 * about to go down due to a button click, tap, or similar user action that 8200 * causes the view to be touched.</li> 8201 * </ul> 8202 * <p> 8203 * The view should implement this method to return true to indicate that it is 8204 * handling the hover event, such as by changing its drawable state. 8205 * </p><p> 8206 * The default implementation calls {@link #setHovered} to update the hovered state 8207 * of the view when a hover enter or hover exit event is received, if the view 8208 * is enabled and is clickable. The default implementation also sends hover 8209 * accessibility events. 8210 * </p> 8211 * 8212 * @param event The motion event that describes the hover. 8213 * @return True if the view handled the hover event. 8214 * 8215 * @see #isHovered 8216 * @see #setHovered 8217 * @see #onHoverChanged 8218 */ 8219 public boolean onHoverEvent(MotionEvent event) { 8220 // The root view may receive hover (or touch) events that are outside the bounds of 8221 // the window. This code ensures that we only send accessibility events for 8222 // hovers that are actually within the bounds of the root view. 8223 final int action = event.getActionMasked(); 8224 if (!mSendingHoverAccessibilityEvents) { 8225 if ((action == MotionEvent.ACTION_HOVER_ENTER 8226 || action == MotionEvent.ACTION_HOVER_MOVE) 8227 && !hasHoveredChild() 8228 && pointInView(event.getX(), event.getY())) { 8229 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 8230 mSendingHoverAccessibilityEvents = true; 8231 } 8232 } else { 8233 if (action == MotionEvent.ACTION_HOVER_EXIT 8234 || (action == MotionEvent.ACTION_MOVE 8235 && !pointInView(event.getX(), event.getY()))) { 8236 mSendingHoverAccessibilityEvents = false; 8237 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 8238 // If the window does not have input focus we take away accessibility 8239 // focus as soon as the user stop hovering over the view. 8240 if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) { 8241 getViewRootImpl().setAccessibilityFocus(null, null); 8242 } 8243 } 8244 } 8245 8246 if (isHoverable()) { 8247 switch (action) { 8248 case MotionEvent.ACTION_HOVER_ENTER: 8249 setHovered(true); 8250 break; 8251 case MotionEvent.ACTION_HOVER_EXIT: 8252 setHovered(false); 8253 break; 8254 } 8255 8256 // Dispatch the event to onGenericMotionEvent before returning true. 8257 // This is to provide compatibility with existing applications that 8258 // handled HOVER_MOVE events in onGenericMotionEvent and that would 8259 // break because of the new default handling for hoverable views 8260 // in onHoverEvent. 8261 // Note that onGenericMotionEvent will be called by default when 8262 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 8263 dispatchGenericMotionEventInternal(event); 8264 // The event was already handled by calling setHovered(), so always 8265 // return true. 8266 return true; 8267 } 8268 8269 return false; 8270 } 8271 8272 /** 8273 * Returns true if the view should handle {@link #onHoverEvent} 8274 * by calling {@link #setHovered} to change its hovered state. 8275 * 8276 * @return True if the view is hoverable. 8277 */ 8278 private boolean isHoverable() { 8279 final int viewFlags = mViewFlags; 8280 if ((viewFlags & ENABLED_MASK) == DISABLED) { 8281 return false; 8282 } 8283 8284 return (viewFlags & CLICKABLE) == CLICKABLE 8285 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 8286 } 8287 8288 /** 8289 * Returns true if the view is currently hovered. 8290 * 8291 * @return True if the view is currently hovered. 8292 * 8293 * @see #setHovered 8294 * @see #onHoverChanged 8295 */ 8296 @ViewDebug.ExportedProperty 8297 public boolean isHovered() { 8298 return (mPrivateFlags & PFLAG_HOVERED) != 0; 8299 } 8300 8301 /** 8302 * Sets whether the view is currently hovered. 8303 * <p> 8304 * Calling this method also changes the drawable state of the view. This 8305 * enables the view to react to hover by using different drawable resources 8306 * to change its appearance. 8307 * </p><p> 8308 * The {@link #onHoverChanged} method is called when the hovered state changes. 8309 * </p> 8310 * 8311 * @param hovered True if the view is hovered. 8312 * 8313 * @see #isHovered 8314 * @see #onHoverChanged 8315 */ 8316 public void setHovered(boolean hovered) { 8317 if (hovered) { 8318 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 8319 mPrivateFlags |= PFLAG_HOVERED; 8320 refreshDrawableState(); 8321 onHoverChanged(true); 8322 } 8323 } else { 8324 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 8325 mPrivateFlags &= ~PFLAG_HOVERED; 8326 refreshDrawableState(); 8327 onHoverChanged(false); 8328 } 8329 } 8330 } 8331 8332 /** 8333 * Implement this method to handle hover state changes. 8334 * <p> 8335 * This method is called whenever the hover state changes as a result of a 8336 * call to {@link #setHovered}. 8337 * </p> 8338 * 8339 * @param hovered The current hover state, as returned by {@link #isHovered}. 8340 * 8341 * @see #isHovered 8342 * @see #setHovered 8343 */ 8344 public void onHoverChanged(boolean hovered) { 8345 } 8346 8347 /** 8348 * Implement this method to handle touch screen motion events. 8349 * 8350 * @param event The motion event. 8351 * @return True if the event was handled, false otherwise. 8352 */ 8353 public boolean onTouchEvent(MotionEvent event) { 8354 final int viewFlags = mViewFlags; 8355 8356 if ((viewFlags & ENABLED_MASK) == DISABLED) { 8357 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 8358 setPressed(false); 8359 } 8360 // A disabled view that is clickable still consumes the touch 8361 // events, it just doesn't respond to them. 8362 return (((viewFlags & CLICKABLE) == CLICKABLE || 8363 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 8364 } 8365 8366 if (mTouchDelegate != null) { 8367 if (mTouchDelegate.onTouchEvent(event)) { 8368 return true; 8369 } 8370 } 8371 8372 if (((viewFlags & CLICKABLE) == CLICKABLE || 8373 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 8374 switch (event.getAction()) { 8375 case MotionEvent.ACTION_UP: 8376 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 8377 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 8378 // take focus if we don't have it already and we should in 8379 // touch mode. 8380 boolean focusTaken = false; 8381 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 8382 focusTaken = requestFocus(); 8383 } 8384 8385 if (prepressed) { 8386 // The button is being released before we actually 8387 // showed it as pressed. Make it show the pressed 8388 // state now (before scheduling the click) to ensure 8389 // the user sees it. 8390 setPressed(true); 8391 } 8392 8393 if (!mHasPerformedLongPress) { 8394 // This is a tap, so remove the longpress check 8395 removeLongPressCallback(); 8396 8397 // Only perform take click actions if we were in the pressed state 8398 if (!focusTaken) { 8399 // Use a Runnable and post this rather than calling 8400 // performClick directly. This lets other visual state 8401 // of the view update before click actions start. 8402 if (mPerformClick == null) { 8403 mPerformClick = new PerformClick(); 8404 } 8405 if (!post(mPerformClick)) { 8406 performClick(); 8407 } 8408 } 8409 } 8410 8411 if (mUnsetPressedState == null) { 8412 mUnsetPressedState = new UnsetPressedState(); 8413 } 8414 8415 if (prepressed) { 8416 postDelayed(mUnsetPressedState, 8417 ViewConfiguration.getPressedStateDuration()); 8418 } else if (!post(mUnsetPressedState)) { 8419 // If the post failed, unpress right now 8420 mUnsetPressedState.run(); 8421 } 8422 removeTapCallback(); 8423 } 8424 break; 8425 8426 case MotionEvent.ACTION_DOWN: 8427 mHasPerformedLongPress = false; 8428 8429 if (performButtonActionOnTouchDown(event)) { 8430 break; 8431 } 8432 8433 // Walk up the hierarchy to determine if we're inside a scrolling container. 8434 boolean isInScrollingContainer = isInScrollingContainer(); 8435 8436 // For views inside a scrolling container, delay the pressed feedback for 8437 // a short period in case this is a scroll. 8438 if (isInScrollingContainer) { 8439 mPrivateFlags |= PFLAG_PREPRESSED; 8440 if (mPendingCheckForTap == null) { 8441 mPendingCheckForTap = new CheckForTap(); 8442 } 8443 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 8444 } else { 8445 // Not inside a scrolling container, so show the feedback right away 8446 setPressed(true); 8447 checkForLongClick(0); 8448 } 8449 break; 8450 8451 case MotionEvent.ACTION_CANCEL: 8452 setPressed(false); 8453 removeTapCallback(); 8454 removeLongPressCallback(); 8455 break; 8456 8457 case MotionEvent.ACTION_MOVE: 8458 final int x = (int) event.getX(); 8459 final int y = (int) event.getY(); 8460 8461 // Be lenient about moving outside of buttons 8462 if (!pointInView(x, y, mTouchSlop)) { 8463 // Outside button 8464 removeTapCallback(); 8465 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 8466 // Remove any future long press/tap checks 8467 removeLongPressCallback(); 8468 8469 setPressed(false); 8470 } 8471 } 8472 break; 8473 } 8474 return true; 8475 } 8476 8477 return false; 8478 } 8479 8480 /** 8481 * @hide 8482 */ 8483 public boolean isInScrollingContainer() { 8484 ViewParent p = getParent(); 8485 while (p != null && p instanceof ViewGroup) { 8486 if (((ViewGroup) p).shouldDelayChildPressedState()) { 8487 return true; 8488 } 8489 p = p.getParent(); 8490 } 8491 return false; 8492 } 8493 8494 /** 8495 * Remove the longpress detection timer. 8496 */ 8497 private void removeLongPressCallback() { 8498 if (mPendingCheckForLongPress != null) { 8499 removeCallbacks(mPendingCheckForLongPress); 8500 } 8501 } 8502 8503 /** 8504 * Remove the pending click action 8505 */ 8506 private void removePerformClickCallback() { 8507 if (mPerformClick != null) { 8508 removeCallbacks(mPerformClick); 8509 } 8510 } 8511 8512 /** 8513 * Remove the prepress detection timer. 8514 */ 8515 private void removeUnsetPressCallback() { 8516 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 8517 setPressed(false); 8518 removeCallbacks(mUnsetPressedState); 8519 } 8520 } 8521 8522 /** 8523 * Remove the tap detection timer. 8524 */ 8525 private void removeTapCallback() { 8526 if (mPendingCheckForTap != null) { 8527 mPrivateFlags &= ~PFLAG_PREPRESSED; 8528 removeCallbacks(mPendingCheckForTap); 8529 } 8530 } 8531 8532 /** 8533 * Cancels a pending long press. Your subclass can use this if you 8534 * want the context menu to come up if the user presses and holds 8535 * at the same place, but you don't want it to come up if they press 8536 * and then move around enough to cause scrolling. 8537 */ 8538 public void cancelLongPress() { 8539 removeLongPressCallback(); 8540 8541 /* 8542 * The prepressed state handled by the tap callback is a display 8543 * construct, but the tap callback will post a long press callback 8544 * less its own timeout. Remove it here. 8545 */ 8546 removeTapCallback(); 8547 } 8548 8549 /** 8550 * Remove the pending callback for sending a 8551 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 8552 */ 8553 private void removeSendViewScrolledAccessibilityEventCallback() { 8554 if (mSendViewScrolledAccessibilityEvent != null) { 8555 removeCallbacks(mSendViewScrolledAccessibilityEvent); 8556 mSendViewScrolledAccessibilityEvent.mIsPending = false; 8557 } 8558 } 8559 8560 /** 8561 * Sets the TouchDelegate for this View. 8562 */ 8563 public void setTouchDelegate(TouchDelegate delegate) { 8564 mTouchDelegate = delegate; 8565 } 8566 8567 /** 8568 * Gets the TouchDelegate for this View. 8569 */ 8570 public TouchDelegate getTouchDelegate() { 8571 return mTouchDelegate; 8572 } 8573 8574 /** 8575 * Set flags controlling behavior of this view. 8576 * 8577 * @param flags Constant indicating the value which should be set 8578 * @param mask Constant indicating the bit range that should be changed 8579 */ 8580 void setFlags(int flags, int mask) { 8581 final boolean accessibilityEnabled = 8582 AccessibilityManager.getInstance(mContext).isEnabled(); 8583 final boolean oldIncludeForAccessibility = accessibilityEnabled 8584 ? includeForAccessibility() : false; 8585 8586 int old = mViewFlags; 8587 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 8588 8589 int changed = mViewFlags ^ old; 8590 if (changed == 0) { 8591 return; 8592 } 8593 int privateFlags = mPrivateFlags; 8594 8595 /* Check if the FOCUSABLE bit has changed */ 8596 if (((changed & FOCUSABLE_MASK) != 0) && 8597 ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) { 8598 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 8599 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 8600 /* Give up focus if we are no longer focusable */ 8601 clearFocus(); 8602 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 8603 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 8604 /* 8605 * Tell the view system that we are now available to take focus 8606 * if no one else already has it. 8607 */ 8608 if (mParent != null) mParent.focusableViewAvailable(this); 8609 } 8610 } 8611 8612 final int newVisibility = flags & VISIBILITY_MASK; 8613 if (newVisibility == VISIBLE) { 8614 if ((changed & VISIBILITY_MASK) != 0) { 8615 /* 8616 * If this view is becoming visible, invalidate it in case it changed while 8617 * it was not visible. Marking it drawn ensures that the invalidation will 8618 * go through. 8619 */ 8620 mPrivateFlags |= PFLAG_DRAWN; 8621 invalidate(true); 8622 8623 needGlobalAttributesUpdate(true); 8624 8625 // a view becoming visible is worth notifying the parent 8626 // about in case nothing has focus. even if this specific view 8627 // isn't focusable, it may contain something that is, so let 8628 // the root view try to give this focus if nothing else does. 8629 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 8630 mParent.focusableViewAvailable(this); 8631 } 8632 } 8633 } 8634 8635 /* Check if the GONE bit has changed */ 8636 if ((changed & GONE) != 0) { 8637 needGlobalAttributesUpdate(false); 8638 requestLayout(); 8639 8640 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 8641 if (hasFocus()) clearFocus(); 8642 clearAccessibilityFocus(); 8643 destroyDrawingCache(); 8644 if (mParent instanceof View) { 8645 // GONE views noop invalidation, so invalidate the parent 8646 ((View) mParent).invalidate(true); 8647 } 8648 // Mark the view drawn to ensure that it gets invalidated properly the next 8649 // time it is visible and gets invalidated 8650 mPrivateFlags |= PFLAG_DRAWN; 8651 } 8652 if (mAttachInfo != null) { 8653 mAttachInfo.mViewVisibilityChanged = true; 8654 } 8655 } 8656 8657 /* Check if the VISIBLE bit has changed */ 8658 if ((changed & INVISIBLE) != 0) { 8659 needGlobalAttributesUpdate(false); 8660 /* 8661 * If this view is becoming invisible, set the DRAWN flag so that 8662 * the next invalidate() will not be skipped. 8663 */ 8664 mPrivateFlags |= PFLAG_DRAWN; 8665 8666 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) { 8667 // root view becoming invisible shouldn't clear focus and accessibility focus 8668 if (getRootView() != this) { 8669 clearFocus(); 8670 clearAccessibilityFocus(); 8671 } 8672 } 8673 if (mAttachInfo != null) { 8674 mAttachInfo.mViewVisibilityChanged = true; 8675 } 8676 } 8677 8678 if ((changed & VISIBILITY_MASK) != 0) { 8679 // If the view is invisible, cleanup its display list to free up resources 8680 if (newVisibility != VISIBLE) { 8681 cleanupDraw(); 8682 } 8683 8684 if (mParent instanceof ViewGroup) { 8685 ((ViewGroup) mParent).onChildVisibilityChanged(this, 8686 (changed & VISIBILITY_MASK), newVisibility); 8687 ((View) mParent).invalidate(true); 8688 } else if (mParent != null) { 8689 mParent.invalidateChild(this, null); 8690 } 8691 dispatchVisibilityChanged(this, newVisibility); 8692 } 8693 8694 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 8695 destroyDrawingCache(); 8696 } 8697 8698 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 8699 destroyDrawingCache(); 8700 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 8701 invalidateParentCaches(); 8702 } 8703 8704 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 8705 destroyDrawingCache(); 8706 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 8707 } 8708 8709 if ((changed & DRAW_MASK) != 0) { 8710 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 8711 if (mBackground != null) { 8712 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 8713 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 8714 } else { 8715 mPrivateFlags |= PFLAG_SKIP_DRAW; 8716 } 8717 } else { 8718 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 8719 } 8720 requestLayout(); 8721 invalidate(true); 8722 } 8723 8724 if ((changed & KEEP_SCREEN_ON) != 0) { 8725 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 8726 mParent.recomputeViewAttributes(this); 8727 } 8728 } 8729 8730 if (accessibilityEnabled) { 8731 if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0 8732 || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) { 8733 if (oldIncludeForAccessibility != includeForAccessibility()) { 8734 notifySubtreeAccessibilityStateChangedIfNeeded(); 8735 } else { 8736 notifyViewAccessibilityStateChangedIfNeeded(); 8737 } 8738 } 8739 if ((changed & ENABLED_MASK) != 0) { 8740 notifyViewAccessibilityStateChangedIfNeeded(); 8741 } 8742 } 8743 } 8744 8745 /** 8746 * Change the view's z order in the tree, so it's on top of other sibling 8747 * views. This ordering change may affect layout, if the parent container 8748 * uses an order-dependent layout scheme (e.g., LinearLayout). This 8749 * method should be followed by calls to {@link #requestLayout()} and 8750 * {@link View#invalidate()} on the parent. 8751 * 8752 * @see ViewGroup#bringChildToFront(View) 8753 */ 8754 public void bringToFront() { 8755 if (mParent != null) { 8756 mParent.bringChildToFront(this); 8757 } 8758 } 8759 8760 /** 8761 * This is called in response to an internal scroll in this view (i.e., the 8762 * view scrolled its own contents). This is typically as a result of 8763 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 8764 * called. 8765 * 8766 * @param l Current horizontal scroll origin. 8767 * @param t Current vertical scroll origin. 8768 * @param oldl Previous horizontal scroll origin. 8769 * @param oldt Previous vertical scroll origin. 8770 */ 8771 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 8772 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 8773 postSendViewScrolledAccessibilityEventCallback(); 8774 } 8775 8776 mBackgroundSizeChanged = true; 8777 8778 final AttachInfo ai = mAttachInfo; 8779 if (ai != null) { 8780 ai.mViewScrollChanged = true; 8781 } 8782 } 8783 8784 /** 8785 * Interface definition for a callback to be invoked when the layout bounds of a view 8786 * changes due to layout processing. 8787 */ 8788 public interface OnLayoutChangeListener { 8789 /** 8790 * Called when the focus state of a view has changed. 8791 * 8792 * @param v The view whose state has changed. 8793 * @param left The new value of the view's left property. 8794 * @param top The new value of the view's top property. 8795 * @param right The new value of the view's right property. 8796 * @param bottom The new value of the view's bottom property. 8797 * @param oldLeft The previous value of the view's left property. 8798 * @param oldTop The previous value of the view's top property. 8799 * @param oldRight The previous value of the view's right property. 8800 * @param oldBottom The previous value of the view's bottom property. 8801 */ 8802 void onLayoutChange(View v, int left, int top, int right, int bottom, 8803 int oldLeft, int oldTop, int oldRight, int oldBottom); 8804 } 8805 8806 /** 8807 * This is called during layout when the size of this view has changed. If 8808 * you were just added to the view hierarchy, you're called with the old 8809 * values of 0. 8810 * 8811 * @param w Current width of this view. 8812 * @param h Current height of this view. 8813 * @param oldw Old width of this view. 8814 * @param oldh Old height of this view. 8815 */ 8816 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 8817 } 8818 8819 /** 8820 * Called by draw to draw the child views. This may be overridden 8821 * by derived classes to gain control just before its children are drawn 8822 * (but after its own view has been drawn). 8823 * @param canvas the canvas on which to draw the view 8824 */ 8825 protected void dispatchDraw(Canvas canvas) { 8826 8827 } 8828 8829 /** 8830 * Gets the parent of this view. Note that the parent is a 8831 * ViewParent and not necessarily a View. 8832 * 8833 * @return Parent of this view. 8834 */ 8835 public final ViewParent getParent() { 8836 return mParent; 8837 } 8838 8839 /** 8840 * Set the horizontal scrolled position of your view. This will cause a call to 8841 * {@link #onScrollChanged(int, int, int, int)} and the view will be 8842 * invalidated. 8843 * @param value the x position to scroll to 8844 */ 8845 public void setScrollX(int value) { 8846 scrollTo(value, mScrollY); 8847 } 8848 8849 /** 8850 * Set the vertical scrolled position of your view. This will cause a call to 8851 * {@link #onScrollChanged(int, int, int, int)} and the view will be 8852 * invalidated. 8853 * @param value the y position to scroll to 8854 */ 8855 public void setScrollY(int value) { 8856 scrollTo(mScrollX, value); 8857 } 8858 8859 /** 8860 * Return the scrolled left position of this view. This is the left edge of 8861 * the displayed part of your view. You do not need to draw any pixels 8862 * farther left, since those are outside of the frame of your view on 8863 * screen. 8864 * 8865 * @return The left edge of the displayed part of your view, in pixels. 8866 */ 8867 public final int getScrollX() { 8868 return mScrollX; 8869 } 8870 8871 /** 8872 * Return the scrolled top position of this view. This is the top edge of 8873 * the displayed part of your view. You do not need to draw any pixels above 8874 * it, since those are outside of the frame of your view on screen. 8875 * 8876 * @return The top edge of the displayed part of your view, in pixels. 8877 */ 8878 public final int getScrollY() { 8879 return mScrollY; 8880 } 8881 8882 /** 8883 * Return the width of the your view. 8884 * 8885 * @return The width of your view, in pixels. 8886 */ 8887 @ViewDebug.ExportedProperty(category = "layout") 8888 public final int getWidth() { 8889 return mRight - mLeft; 8890 } 8891 8892 /** 8893 * Return the height of your view. 8894 * 8895 * @return The height of your view, in pixels. 8896 */ 8897 @ViewDebug.ExportedProperty(category = "layout") 8898 public final int getHeight() { 8899 return mBottom - mTop; 8900 } 8901 8902 /** 8903 * Return the visible drawing bounds of your view. Fills in the output 8904 * rectangle with the values from getScrollX(), getScrollY(), 8905 * getWidth(), and getHeight(). These bounds do not account for any 8906 * transformation properties currently set on the view, such as 8907 * {@link #setScaleX(float)} or {@link #setRotation(float)}. 8908 * 8909 * @param outRect The (scrolled) drawing bounds of the view. 8910 */ 8911 public void getDrawingRect(Rect outRect) { 8912 outRect.left = mScrollX; 8913 outRect.top = mScrollY; 8914 outRect.right = mScrollX + (mRight - mLeft); 8915 outRect.bottom = mScrollY + (mBottom - mTop); 8916 } 8917 8918 /** 8919 * Like {@link #getMeasuredWidthAndState()}, but only returns the 8920 * raw width component (that is the result is masked by 8921 * {@link #MEASURED_SIZE_MASK}). 8922 * 8923 * @return The raw measured width of this view. 8924 */ 8925 public final int getMeasuredWidth() { 8926 return mMeasuredWidth & MEASURED_SIZE_MASK; 8927 } 8928 8929 /** 8930 * Return the full width measurement information for this view as computed 8931 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 8932 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 8933 * This should be used during measurement and layout calculations only. Use 8934 * {@link #getWidth()} to see how wide a view is after layout. 8935 * 8936 * @return The measured width of this view as a bit mask. 8937 */ 8938 public final int getMeasuredWidthAndState() { 8939 return mMeasuredWidth; 8940 } 8941 8942 /** 8943 * Like {@link #getMeasuredHeightAndState()}, but only returns the 8944 * raw width component (that is the result is masked by 8945 * {@link #MEASURED_SIZE_MASK}). 8946 * 8947 * @return The raw measured height of this view. 8948 */ 8949 public final int getMeasuredHeight() { 8950 return mMeasuredHeight & MEASURED_SIZE_MASK; 8951 } 8952 8953 /** 8954 * Return the full height measurement information for this view as computed 8955 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 8956 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 8957 * This should be used during measurement and layout calculations only. Use 8958 * {@link #getHeight()} to see how wide a view is after layout. 8959 * 8960 * @return The measured width of this view as a bit mask. 8961 */ 8962 public final int getMeasuredHeightAndState() { 8963 return mMeasuredHeight; 8964 } 8965 8966 /** 8967 * Return only the state bits of {@link #getMeasuredWidthAndState()} 8968 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 8969 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 8970 * and the height component is at the shifted bits 8971 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 8972 */ 8973 public final int getMeasuredState() { 8974 return (mMeasuredWidth&MEASURED_STATE_MASK) 8975 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 8976 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 8977 } 8978 8979 /** 8980 * The transform matrix of this view, which is calculated based on the current 8981 * roation, scale, and pivot properties. 8982 * 8983 * @see #getRotation() 8984 * @see #getScaleX() 8985 * @see #getScaleY() 8986 * @see #getPivotX() 8987 * @see #getPivotY() 8988 * @return The current transform matrix for the view 8989 */ 8990 public Matrix getMatrix() { 8991 if (mTransformationInfo != null) { 8992 updateMatrix(); 8993 return mTransformationInfo.mMatrix; 8994 } 8995 return Matrix.IDENTITY_MATRIX; 8996 } 8997 8998 /** 8999 * Utility function to determine if the value is far enough away from zero to be 9000 * considered non-zero. 9001 * @param value A floating point value to check for zero-ness 9002 * @return whether the passed-in value is far enough away from zero to be considered non-zero 9003 */ 9004 private static boolean nonzero(float value) { 9005 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON); 9006 } 9007 9008 /** 9009 * Returns true if the transform matrix is the identity matrix. 9010 * Recomputes the matrix if necessary. 9011 * 9012 * @return True if the transform matrix is the identity matrix, false otherwise. 9013 */ 9014 final boolean hasIdentityMatrix() { 9015 if (mTransformationInfo != null) { 9016 updateMatrix(); 9017 return mTransformationInfo.mMatrixIsIdentity; 9018 } 9019 return true; 9020 } 9021 9022 void ensureTransformationInfo() { 9023 if (mTransformationInfo == null) { 9024 mTransformationInfo = new TransformationInfo(); 9025 } 9026 } 9027 9028 /** 9029 * Recomputes the transform matrix if necessary. 9030 */ 9031 private void updateMatrix() { 9032 final TransformationInfo info = mTransformationInfo; 9033 if (info == null) { 9034 return; 9035 } 9036 if (info.mMatrixDirty) { 9037 // transform-related properties have changed since the last time someone 9038 // asked for the matrix; recalculate it with the current values 9039 9040 // Figure out if we need to update the pivot point 9041 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 9042 if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) { 9043 info.mPrevWidth = mRight - mLeft; 9044 info.mPrevHeight = mBottom - mTop; 9045 info.mPivotX = info.mPrevWidth / 2f; 9046 info.mPivotY = info.mPrevHeight / 2f; 9047 } 9048 } 9049 info.mMatrix.reset(); 9050 if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) { 9051 info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY); 9052 info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY); 9053 info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY); 9054 } else { 9055 if (info.mCamera == null) { 9056 info.mCamera = new Camera(); 9057 info.matrix3D = new Matrix(); 9058 } 9059 info.mCamera.save(); 9060 info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY); 9061 info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation); 9062 info.mCamera.getMatrix(info.matrix3D); 9063 info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY); 9064 info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX, 9065 info.mPivotY + info.mTranslationY); 9066 info.mMatrix.postConcat(info.matrix3D); 9067 info.mCamera.restore(); 9068 } 9069 info.mMatrixDirty = false; 9070 info.mMatrixIsIdentity = info.mMatrix.isIdentity(); 9071 info.mInverseMatrixDirty = true; 9072 } 9073 } 9074 9075 /** 9076 * Utility method to retrieve the inverse of the current mMatrix property. 9077 * We cache the matrix to avoid recalculating it when transform properties 9078 * have not changed. 9079 * 9080 * @return The inverse of the current matrix of this view. 9081 */ 9082 final Matrix getInverseMatrix() { 9083 final TransformationInfo info = mTransformationInfo; 9084 if (info != null) { 9085 updateMatrix(); 9086 if (info.mInverseMatrixDirty) { 9087 if (info.mInverseMatrix == null) { 9088 info.mInverseMatrix = new Matrix(); 9089 } 9090 info.mMatrix.invert(info.mInverseMatrix); 9091 info.mInverseMatrixDirty = false; 9092 } 9093 return info.mInverseMatrix; 9094 } 9095 return Matrix.IDENTITY_MATRIX; 9096 } 9097 9098 /** 9099 * Gets the distance along the Z axis from the camera to this view. 9100 * 9101 * @see #setCameraDistance(float) 9102 * 9103 * @return The distance along the Z axis. 9104 */ 9105 public float getCameraDistance() { 9106 ensureTransformationInfo(); 9107 final float dpi = mResources.getDisplayMetrics().densityDpi; 9108 final TransformationInfo info = mTransformationInfo; 9109 if (info.mCamera == null) { 9110 info.mCamera = new Camera(); 9111 info.matrix3D = new Matrix(); 9112 } 9113 return -(info.mCamera.getLocationZ() * dpi); 9114 } 9115 9116 /** 9117 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 9118 * views are drawn) from the camera to this view. The camera's distance 9119 * affects 3D transformations, for instance rotations around the X and Y 9120 * axis. If the rotationX or rotationY properties are changed and this view is 9121 * large (more than half the size of the screen), it is recommended to always 9122 * use a camera distance that's greater than the height (X axis rotation) or 9123 * the width (Y axis rotation) of this view.</p> 9124 * 9125 * <p>The distance of the camera from the view plane can have an affect on the 9126 * perspective distortion of the view when it is rotated around the x or y axis. 9127 * For example, a large distance will result in a large viewing angle, and there 9128 * will not be much perspective distortion of the view as it rotates. A short 9129 * distance may cause much more perspective distortion upon rotation, and can 9130 * also result in some drawing artifacts if the rotated view ends up partially 9131 * behind the camera (which is why the recommendation is to use a distance at 9132 * least as far as the size of the view, if the view is to be rotated.)</p> 9133 * 9134 * <p>The distance is expressed in "depth pixels." The default distance depends 9135 * on the screen density. For instance, on a medium density display, the 9136 * default distance is 1280. On a high density display, the default distance 9137 * is 1920.</p> 9138 * 9139 * <p>If you want to specify a distance that leads to visually consistent 9140 * results across various densities, use the following formula:</p> 9141 * <pre> 9142 * float scale = context.getResources().getDisplayMetrics().density; 9143 * view.setCameraDistance(distance * scale); 9144 * </pre> 9145 * 9146 * <p>The density scale factor of a high density display is 1.5, 9147 * and 1920 = 1280 * 1.5.</p> 9148 * 9149 * @param distance The distance in "depth pixels", if negative the opposite 9150 * value is used 9151 * 9152 * @see #setRotationX(float) 9153 * @see #setRotationY(float) 9154 */ 9155 public void setCameraDistance(float distance) { 9156 invalidateViewProperty(true, false); 9157 9158 ensureTransformationInfo(); 9159 final float dpi = mResources.getDisplayMetrics().densityDpi; 9160 final TransformationInfo info = mTransformationInfo; 9161 if (info.mCamera == null) { 9162 info.mCamera = new Camera(); 9163 info.matrix3D = new Matrix(); 9164 } 9165 9166 info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi); 9167 info.mMatrixDirty = true; 9168 9169 invalidateViewProperty(false, false); 9170 if (mDisplayList != null) { 9171 mDisplayList.setCameraDistance(-Math.abs(distance) / dpi); 9172 } 9173 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9174 // View was rejected last time it was drawn by its parent; this may have changed 9175 invalidateParentIfNeeded(); 9176 } 9177 } 9178 9179 /** 9180 * The degrees that the view is rotated around the pivot point. 9181 * 9182 * @see #setRotation(float) 9183 * @see #getPivotX() 9184 * @see #getPivotY() 9185 * 9186 * @return The degrees of rotation. 9187 */ 9188 @ViewDebug.ExportedProperty(category = "drawing") 9189 public float getRotation() { 9190 return mTransformationInfo != null ? mTransformationInfo.mRotation : 0; 9191 } 9192 9193 /** 9194 * Sets the degrees that the view is rotated around the pivot point. Increasing values 9195 * result in clockwise rotation. 9196 * 9197 * @param rotation The degrees of rotation. 9198 * 9199 * @see #getRotation() 9200 * @see #getPivotX() 9201 * @see #getPivotY() 9202 * @see #setRotationX(float) 9203 * @see #setRotationY(float) 9204 * 9205 * @attr ref android.R.styleable#View_rotation 9206 */ 9207 public void setRotation(float rotation) { 9208 ensureTransformationInfo(); 9209 final TransformationInfo info = mTransformationInfo; 9210 if (info.mRotation != rotation) { 9211 // Double-invalidation is necessary to capture view's old and new areas 9212 invalidateViewProperty(true, false); 9213 info.mRotation = rotation; 9214 info.mMatrixDirty = true; 9215 invalidateViewProperty(false, true); 9216 if (mDisplayList != null) { 9217 mDisplayList.setRotation(rotation); 9218 } 9219 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9220 // View was rejected last time it was drawn by its parent; this may have changed 9221 invalidateParentIfNeeded(); 9222 } 9223 } 9224 } 9225 9226 /** 9227 * The degrees that the view is rotated around the vertical axis through the pivot point. 9228 * 9229 * @see #getPivotX() 9230 * @see #getPivotY() 9231 * @see #setRotationY(float) 9232 * 9233 * @return The degrees of Y rotation. 9234 */ 9235 @ViewDebug.ExportedProperty(category = "drawing") 9236 public float getRotationY() { 9237 return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0; 9238 } 9239 9240 /** 9241 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 9242 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 9243 * down the y axis. 9244 * 9245 * When rotating large views, it is recommended to adjust the camera distance 9246 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 9247 * 9248 * @param rotationY The degrees of Y rotation. 9249 * 9250 * @see #getRotationY() 9251 * @see #getPivotX() 9252 * @see #getPivotY() 9253 * @see #setRotation(float) 9254 * @see #setRotationX(float) 9255 * @see #setCameraDistance(float) 9256 * 9257 * @attr ref android.R.styleable#View_rotationY 9258 */ 9259 public void setRotationY(float rotationY) { 9260 ensureTransformationInfo(); 9261 final TransformationInfo info = mTransformationInfo; 9262 if (info.mRotationY != rotationY) { 9263 invalidateViewProperty(true, false); 9264 info.mRotationY = rotationY; 9265 info.mMatrixDirty = true; 9266 invalidateViewProperty(false, true); 9267 if (mDisplayList != null) { 9268 mDisplayList.setRotationY(rotationY); 9269 } 9270 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9271 // View was rejected last time it was drawn by its parent; this may have changed 9272 invalidateParentIfNeeded(); 9273 } 9274 } 9275 } 9276 9277 /** 9278 * The degrees that the view is rotated around the horizontal axis through the pivot point. 9279 * 9280 * @see #getPivotX() 9281 * @see #getPivotY() 9282 * @see #setRotationX(float) 9283 * 9284 * @return The degrees of X rotation. 9285 */ 9286 @ViewDebug.ExportedProperty(category = "drawing") 9287 public float getRotationX() { 9288 return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0; 9289 } 9290 9291 /** 9292 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 9293 * Increasing values result in clockwise rotation from the viewpoint of looking down the 9294 * x axis. 9295 * 9296 * When rotating large views, it is recommended to adjust the camera distance 9297 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 9298 * 9299 * @param rotationX The degrees of X rotation. 9300 * 9301 * @see #getRotationX() 9302 * @see #getPivotX() 9303 * @see #getPivotY() 9304 * @see #setRotation(float) 9305 * @see #setRotationY(float) 9306 * @see #setCameraDistance(float) 9307 * 9308 * @attr ref android.R.styleable#View_rotationX 9309 */ 9310 public void setRotationX(float rotationX) { 9311 ensureTransformationInfo(); 9312 final TransformationInfo info = mTransformationInfo; 9313 if (info.mRotationX != rotationX) { 9314 invalidateViewProperty(true, false); 9315 info.mRotationX = rotationX; 9316 info.mMatrixDirty = true; 9317 invalidateViewProperty(false, true); 9318 if (mDisplayList != null) { 9319 mDisplayList.setRotationX(rotationX); 9320 } 9321 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9322 // View was rejected last time it was drawn by its parent; this may have changed 9323 invalidateParentIfNeeded(); 9324 } 9325 } 9326 } 9327 9328 /** 9329 * The amount that the view is scaled in x around the pivot point, as a proportion of 9330 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 9331 * 9332 * <p>By default, this is 1.0f. 9333 * 9334 * @see #getPivotX() 9335 * @see #getPivotY() 9336 * @return The scaling factor. 9337 */ 9338 @ViewDebug.ExportedProperty(category = "drawing") 9339 public float getScaleX() { 9340 return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1; 9341 } 9342 9343 /** 9344 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 9345 * the view's unscaled width. A value of 1 means that no scaling is applied. 9346 * 9347 * @param scaleX The scaling factor. 9348 * @see #getPivotX() 9349 * @see #getPivotY() 9350 * 9351 * @attr ref android.R.styleable#View_scaleX 9352 */ 9353 public void setScaleX(float scaleX) { 9354 ensureTransformationInfo(); 9355 final TransformationInfo info = mTransformationInfo; 9356 if (info.mScaleX != scaleX) { 9357 invalidateViewProperty(true, false); 9358 info.mScaleX = scaleX; 9359 info.mMatrixDirty = true; 9360 invalidateViewProperty(false, true); 9361 if (mDisplayList != null) { 9362 mDisplayList.setScaleX(scaleX); 9363 } 9364 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9365 // View was rejected last time it was drawn by its parent; this may have changed 9366 invalidateParentIfNeeded(); 9367 } 9368 } 9369 } 9370 9371 /** 9372 * The amount that the view is scaled in y around the pivot point, as a proportion of 9373 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 9374 * 9375 * <p>By default, this is 1.0f. 9376 * 9377 * @see #getPivotX() 9378 * @see #getPivotY() 9379 * @return The scaling factor. 9380 */ 9381 @ViewDebug.ExportedProperty(category = "drawing") 9382 public float getScaleY() { 9383 return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1; 9384 } 9385 9386 /** 9387 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 9388 * the view's unscaled width. A value of 1 means that no scaling is applied. 9389 * 9390 * @param scaleY The scaling factor. 9391 * @see #getPivotX() 9392 * @see #getPivotY() 9393 * 9394 * @attr ref android.R.styleable#View_scaleY 9395 */ 9396 public void setScaleY(float scaleY) { 9397 ensureTransformationInfo(); 9398 final TransformationInfo info = mTransformationInfo; 9399 if (info.mScaleY != scaleY) { 9400 invalidateViewProperty(true, false); 9401 info.mScaleY = scaleY; 9402 info.mMatrixDirty = true; 9403 invalidateViewProperty(false, true); 9404 if (mDisplayList != null) { 9405 mDisplayList.setScaleY(scaleY); 9406 } 9407 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9408 // View was rejected last time it was drawn by its parent; this may have changed 9409 invalidateParentIfNeeded(); 9410 } 9411 } 9412 } 9413 9414 /** 9415 * The x location of the point around which the view is {@link #setRotation(float) rotated} 9416 * and {@link #setScaleX(float) scaled}. 9417 * 9418 * @see #getRotation() 9419 * @see #getScaleX() 9420 * @see #getScaleY() 9421 * @see #getPivotY() 9422 * @return The x location of the pivot point. 9423 * 9424 * @attr ref android.R.styleable#View_transformPivotX 9425 */ 9426 @ViewDebug.ExportedProperty(category = "drawing") 9427 public float getPivotX() { 9428 return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0; 9429 } 9430 9431 /** 9432 * Sets the x location of the point around which the view is 9433 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 9434 * By default, the pivot point is centered on the object. 9435 * Setting this property disables this behavior and causes the view to use only the 9436 * explicitly set pivotX and pivotY values. 9437 * 9438 * @param pivotX The x location of the pivot point. 9439 * @see #getRotation() 9440 * @see #getScaleX() 9441 * @see #getScaleY() 9442 * @see #getPivotY() 9443 * 9444 * @attr ref android.R.styleable#View_transformPivotX 9445 */ 9446 public void setPivotX(float pivotX) { 9447 ensureTransformationInfo(); 9448 mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET; 9449 final TransformationInfo info = mTransformationInfo; 9450 if (info.mPivotX != pivotX) { 9451 invalidateViewProperty(true, false); 9452 info.mPivotX = pivotX; 9453 info.mMatrixDirty = true; 9454 invalidateViewProperty(false, true); 9455 if (mDisplayList != null) { 9456 mDisplayList.setPivotX(pivotX); 9457 } 9458 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9459 // View was rejected last time it was drawn by its parent; this may have changed 9460 invalidateParentIfNeeded(); 9461 } 9462 } 9463 } 9464 9465 /** 9466 * The y location of the point around which the view is {@link #setRotation(float) rotated} 9467 * and {@link #setScaleY(float) scaled}. 9468 * 9469 * @see #getRotation() 9470 * @see #getScaleX() 9471 * @see #getScaleY() 9472 * @see #getPivotY() 9473 * @return The y location of the pivot point. 9474 * 9475 * @attr ref android.R.styleable#View_transformPivotY 9476 */ 9477 @ViewDebug.ExportedProperty(category = "drawing") 9478 public float getPivotY() { 9479 return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0; 9480 } 9481 9482 /** 9483 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 9484 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 9485 * Setting this property disables this behavior and causes the view to use only the 9486 * explicitly set pivotX and pivotY values. 9487 * 9488 * @param pivotY The y location of the pivot point. 9489 * @see #getRotation() 9490 * @see #getScaleX() 9491 * @see #getScaleY() 9492 * @see #getPivotY() 9493 * 9494 * @attr ref android.R.styleable#View_transformPivotY 9495 */ 9496 public void setPivotY(float pivotY) { 9497 ensureTransformationInfo(); 9498 mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET; 9499 final TransformationInfo info = mTransformationInfo; 9500 if (info.mPivotY != pivotY) { 9501 invalidateViewProperty(true, false); 9502 info.mPivotY = pivotY; 9503 info.mMatrixDirty = true; 9504 invalidateViewProperty(false, true); 9505 if (mDisplayList != null) { 9506 mDisplayList.setPivotY(pivotY); 9507 } 9508 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9509 // View was rejected last time it was drawn by its parent; this may have changed 9510 invalidateParentIfNeeded(); 9511 } 9512 } 9513 } 9514 9515 /** 9516 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 9517 * completely transparent and 1 means the view is completely opaque. 9518 * 9519 * <p>By default this is 1.0f. 9520 * @return The opacity of the view. 9521 */ 9522 @ViewDebug.ExportedProperty(category = "drawing") 9523 public float getAlpha() { 9524 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 9525 } 9526 9527 /** 9528 * Returns whether this View has content which overlaps. This function, intended to be 9529 * overridden by specific View types, is an optimization when alpha is set on a view. If 9530 * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer 9531 * and then composited it into place, which can be expensive. If the view has no overlapping 9532 * rendering, the view can draw each primitive with the appropriate alpha value directly. 9533 * An example of overlapping rendering is a TextView with a background image, such as a 9534 * Button. An example of non-overlapping rendering is a TextView with no background, or 9535 * an ImageView with only the foreground image. The default implementation returns true; 9536 * subclasses should override if they have cases which can be optimized. 9537 * 9538 * @return true if the content in this view might overlap, false otherwise. 9539 */ 9540 public boolean hasOverlappingRendering() { 9541 return true; 9542 } 9543 9544 /** 9545 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 9546 * completely transparent and 1 means the view is completely opaque.</p> 9547 * 9548 * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant 9549 * performance implications, especially for large views. It is best to use the alpha property 9550 * sparingly and transiently, as in the case of fading animations.</p> 9551 * 9552 * <p>For a view with a frequently changing alpha, such as during a fading animation, it is 9553 * strongly recommended for performance reasons to either override 9554 * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a 9555 * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p> 9556 * 9557 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 9558 * responsible for applying the opacity itself.</p> 9559 * 9560 * <p>Note that if the view is backed by a 9561 * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a 9562 * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than 9563 * 1.0 will supercede the alpha of the layer paint.</p> 9564 * 9565 * @param alpha The opacity of the view. 9566 * 9567 * @see #hasOverlappingRendering() 9568 * @see #setLayerType(int, android.graphics.Paint) 9569 * 9570 * @attr ref android.R.styleable#View_alpha 9571 */ 9572 public void setAlpha(float alpha) { 9573 ensureTransformationInfo(); 9574 if (mTransformationInfo.mAlpha != alpha) { 9575 mTransformationInfo.mAlpha = alpha; 9576 if (onSetAlpha((int) (alpha * 255))) { 9577 mPrivateFlags |= PFLAG_ALPHA_SET; 9578 // subclass is handling alpha - don't optimize rendering cache invalidation 9579 invalidateParentCaches(); 9580 invalidate(true); 9581 } else { 9582 mPrivateFlags &= ~PFLAG_ALPHA_SET; 9583 invalidateViewProperty(true, false); 9584 if (mDisplayList != null) { 9585 mDisplayList.setAlpha(alpha); 9586 } 9587 } 9588 } 9589 } 9590 9591 /** 9592 * Faster version of setAlpha() which performs the same steps except there are 9593 * no calls to invalidate(). The caller of this function should perform proper invalidation 9594 * on the parent and this object. The return value indicates whether the subclass handles 9595 * alpha (the return value for onSetAlpha()). 9596 * 9597 * @param alpha The new value for the alpha property 9598 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 9599 * the new value for the alpha property is different from the old value 9600 */ 9601 boolean setAlphaNoInvalidation(float alpha) { 9602 ensureTransformationInfo(); 9603 if (mTransformationInfo.mAlpha != alpha) { 9604 mTransformationInfo.mAlpha = alpha; 9605 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 9606 if (subclassHandlesAlpha) { 9607 mPrivateFlags |= PFLAG_ALPHA_SET; 9608 return true; 9609 } else { 9610 mPrivateFlags &= ~PFLAG_ALPHA_SET; 9611 if (mDisplayList != null) { 9612 mDisplayList.setAlpha(alpha); 9613 } 9614 } 9615 } 9616 return false; 9617 } 9618 9619 /** 9620 * Top position of this view relative to its parent. 9621 * 9622 * @return The top of this view, in pixels. 9623 */ 9624 @ViewDebug.CapturedViewProperty 9625 public final int getTop() { 9626 return mTop; 9627 } 9628 9629 /** 9630 * Sets the top position of this view relative to its parent. This method is meant to be called 9631 * by the layout system and should not generally be called otherwise, because the property 9632 * may be changed at any time by the layout. 9633 * 9634 * @param top The top of this view, in pixels. 9635 */ 9636 public final void setTop(int top) { 9637 if (top != mTop) { 9638 updateMatrix(); 9639 final boolean matrixIsIdentity = mTransformationInfo == null 9640 || mTransformationInfo.mMatrixIsIdentity; 9641 if (matrixIsIdentity) { 9642 if (mAttachInfo != null) { 9643 int minTop; 9644 int yLoc; 9645 if (top < mTop) { 9646 minTop = top; 9647 yLoc = top - mTop; 9648 } else { 9649 minTop = mTop; 9650 yLoc = 0; 9651 } 9652 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 9653 } 9654 } else { 9655 // Double-invalidation is necessary to capture view's old and new areas 9656 invalidate(true); 9657 } 9658 9659 int width = mRight - mLeft; 9660 int oldHeight = mBottom - mTop; 9661 9662 mTop = top; 9663 if (mDisplayList != null) { 9664 mDisplayList.setTop(mTop); 9665 } 9666 9667 sizeChange(width, mBottom - mTop, width, oldHeight); 9668 9669 if (!matrixIsIdentity) { 9670 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 9671 // A change in dimension means an auto-centered pivot point changes, too 9672 mTransformationInfo.mMatrixDirty = true; 9673 } 9674 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 9675 invalidate(true); 9676 } 9677 mBackgroundSizeChanged = true; 9678 invalidateParentIfNeeded(); 9679 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9680 // View was rejected last time it was drawn by its parent; this may have changed 9681 invalidateParentIfNeeded(); 9682 } 9683 } 9684 } 9685 9686 /** 9687 * Bottom position of this view relative to its parent. 9688 * 9689 * @return The bottom of this view, in pixels. 9690 */ 9691 @ViewDebug.CapturedViewProperty 9692 public final int getBottom() { 9693 return mBottom; 9694 } 9695 9696 /** 9697 * True if this view has changed since the last time being drawn. 9698 * 9699 * @return The dirty state of this view. 9700 */ 9701 public boolean isDirty() { 9702 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 9703 } 9704 9705 /** 9706 * Sets the bottom position of this view relative to its parent. This method is meant to be 9707 * called by the layout system and should not generally be called otherwise, because the 9708 * property may be changed at any time by the layout. 9709 * 9710 * @param bottom The bottom of this view, in pixels. 9711 */ 9712 public final void setBottom(int bottom) { 9713 if (bottom != mBottom) { 9714 updateMatrix(); 9715 final boolean matrixIsIdentity = mTransformationInfo == null 9716 || mTransformationInfo.mMatrixIsIdentity; 9717 if (matrixIsIdentity) { 9718 if (mAttachInfo != null) { 9719 int maxBottom; 9720 if (bottom < mBottom) { 9721 maxBottom = mBottom; 9722 } else { 9723 maxBottom = bottom; 9724 } 9725 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 9726 } 9727 } else { 9728 // Double-invalidation is necessary to capture view's old and new areas 9729 invalidate(true); 9730 } 9731 9732 int width = mRight - mLeft; 9733 int oldHeight = mBottom - mTop; 9734 9735 mBottom = bottom; 9736 if (mDisplayList != null) { 9737 mDisplayList.setBottom(mBottom); 9738 } 9739 9740 sizeChange(width, mBottom - mTop, width, oldHeight); 9741 9742 if (!matrixIsIdentity) { 9743 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 9744 // A change in dimension means an auto-centered pivot point changes, too 9745 mTransformationInfo.mMatrixDirty = true; 9746 } 9747 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 9748 invalidate(true); 9749 } 9750 mBackgroundSizeChanged = true; 9751 invalidateParentIfNeeded(); 9752 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9753 // View was rejected last time it was drawn by its parent; this may have changed 9754 invalidateParentIfNeeded(); 9755 } 9756 } 9757 } 9758 9759 /** 9760 * Left position of this view relative to its parent. 9761 * 9762 * @return The left edge of this view, in pixels. 9763 */ 9764 @ViewDebug.CapturedViewProperty 9765 public final int getLeft() { 9766 return mLeft; 9767 } 9768 9769 /** 9770 * Sets the left position of this view relative to its parent. This method is meant to be called 9771 * by the layout system and should not generally be called otherwise, because the property 9772 * may be changed at any time by the layout. 9773 * 9774 * @param left The bottom of this view, in pixels. 9775 */ 9776 public final void setLeft(int left) { 9777 if (left != mLeft) { 9778 updateMatrix(); 9779 final boolean matrixIsIdentity = mTransformationInfo == null 9780 || mTransformationInfo.mMatrixIsIdentity; 9781 if (matrixIsIdentity) { 9782 if (mAttachInfo != null) { 9783 int minLeft; 9784 int xLoc; 9785 if (left < mLeft) { 9786 minLeft = left; 9787 xLoc = left - mLeft; 9788 } else { 9789 minLeft = mLeft; 9790 xLoc = 0; 9791 } 9792 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 9793 } 9794 } else { 9795 // Double-invalidation is necessary to capture view's old and new areas 9796 invalidate(true); 9797 } 9798 9799 int oldWidth = mRight - mLeft; 9800 int height = mBottom - mTop; 9801 9802 mLeft = left; 9803 if (mDisplayList != null) { 9804 mDisplayList.setLeft(left); 9805 } 9806 9807 sizeChange(mRight - mLeft, height, oldWidth, height); 9808 9809 if (!matrixIsIdentity) { 9810 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 9811 // A change in dimension means an auto-centered pivot point changes, too 9812 mTransformationInfo.mMatrixDirty = true; 9813 } 9814 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 9815 invalidate(true); 9816 } 9817 mBackgroundSizeChanged = true; 9818 invalidateParentIfNeeded(); 9819 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9820 // View was rejected last time it was drawn by its parent; this may have changed 9821 invalidateParentIfNeeded(); 9822 } 9823 } 9824 } 9825 9826 /** 9827 * Right position of this view relative to its parent. 9828 * 9829 * @return The right edge of this view, in pixels. 9830 */ 9831 @ViewDebug.CapturedViewProperty 9832 public final int getRight() { 9833 return mRight; 9834 } 9835 9836 /** 9837 * Sets the right position of this view relative to its parent. This method is meant to be called 9838 * by the layout system and should not generally be called otherwise, because the property 9839 * may be changed at any time by the layout. 9840 * 9841 * @param right The bottom of this view, in pixels. 9842 */ 9843 public final void setRight(int right) { 9844 if (right != mRight) { 9845 updateMatrix(); 9846 final boolean matrixIsIdentity = mTransformationInfo == null 9847 || mTransformationInfo.mMatrixIsIdentity; 9848 if (matrixIsIdentity) { 9849 if (mAttachInfo != null) { 9850 int maxRight; 9851 if (right < mRight) { 9852 maxRight = mRight; 9853 } else { 9854 maxRight = right; 9855 } 9856 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 9857 } 9858 } else { 9859 // Double-invalidation is necessary to capture view's old and new areas 9860 invalidate(true); 9861 } 9862 9863 int oldWidth = mRight - mLeft; 9864 int height = mBottom - mTop; 9865 9866 mRight = right; 9867 if (mDisplayList != null) { 9868 mDisplayList.setRight(mRight); 9869 } 9870 9871 sizeChange(mRight - mLeft, height, oldWidth, height); 9872 9873 if (!matrixIsIdentity) { 9874 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 9875 // A change in dimension means an auto-centered pivot point changes, too 9876 mTransformationInfo.mMatrixDirty = true; 9877 } 9878 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 9879 invalidate(true); 9880 } 9881 mBackgroundSizeChanged = true; 9882 invalidateParentIfNeeded(); 9883 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9884 // View was rejected last time it was drawn by its parent; this may have changed 9885 invalidateParentIfNeeded(); 9886 } 9887 } 9888 } 9889 9890 /** 9891 * The visual x position of this view, in pixels. This is equivalent to the 9892 * {@link #setTranslationX(float) translationX} property plus the current 9893 * {@link #getLeft() left} property. 9894 * 9895 * @return The visual x position of this view, in pixels. 9896 */ 9897 @ViewDebug.ExportedProperty(category = "drawing") 9898 public float getX() { 9899 return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0); 9900 } 9901 9902 /** 9903 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 9904 * {@link #setTranslationX(float) translationX} property to be the difference between 9905 * the x value passed in and the current {@link #getLeft() left} property. 9906 * 9907 * @param x The visual x position of this view, in pixels. 9908 */ 9909 public void setX(float x) { 9910 setTranslationX(x - mLeft); 9911 } 9912 9913 /** 9914 * The visual y position of this view, in pixels. This is equivalent to the 9915 * {@link #setTranslationY(float) translationY} property plus the current 9916 * {@link #getTop() top} property. 9917 * 9918 * @return The visual y position of this view, in pixels. 9919 */ 9920 @ViewDebug.ExportedProperty(category = "drawing") 9921 public float getY() { 9922 return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0); 9923 } 9924 9925 /** 9926 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 9927 * {@link #setTranslationY(float) translationY} property to be the difference between 9928 * the y value passed in and the current {@link #getTop() top} property. 9929 * 9930 * @param y The visual y position of this view, in pixels. 9931 */ 9932 public void setY(float y) { 9933 setTranslationY(y - mTop); 9934 } 9935 9936 9937 /** 9938 * The horizontal location of this view relative to its {@link #getLeft() left} position. 9939 * This position is post-layout, in addition to wherever the object's 9940 * layout placed it. 9941 * 9942 * @return The horizontal position of this view relative to its left position, in pixels. 9943 */ 9944 @ViewDebug.ExportedProperty(category = "drawing") 9945 public float getTranslationX() { 9946 return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0; 9947 } 9948 9949 /** 9950 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 9951 * This effectively positions the object post-layout, in addition to wherever the object's 9952 * layout placed it. 9953 * 9954 * @param translationX The horizontal position of this view relative to its left position, 9955 * in pixels. 9956 * 9957 * @attr ref android.R.styleable#View_translationX 9958 */ 9959 public void setTranslationX(float translationX) { 9960 ensureTransformationInfo(); 9961 final TransformationInfo info = mTransformationInfo; 9962 if (info.mTranslationX != translationX) { 9963 // Double-invalidation is necessary to capture view's old and new areas 9964 invalidateViewProperty(true, false); 9965 info.mTranslationX = translationX; 9966 info.mMatrixDirty = true; 9967 invalidateViewProperty(false, true); 9968 if (mDisplayList != null) { 9969 mDisplayList.setTranslationX(translationX); 9970 } 9971 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9972 // View was rejected last time it was drawn by its parent; this may have changed 9973 invalidateParentIfNeeded(); 9974 } 9975 } 9976 } 9977 9978 /** 9979 * The horizontal location of this view relative to its {@link #getTop() top} position. 9980 * This position is post-layout, in addition to wherever the object's 9981 * layout placed it. 9982 * 9983 * @return The vertical position of this view relative to its top position, 9984 * in pixels. 9985 */ 9986 @ViewDebug.ExportedProperty(category = "drawing") 9987 public float getTranslationY() { 9988 return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0; 9989 } 9990 9991 /** 9992 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 9993 * This effectively positions the object post-layout, in addition to wherever the object's 9994 * layout placed it. 9995 * 9996 * @param translationY The vertical position of this view relative to its top position, 9997 * in pixels. 9998 * 9999 * @attr ref android.R.styleable#View_translationY 10000 */ 10001 public void setTranslationY(float translationY) { 10002 ensureTransformationInfo(); 10003 final TransformationInfo info = mTransformationInfo; 10004 if (info.mTranslationY != translationY) { 10005 invalidateViewProperty(true, false); 10006 info.mTranslationY = translationY; 10007 info.mMatrixDirty = true; 10008 invalidateViewProperty(false, true); 10009 if (mDisplayList != null) { 10010 mDisplayList.setTranslationY(translationY); 10011 } 10012 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10013 // View was rejected last time it was drawn by its parent; this may have changed 10014 invalidateParentIfNeeded(); 10015 } 10016 } 10017 } 10018 10019 /** 10020 * Hit rectangle in parent's coordinates 10021 * 10022 * @param outRect The hit rectangle of the view. 10023 */ 10024 public void getHitRect(Rect outRect) { 10025 updateMatrix(); 10026 final TransformationInfo info = mTransformationInfo; 10027 if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) { 10028 outRect.set(mLeft, mTop, mRight, mBottom); 10029 } else { 10030 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 10031 tmpRect.set(0, 0, getWidth(), getHeight()); 10032 info.mMatrix.mapRect(tmpRect); 10033 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 10034 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 10035 } 10036 } 10037 10038 /** 10039 * Determines whether the given point, in local coordinates is inside the view. 10040 */ 10041 /*package*/ final boolean pointInView(float localX, float localY) { 10042 return localX >= 0 && localX < (mRight - mLeft) 10043 && localY >= 0 && localY < (mBottom - mTop); 10044 } 10045 10046 /** 10047 * Utility method to determine whether the given point, in local coordinates, 10048 * is inside the view, where the area of the view is expanded by the slop factor. 10049 * This method is called while processing touch-move events to determine if the event 10050 * is still within the view. 10051 */ 10052 private boolean pointInView(float localX, float localY, float slop) { 10053 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 10054 localY < ((mBottom - mTop) + slop); 10055 } 10056 10057 /** 10058 * When a view has focus and the user navigates away from it, the next view is searched for 10059 * starting from the rectangle filled in by this method. 10060 * 10061 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 10062 * of the view. However, if your view maintains some idea of internal selection, 10063 * such as a cursor, or a selected row or column, you should override this method and 10064 * fill in a more specific rectangle. 10065 * 10066 * @param r The rectangle to fill in, in this view's coordinates. 10067 */ 10068 public void getFocusedRect(Rect r) { 10069 getDrawingRect(r); 10070 } 10071 10072 /** 10073 * If some part of this view is not clipped by any of its parents, then 10074 * return that area in r in global (root) coordinates. To convert r to local 10075 * coordinates (without taking possible View rotations into account), offset 10076 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 10077 * If the view is completely clipped or translated out, return false. 10078 * 10079 * @param r If true is returned, r holds the global coordinates of the 10080 * visible portion of this view. 10081 * @param globalOffset If true is returned, globalOffset holds the dx,dy 10082 * between this view and its root. globalOffet may be null. 10083 * @return true if r is non-empty (i.e. part of the view is visible at the 10084 * root level. 10085 */ 10086 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 10087 int width = mRight - mLeft; 10088 int height = mBottom - mTop; 10089 if (width > 0 && height > 0) { 10090 r.set(0, 0, width, height); 10091 if (globalOffset != null) { 10092 globalOffset.set(-mScrollX, -mScrollY); 10093 } 10094 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 10095 } 10096 return false; 10097 } 10098 10099 public final boolean getGlobalVisibleRect(Rect r) { 10100 return getGlobalVisibleRect(r, null); 10101 } 10102 10103 public final boolean getLocalVisibleRect(Rect r) { 10104 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 10105 if (getGlobalVisibleRect(r, offset)) { 10106 r.offset(-offset.x, -offset.y); // make r local 10107 return true; 10108 } 10109 return false; 10110 } 10111 10112 /** 10113 * Offset this view's vertical location by the specified number of pixels. 10114 * 10115 * @param offset the number of pixels to offset the view by 10116 */ 10117 public void offsetTopAndBottom(int offset) { 10118 if (offset != 0) { 10119 updateMatrix(); 10120 final boolean matrixIsIdentity = mTransformationInfo == null 10121 || mTransformationInfo.mMatrixIsIdentity; 10122 if (matrixIsIdentity) { 10123 if (mDisplayList != null) { 10124 invalidateViewProperty(false, false); 10125 } else { 10126 final ViewParent p = mParent; 10127 if (p != null && mAttachInfo != null) { 10128 final Rect r = mAttachInfo.mTmpInvalRect; 10129 int minTop; 10130 int maxBottom; 10131 int yLoc; 10132 if (offset < 0) { 10133 minTop = mTop + offset; 10134 maxBottom = mBottom; 10135 yLoc = offset; 10136 } else { 10137 minTop = mTop; 10138 maxBottom = mBottom + offset; 10139 yLoc = 0; 10140 } 10141 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 10142 p.invalidateChild(this, r); 10143 } 10144 } 10145 } else { 10146 invalidateViewProperty(false, false); 10147 } 10148 10149 mTop += offset; 10150 mBottom += offset; 10151 if (mDisplayList != null) { 10152 mDisplayList.offsetTopAndBottom(offset); 10153 invalidateViewProperty(false, false); 10154 } else { 10155 if (!matrixIsIdentity) { 10156 invalidateViewProperty(false, true); 10157 } 10158 invalidateParentIfNeeded(); 10159 } 10160 } 10161 } 10162 10163 /** 10164 * Offset this view's horizontal location by the specified amount of pixels. 10165 * 10166 * @param offset the number of pixels to offset the view by 10167 */ 10168 public void offsetLeftAndRight(int offset) { 10169 if (offset != 0) { 10170 updateMatrix(); 10171 final boolean matrixIsIdentity = mTransformationInfo == null 10172 || mTransformationInfo.mMatrixIsIdentity; 10173 if (matrixIsIdentity) { 10174 if (mDisplayList != null) { 10175 invalidateViewProperty(false, false); 10176 } else { 10177 final ViewParent p = mParent; 10178 if (p != null && mAttachInfo != null) { 10179 final Rect r = mAttachInfo.mTmpInvalRect; 10180 int minLeft; 10181 int maxRight; 10182 if (offset < 0) { 10183 minLeft = mLeft + offset; 10184 maxRight = mRight; 10185 } else { 10186 minLeft = mLeft; 10187 maxRight = mRight + offset; 10188 } 10189 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 10190 p.invalidateChild(this, r); 10191 } 10192 } 10193 } else { 10194 invalidateViewProperty(false, false); 10195 } 10196 10197 mLeft += offset; 10198 mRight += offset; 10199 if (mDisplayList != null) { 10200 mDisplayList.offsetLeftAndRight(offset); 10201 invalidateViewProperty(false, false); 10202 } else { 10203 if (!matrixIsIdentity) { 10204 invalidateViewProperty(false, true); 10205 } 10206 invalidateParentIfNeeded(); 10207 } 10208 } 10209 } 10210 10211 /** 10212 * Get the LayoutParams associated with this view. All views should have 10213 * layout parameters. These supply parameters to the <i>parent</i> of this 10214 * view specifying how it should be arranged. There are many subclasses of 10215 * ViewGroup.LayoutParams, and these correspond to the different subclasses 10216 * of ViewGroup that are responsible for arranging their children. 10217 * 10218 * This method may return null if this View is not attached to a parent 10219 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 10220 * was not invoked successfully. When a View is attached to a parent 10221 * ViewGroup, this method must not return null. 10222 * 10223 * @return The LayoutParams associated with this view, or null if no 10224 * parameters have been set yet 10225 */ 10226 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 10227 public ViewGroup.LayoutParams getLayoutParams() { 10228 return mLayoutParams; 10229 } 10230 10231 /** 10232 * Set the layout parameters associated with this view. These supply 10233 * parameters to the <i>parent</i> of this view specifying how it should be 10234 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 10235 * correspond to the different subclasses of ViewGroup that are responsible 10236 * for arranging their children. 10237 * 10238 * @param params The layout parameters for this view, cannot be null 10239 */ 10240 public void setLayoutParams(ViewGroup.LayoutParams params) { 10241 if (params == null) { 10242 throw new NullPointerException("Layout parameters cannot be null"); 10243 } 10244 mLayoutParams = params; 10245 resolveLayoutParams(); 10246 if (mParent instanceof ViewGroup) { 10247 ((ViewGroup) mParent).onSetLayoutParams(this, params); 10248 } 10249 requestLayout(); 10250 } 10251 10252 /** 10253 * Resolve the layout parameters depending on the resolved layout direction 10254 * 10255 * @hide 10256 */ 10257 public void resolveLayoutParams() { 10258 if (mLayoutParams != null) { 10259 mLayoutParams.resolveLayoutDirection(getLayoutDirection()); 10260 } 10261 } 10262 10263 /** 10264 * Set the scrolled position of your view. This will cause a call to 10265 * {@link #onScrollChanged(int, int, int, int)} and the view will be 10266 * invalidated. 10267 * @param x the x position to scroll to 10268 * @param y the y position to scroll to 10269 */ 10270 public void scrollTo(int x, int y) { 10271 if (mScrollX != x || mScrollY != y) { 10272 int oldX = mScrollX; 10273 int oldY = mScrollY; 10274 mScrollX = x; 10275 mScrollY = y; 10276 invalidateParentCaches(); 10277 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 10278 if (!awakenScrollBars()) { 10279 postInvalidateOnAnimation(); 10280 } 10281 } 10282 } 10283 10284 /** 10285 * Move the scrolled position of your view. This will cause a call to 10286 * {@link #onScrollChanged(int, int, int, int)} and the view will be 10287 * invalidated. 10288 * @param x the amount of pixels to scroll by horizontally 10289 * @param y the amount of pixels to scroll by vertically 10290 */ 10291 public void scrollBy(int x, int y) { 10292 scrollTo(mScrollX + x, mScrollY + y); 10293 } 10294 10295 /** 10296 * <p>Trigger the scrollbars to draw. When invoked this method starts an 10297 * animation to fade the scrollbars out after a default delay. If a subclass 10298 * provides animated scrolling, the start delay should equal the duration 10299 * of the scrolling animation.</p> 10300 * 10301 * <p>The animation starts only if at least one of the scrollbars is 10302 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 10303 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 10304 * this method returns true, and false otherwise. If the animation is 10305 * started, this method calls {@link #invalidate()}; in that case the 10306 * caller should not call {@link #invalidate()}.</p> 10307 * 10308 * <p>This method should be invoked every time a subclass directly updates 10309 * the scroll parameters.</p> 10310 * 10311 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 10312 * and {@link #scrollTo(int, int)}.</p> 10313 * 10314 * @return true if the animation is played, false otherwise 10315 * 10316 * @see #awakenScrollBars(int) 10317 * @see #scrollBy(int, int) 10318 * @see #scrollTo(int, int) 10319 * @see #isHorizontalScrollBarEnabled() 10320 * @see #isVerticalScrollBarEnabled() 10321 * @see #setHorizontalScrollBarEnabled(boolean) 10322 * @see #setVerticalScrollBarEnabled(boolean) 10323 */ 10324 protected boolean awakenScrollBars() { 10325 return mScrollCache != null && 10326 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 10327 } 10328 10329 /** 10330 * Trigger the scrollbars to draw. 10331 * This method differs from awakenScrollBars() only in its default duration. 10332 * initialAwakenScrollBars() will show the scroll bars for longer than 10333 * usual to give the user more of a chance to notice them. 10334 * 10335 * @return true if the animation is played, false otherwise. 10336 */ 10337 private boolean initialAwakenScrollBars() { 10338 return mScrollCache != null && 10339 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 10340 } 10341 10342 /** 10343 * <p> 10344 * Trigger the scrollbars to draw. When invoked this method starts an 10345 * animation to fade the scrollbars out after a fixed delay. If a subclass 10346 * provides animated scrolling, the start delay should equal the duration of 10347 * the scrolling animation. 10348 * </p> 10349 * 10350 * <p> 10351 * The animation starts only if at least one of the scrollbars is enabled, 10352 * as specified by {@link #isHorizontalScrollBarEnabled()} and 10353 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 10354 * this method returns true, and false otherwise. If the animation is 10355 * started, this method calls {@link #invalidate()}; in that case the caller 10356 * should not call {@link #invalidate()}. 10357 * </p> 10358 * 10359 * <p> 10360 * This method should be invoked everytime a subclass directly updates the 10361 * scroll parameters. 10362 * </p> 10363 * 10364 * @param startDelay the delay, in milliseconds, after which the animation 10365 * should start; when the delay is 0, the animation starts 10366 * immediately 10367 * @return true if the animation is played, false otherwise 10368 * 10369 * @see #scrollBy(int, int) 10370 * @see #scrollTo(int, int) 10371 * @see #isHorizontalScrollBarEnabled() 10372 * @see #isVerticalScrollBarEnabled() 10373 * @see #setHorizontalScrollBarEnabled(boolean) 10374 * @see #setVerticalScrollBarEnabled(boolean) 10375 */ 10376 protected boolean awakenScrollBars(int startDelay) { 10377 return awakenScrollBars(startDelay, true); 10378 } 10379 10380 /** 10381 * <p> 10382 * Trigger the scrollbars to draw. When invoked this method starts an 10383 * animation to fade the scrollbars out after a fixed delay. If a subclass 10384 * provides animated scrolling, the start delay should equal the duration of 10385 * the scrolling animation. 10386 * </p> 10387 * 10388 * <p> 10389 * The animation starts only if at least one of the scrollbars is enabled, 10390 * as specified by {@link #isHorizontalScrollBarEnabled()} and 10391 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 10392 * this method returns true, and false otherwise. If the animation is 10393 * started, this method calls {@link #invalidate()} if the invalidate parameter 10394 * is set to true; in that case the caller 10395 * should not call {@link #invalidate()}. 10396 * </p> 10397 * 10398 * <p> 10399 * This method should be invoked everytime a subclass directly updates the 10400 * scroll parameters. 10401 * </p> 10402 * 10403 * @param startDelay the delay, in milliseconds, after which the animation 10404 * should start; when the delay is 0, the animation starts 10405 * immediately 10406 * 10407 * @param invalidate Wheter this method should call invalidate 10408 * 10409 * @return true if the animation is played, false otherwise 10410 * 10411 * @see #scrollBy(int, int) 10412 * @see #scrollTo(int, int) 10413 * @see #isHorizontalScrollBarEnabled() 10414 * @see #isVerticalScrollBarEnabled() 10415 * @see #setHorizontalScrollBarEnabled(boolean) 10416 * @see #setVerticalScrollBarEnabled(boolean) 10417 */ 10418 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 10419 final ScrollabilityCache scrollCache = mScrollCache; 10420 10421 if (scrollCache == null || !scrollCache.fadeScrollBars) { 10422 return false; 10423 } 10424 10425 if (scrollCache.scrollBar == null) { 10426 scrollCache.scrollBar = new ScrollBarDrawable(); 10427 } 10428 10429 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 10430 10431 if (invalidate) { 10432 // Invalidate to show the scrollbars 10433 postInvalidateOnAnimation(); 10434 } 10435 10436 if (scrollCache.state == ScrollabilityCache.OFF) { 10437 // FIXME: this is copied from WindowManagerService. 10438 // We should get this value from the system when it 10439 // is possible to do so. 10440 final int KEY_REPEAT_FIRST_DELAY = 750; 10441 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 10442 } 10443 10444 // Tell mScrollCache when we should start fading. This may 10445 // extend the fade start time if one was already scheduled 10446 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 10447 scrollCache.fadeStartTime = fadeStartTime; 10448 scrollCache.state = ScrollabilityCache.ON; 10449 10450 // Schedule our fader to run, unscheduling any old ones first 10451 if (mAttachInfo != null) { 10452 mAttachInfo.mHandler.removeCallbacks(scrollCache); 10453 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 10454 } 10455 10456 return true; 10457 } 10458 10459 return false; 10460 } 10461 10462 /** 10463 * Do not invalidate views which are not visible and which are not running an animation. They 10464 * will not get drawn and they should not set dirty flags as if they will be drawn 10465 */ 10466 private boolean skipInvalidate() { 10467 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 10468 (!(mParent instanceof ViewGroup) || 10469 !((ViewGroup) mParent).isViewTransitioning(this)); 10470 } 10471 /** 10472 * Mark the area defined by dirty as needing to be drawn. If the view is 10473 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point 10474 * in the future. This must be called from a UI thread. To call from a non-UI 10475 * thread, call {@link #postInvalidate()}. 10476 * 10477 * WARNING: This method is destructive to dirty. 10478 * @param dirty the rectangle representing the bounds of the dirty region 10479 */ 10480 public void invalidate(Rect dirty) { 10481 if (skipInvalidate()) { 10482 return; 10483 } 10484 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) || 10485 (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID || 10486 (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) { 10487 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 10488 mPrivateFlags |= PFLAG_INVALIDATED; 10489 mPrivateFlags |= PFLAG_DIRTY; 10490 final ViewParent p = mParent; 10491 final AttachInfo ai = mAttachInfo; 10492 //noinspection PointlessBooleanExpression,ConstantConditions 10493 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 10494 if (p != null && ai != null && ai.mHardwareAccelerated) { 10495 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 10496 // with a null dirty rect, which tells the ViewAncestor to redraw everything 10497 p.invalidateChild(this, null); 10498 return; 10499 } 10500 } 10501 if (p != null && ai != null) { 10502 final int scrollX = mScrollX; 10503 final int scrollY = mScrollY; 10504 final Rect r = ai.mTmpInvalRect; 10505 r.set(dirty.left - scrollX, dirty.top - scrollY, 10506 dirty.right - scrollX, dirty.bottom - scrollY); 10507 mParent.invalidateChild(this, r); 10508 } 10509 } 10510 } 10511 10512 /** 10513 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. 10514 * The coordinates of the dirty rect are relative to the view. 10515 * If the view is visible, {@link #onDraw(android.graphics.Canvas)} 10516 * will be called at some point in the future. This must be called from 10517 * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}. 10518 * @param l the left position of the dirty region 10519 * @param t the top position of the dirty region 10520 * @param r the right position of the dirty region 10521 * @param b the bottom position of the dirty region 10522 */ 10523 public void invalidate(int l, int t, int r, int b) { 10524 if (skipInvalidate()) { 10525 return; 10526 } 10527 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) || 10528 (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID || 10529 (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) { 10530 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 10531 mPrivateFlags |= PFLAG_INVALIDATED; 10532 mPrivateFlags |= PFLAG_DIRTY; 10533 final ViewParent p = mParent; 10534 final AttachInfo ai = mAttachInfo; 10535 //noinspection PointlessBooleanExpression,ConstantConditions 10536 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 10537 if (p != null && ai != null && ai.mHardwareAccelerated) { 10538 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 10539 // with a null dirty rect, which tells the ViewAncestor to redraw everything 10540 p.invalidateChild(this, null); 10541 return; 10542 } 10543 } 10544 if (p != null && ai != null && l < r && t < b) { 10545 final int scrollX = mScrollX; 10546 final int scrollY = mScrollY; 10547 final Rect tmpr = ai.mTmpInvalRect; 10548 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY); 10549 p.invalidateChild(this, tmpr); 10550 } 10551 } 10552 } 10553 10554 /** 10555 * Invalidate the whole view. If the view is visible, 10556 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 10557 * the future. This must be called from a UI thread. To call from a non-UI thread, 10558 * call {@link #postInvalidate()}. 10559 */ 10560 public void invalidate() { 10561 invalidate(true); 10562 } 10563 10564 /** 10565 * This is where the invalidate() work actually happens. A full invalidate() 10566 * causes the drawing cache to be invalidated, but this function can be called with 10567 * invalidateCache set to false to skip that invalidation step for cases that do not 10568 * need it (for example, a component that remains at the same dimensions with the same 10569 * content). 10570 * 10571 * @param invalidateCache Whether the drawing cache for this view should be invalidated as 10572 * well. This is usually true for a full invalidate, but may be set to false if the 10573 * View's contents or dimensions have not changed. 10574 */ 10575 void invalidate(boolean invalidateCache) { 10576 if (skipInvalidate()) { 10577 return; 10578 } 10579 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) || 10580 (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) || 10581 (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED || isOpaque() != mLastIsOpaque) { 10582 mLastIsOpaque = isOpaque(); 10583 mPrivateFlags &= ~PFLAG_DRAWN; 10584 mPrivateFlags |= PFLAG_DIRTY; 10585 if (invalidateCache) { 10586 mPrivateFlags |= PFLAG_INVALIDATED; 10587 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 10588 } 10589 final AttachInfo ai = mAttachInfo; 10590 final ViewParent p = mParent; 10591 //noinspection PointlessBooleanExpression,ConstantConditions 10592 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 10593 if (p != null && ai != null && ai.mHardwareAccelerated) { 10594 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 10595 // with a null dirty rect, which tells the ViewAncestor to redraw everything 10596 p.invalidateChild(this, null); 10597 return; 10598 } 10599 } 10600 10601 if (p != null && ai != null) { 10602 final Rect r = ai.mTmpInvalRect; 10603 r.set(0, 0, mRight - mLeft, mBottom - mTop); 10604 // Don't call invalidate -- we don't want to internally scroll 10605 // our own bounds 10606 p.invalidateChild(this, r); 10607 } 10608 } 10609 } 10610 10611 /** 10612 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 10613 * set any flags or handle all of the cases handled by the default invalidation methods. 10614 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 10615 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 10616 * walk up the hierarchy, transforming the dirty rect as necessary. 10617 * 10618 * The method also handles normal invalidation logic if display list properties are not 10619 * being used in this view. The invalidateParent and forceRedraw flags are used by that 10620 * backup approach, to handle these cases used in the various property-setting methods. 10621 * 10622 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 10623 * are not being used in this view 10624 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 10625 * list properties are not being used in this view 10626 */ 10627 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 10628 if (mDisplayList == null || (mPrivateFlags & PFLAG_DRAW_ANIMATION) == PFLAG_DRAW_ANIMATION) { 10629 if (invalidateParent) { 10630 invalidateParentCaches(); 10631 } 10632 if (forceRedraw) { 10633 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10634 } 10635 invalidate(false); 10636 } else { 10637 final AttachInfo ai = mAttachInfo; 10638 final ViewParent p = mParent; 10639 if (p != null && ai != null) { 10640 final Rect r = ai.mTmpInvalRect; 10641 r.set(0, 0, mRight - mLeft, mBottom - mTop); 10642 if (mParent instanceof ViewGroup) { 10643 ((ViewGroup) mParent).invalidateChildFast(this, r); 10644 } else { 10645 mParent.invalidateChild(this, r); 10646 } 10647 } 10648 } 10649 } 10650 10651 /** 10652 * Utility method to transform a given Rect by the current matrix of this view. 10653 */ 10654 void transformRect(final Rect rect) { 10655 if (!getMatrix().isIdentity()) { 10656 RectF boundingRect = mAttachInfo.mTmpTransformRect; 10657 boundingRect.set(rect); 10658 getMatrix().mapRect(boundingRect); 10659 rect.set((int) Math.floor(boundingRect.left), 10660 (int) Math.floor(boundingRect.top), 10661 (int) Math.ceil(boundingRect.right), 10662 (int) Math.ceil(boundingRect.bottom)); 10663 } 10664 } 10665 10666 /** 10667 * Used to indicate that the parent of this view should clear its caches. This functionality 10668 * is used to force the parent to rebuild its display list (when hardware-accelerated), 10669 * which is necessary when various parent-managed properties of the view change, such as 10670 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 10671 * clears the parent caches and does not causes an invalidate event. 10672 * 10673 * @hide 10674 */ 10675 protected void invalidateParentCaches() { 10676 if (mParent instanceof View) { 10677 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 10678 } 10679 } 10680 10681 /** 10682 * Used to indicate that the parent of this view should be invalidated. This functionality 10683 * is used to force the parent to rebuild its display list (when hardware-accelerated), 10684 * which is necessary when various parent-managed properties of the view change, such as 10685 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 10686 * an invalidation event to the parent. 10687 * 10688 * @hide 10689 */ 10690 protected void invalidateParentIfNeeded() { 10691 if (isHardwareAccelerated() && mParent instanceof View) { 10692 ((View) mParent).invalidate(true); 10693 } 10694 } 10695 10696 /** 10697 * Indicates whether this View is opaque. An opaque View guarantees that it will 10698 * draw all the pixels overlapping its bounds using a fully opaque color. 10699 * 10700 * Subclasses of View should override this method whenever possible to indicate 10701 * whether an instance is opaque. Opaque Views are treated in a special way by 10702 * the View hierarchy, possibly allowing it to perform optimizations during 10703 * invalidate/draw passes. 10704 * 10705 * @return True if this View is guaranteed to be fully opaque, false otherwise. 10706 */ 10707 @ViewDebug.ExportedProperty(category = "drawing") 10708 public boolean isOpaque() { 10709 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 10710 ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1.0f) >= 1.0f); 10711 } 10712 10713 /** 10714 * @hide 10715 */ 10716 protected void computeOpaqueFlags() { 10717 // Opaque if: 10718 // - Has a background 10719 // - Background is opaque 10720 // - Doesn't have scrollbars or scrollbars overlay 10721 10722 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 10723 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 10724 } else { 10725 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 10726 } 10727 10728 final int flags = mViewFlags; 10729 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 10730 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY || 10731 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) { 10732 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 10733 } else { 10734 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 10735 } 10736 } 10737 10738 /** 10739 * @hide 10740 */ 10741 protected boolean hasOpaqueScrollbars() { 10742 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 10743 } 10744 10745 /** 10746 * @return A handler associated with the thread running the View. This 10747 * handler can be used to pump events in the UI events queue. 10748 */ 10749 public Handler getHandler() { 10750 final AttachInfo attachInfo = mAttachInfo; 10751 if (attachInfo != null) { 10752 return attachInfo.mHandler; 10753 } 10754 return null; 10755 } 10756 10757 /** 10758 * Gets the view root associated with the View. 10759 * @return The view root, or null if none. 10760 * @hide 10761 */ 10762 public ViewRootImpl getViewRootImpl() { 10763 if (mAttachInfo != null) { 10764 return mAttachInfo.mViewRootImpl; 10765 } 10766 return null; 10767 } 10768 10769 /** 10770 * <p>Causes the Runnable to be added to the message queue. 10771 * The runnable will be run on the user interface thread.</p> 10772 * 10773 * @param action The Runnable that will be executed. 10774 * 10775 * @return Returns true if the Runnable was successfully placed in to the 10776 * message queue. Returns false on failure, usually because the 10777 * looper processing the message queue is exiting. 10778 * 10779 * @see #postDelayed 10780 * @see #removeCallbacks 10781 */ 10782 public boolean post(Runnable action) { 10783 final AttachInfo attachInfo = mAttachInfo; 10784 if (attachInfo != null) { 10785 return attachInfo.mHandler.post(action); 10786 } 10787 // Assume that post will succeed later 10788 ViewRootImpl.getRunQueue().post(action); 10789 return true; 10790 } 10791 10792 /** 10793 * <p>Causes the Runnable to be added to the message queue, to be run 10794 * after the specified amount of time elapses. 10795 * The runnable will be run on the user interface thread.</p> 10796 * 10797 * @param action The Runnable that will be executed. 10798 * @param delayMillis The delay (in milliseconds) until the Runnable 10799 * will be executed. 10800 * 10801 * @return true if the Runnable was successfully placed in to the 10802 * message queue. Returns false on failure, usually because the 10803 * looper processing the message queue is exiting. Note that a 10804 * result of true does not mean the Runnable will be processed -- 10805 * if the looper is quit before the delivery time of the message 10806 * occurs then the message will be dropped. 10807 * 10808 * @see #post 10809 * @see #removeCallbacks 10810 */ 10811 public boolean postDelayed(Runnable action, long delayMillis) { 10812 final AttachInfo attachInfo = mAttachInfo; 10813 if (attachInfo != null) { 10814 return attachInfo.mHandler.postDelayed(action, delayMillis); 10815 } 10816 // Assume that post will succeed later 10817 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 10818 return true; 10819 } 10820 10821 /** 10822 * <p>Causes the Runnable to execute on the next animation time step. 10823 * The runnable will be run on the user interface thread.</p> 10824 * 10825 * @param action The Runnable that will be executed. 10826 * 10827 * @see #postOnAnimationDelayed 10828 * @see #removeCallbacks 10829 */ 10830 public void postOnAnimation(Runnable action) { 10831 final AttachInfo attachInfo = mAttachInfo; 10832 if (attachInfo != null) { 10833 attachInfo.mViewRootImpl.mChoreographer.postCallback( 10834 Choreographer.CALLBACK_ANIMATION, action, null); 10835 } else { 10836 // Assume that post will succeed later 10837 ViewRootImpl.getRunQueue().post(action); 10838 } 10839 } 10840 10841 /** 10842 * <p>Causes the Runnable to execute on the next animation time step, 10843 * after the specified amount of time elapses. 10844 * The runnable will be run on the user interface thread.</p> 10845 * 10846 * @param action The Runnable that will be executed. 10847 * @param delayMillis The delay (in milliseconds) until the Runnable 10848 * will be executed. 10849 * 10850 * @see #postOnAnimation 10851 * @see #removeCallbacks 10852 */ 10853 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 10854 final AttachInfo attachInfo = mAttachInfo; 10855 if (attachInfo != null) { 10856 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 10857 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 10858 } else { 10859 // Assume that post will succeed later 10860 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 10861 } 10862 } 10863 10864 /** 10865 * <p>Removes the specified Runnable from the message queue.</p> 10866 * 10867 * @param action The Runnable to remove from the message handling queue 10868 * 10869 * @return true if this view could ask the Handler to remove the Runnable, 10870 * false otherwise. When the returned value is true, the Runnable 10871 * may or may not have been actually removed from the message queue 10872 * (for instance, if the Runnable was not in the queue already.) 10873 * 10874 * @see #post 10875 * @see #postDelayed 10876 * @see #postOnAnimation 10877 * @see #postOnAnimationDelayed 10878 */ 10879 public boolean removeCallbacks(Runnable action) { 10880 if (action != null) { 10881 final AttachInfo attachInfo = mAttachInfo; 10882 if (attachInfo != null) { 10883 attachInfo.mHandler.removeCallbacks(action); 10884 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 10885 Choreographer.CALLBACK_ANIMATION, action, null); 10886 } else { 10887 // Assume that post will succeed later 10888 ViewRootImpl.getRunQueue().removeCallbacks(action); 10889 } 10890 } 10891 return true; 10892 } 10893 10894 /** 10895 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 10896 * Use this to invalidate the View from a non-UI thread.</p> 10897 * 10898 * <p>This method can be invoked from outside of the UI thread 10899 * only when this View is attached to a window.</p> 10900 * 10901 * @see #invalidate() 10902 * @see #postInvalidateDelayed(long) 10903 */ 10904 public void postInvalidate() { 10905 postInvalidateDelayed(0); 10906 } 10907 10908 /** 10909 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 10910 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 10911 * 10912 * <p>This method can be invoked from outside of the UI thread 10913 * only when this View is attached to a window.</p> 10914 * 10915 * @param left The left coordinate of the rectangle to invalidate. 10916 * @param top The top coordinate of the rectangle to invalidate. 10917 * @param right The right coordinate of the rectangle to invalidate. 10918 * @param bottom The bottom coordinate of the rectangle to invalidate. 10919 * 10920 * @see #invalidate(int, int, int, int) 10921 * @see #invalidate(Rect) 10922 * @see #postInvalidateDelayed(long, int, int, int, int) 10923 */ 10924 public void postInvalidate(int left, int top, int right, int bottom) { 10925 postInvalidateDelayed(0, left, top, right, bottom); 10926 } 10927 10928 /** 10929 * <p>Cause an invalidate to happen on a subsequent cycle through the event 10930 * loop. Waits for the specified amount of time.</p> 10931 * 10932 * <p>This method can be invoked from outside of the UI thread 10933 * only when this View is attached to a window.</p> 10934 * 10935 * @param delayMilliseconds the duration in milliseconds to delay the 10936 * invalidation by 10937 * 10938 * @see #invalidate() 10939 * @see #postInvalidate() 10940 */ 10941 public void postInvalidateDelayed(long delayMilliseconds) { 10942 // We try only with the AttachInfo because there's no point in invalidating 10943 // if we are not attached to our window 10944 final AttachInfo attachInfo = mAttachInfo; 10945 if (attachInfo != null) { 10946 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 10947 } 10948 } 10949 10950 /** 10951 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 10952 * through the event loop. Waits for the specified amount of time.</p> 10953 * 10954 * <p>This method can be invoked from outside of the UI thread 10955 * only when this View is attached to a window.</p> 10956 * 10957 * @param delayMilliseconds the duration in milliseconds to delay the 10958 * invalidation by 10959 * @param left The left coordinate of the rectangle to invalidate. 10960 * @param top The top coordinate of the rectangle to invalidate. 10961 * @param right The right coordinate of the rectangle to invalidate. 10962 * @param bottom The bottom coordinate of the rectangle to invalidate. 10963 * 10964 * @see #invalidate(int, int, int, int) 10965 * @see #invalidate(Rect) 10966 * @see #postInvalidate(int, int, int, int) 10967 */ 10968 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 10969 int right, int bottom) { 10970 10971 // We try only with the AttachInfo because there's no point in invalidating 10972 // if we are not attached to our window 10973 final AttachInfo attachInfo = mAttachInfo; 10974 if (attachInfo != null) { 10975 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 10976 info.target = this; 10977 info.left = left; 10978 info.top = top; 10979 info.right = right; 10980 info.bottom = bottom; 10981 10982 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 10983 } 10984 } 10985 10986 /** 10987 * <p>Cause an invalidate to happen on the next animation time step, typically the 10988 * next display frame.</p> 10989 * 10990 * <p>This method can be invoked from outside of the UI thread 10991 * only when this View is attached to a window.</p> 10992 * 10993 * @see #invalidate() 10994 */ 10995 public void postInvalidateOnAnimation() { 10996 // We try only with the AttachInfo because there's no point in invalidating 10997 // if we are not attached to our window 10998 final AttachInfo attachInfo = mAttachInfo; 10999 if (attachInfo != null) { 11000 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 11001 } 11002 } 11003 11004 /** 11005 * <p>Cause an invalidate of the specified area to happen on the next animation 11006 * time step, typically the next display frame.</p> 11007 * 11008 * <p>This method can be invoked from outside of the UI thread 11009 * only when this View is attached to a window.</p> 11010 * 11011 * @param left The left coordinate of the rectangle to invalidate. 11012 * @param top The top coordinate of the rectangle to invalidate. 11013 * @param right The right coordinate of the rectangle to invalidate. 11014 * @param bottom The bottom coordinate of the rectangle to invalidate. 11015 * 11016 * @see #invalidate(int, int, int, int) 11017 * @see #invalidate(Rect) 11018 */ 11019 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 11020 // We try only with the AttachInfo because there's no point in invalidating 11021 // if we are not attached to our window 11022 final AttachInfo attachInfo = mAttachInfo; 11023 if (attachInfo != null) { 11024 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 11025 info.target = this; 11026 info.left = left; 11027 info.top = top; 11028 info.right = right; 11029 info.bottom = bottom; 11030 11031 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 11032 } 11033 } 11034 11035 /** 11036 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 11037 * This event is sent at most once every 11038 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 11039 */ 11040 private void postSendViewScrolledAccessibilityEventCallback() { 11041 if (mSendViewScrolledAccessibilityEvent == null) { 11042 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 11043 } 11044 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 11045 mSendViewScrolledAccessibilityEvent.mIsPending = true; 11046 postDelayed(mSendViewScrolledAccessibilityEvent, 11047 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 11048 } 11049 } 11050 11051 /** 11052 * Called by a parent to request that a child update its values for mScrollX 11053 * and mScrollY if necessary. This will typically be done if the child is 11054 * animating a scroll using a {@link android.widget.Scroller Scroller} 11055 * object. 11056 */ 11057 public void computeScroll() { 11058 } 11059 11060 /** 11061 * <p>Indicate whether the horizontal edges are faded when the view is 11062 * scrolled horizontally.</p> 11063 * 11064 * @return true if the horizontal edges should are faded on scroll, false 11065 * otherwise 11066 * 11067 * @see #setHorizontalFadingEdgeEnabled(boolean) 11068 * 11069 * @attr ref android.R.styleable#View_requiresFadingEdge 11070 */ 11071 public boolean isHorizontalFadingEdgeEnabled() { 11072 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 11073 } 11074 11075 /** 11076 * <p>Define whether the horizontal edges should be faded when this view 11077 * is scrolled horizontally.</p> 11078 * 11079 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 11080 * be faded when the view is scrolled 11081 * horizontally 11082 * 11083 * @see #isHorizontalFadingEdgeEnabled() 11084 * 11085 * @attr ref android.R.styleable#View_requiresFadingEdge 11086 */ 11087 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 11088 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 11089 if (horizontalFadingEdgeEnabled) { 11090 initScrollCache(); 11091 } 11092 11093 mViewFlags ^= FADING_EDGE_HORIZONTAL; 11094 } 11095 } 11096 11097 /** 11098 * <p>Indicate whether the vertical edges are faded when the view is 11099 * scrolled horizontally.</p> 11100 * 11101 * @return true if the vertical edges should are faded on scroll, false 11102 * otherwise 11103 * 11104 * @see #setVerticalFadingEdgeEnabled(boolean) 11105 * 11106 * @attr ref android.R.styleable#View_requiresFadingEdge 11107 */ 11108 public boolean isVerticalFadingEdgeEnabled() { 11109 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 11110 } 11111 11112 /** 11113 * <p>Define whether the vertical edges should be faded when this view 11114 * is scrolled vertically.</p> 11115 * 11116 * @param verticalFadingEdgeEnabled true if the vertical edges should 11117 * be faded when the view is scrolled 11118 * vertically 11119 * 11120 * @see #isVerticalFadingEdgeEnabled() 11121 * 11122 * @attr ref android.R.styleable#View_requiresFadingEdge 11123 */ 11124 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 11125 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 11126 if (verticalFadingEdgeEnabled) { 11127 initScrollCache(); 11128 } 11129 11130 mViewFlags ^= FADING_EDGE_VERTICAL; 11131 } 11132 } 11133 11134 /** 11135 * Returns the strength, or intensity, of the top faded edge. The strength is 11136 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11137 * returns 0.0 or 1.0 but no value in between. 11138 * 11139 * Subclasses should override this method to provide a smoother fade transition 11140 * when scrolling occurs. 11141 * 11142 * @return the intensity of the top fade as a float between 0.0f and 1.0f 11143 */ 11144 protected float getTopFadingEdgeStrength() { 11145 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 11146 } 11147 11148 /** 11149 * Returns the strength, or intensity, of the bottom faded edge. The strength is 11150 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11151 * returns 0.0 or 1.0 but no value in between. 11152 * 11153 * Subclasses should override this method to provide a smoother fade transition 11154 * when scrolling occurs. 11155 * 11156 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 11157 */ 11158 protected float getBottomFadingEdgeStrength() { 11159 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 11160 computeVerticalScrollRange() ? 1.0f : 0.0f; 11161 } 11162 11163 /** 11164 * Returns the strength, or intensity, of the left faded edge. The strength is 11165 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11166 * returns 0.0 or 1.0 but no value in between. 11167 * 11168 * Subclasses should override this method to provide a smoother fade transition 11169 * when scrolling occurs. 11170 * 11171 * @return the intensity of the left fade as a float between 0.0f and 1.0f 11172 */ 11173 protected float getLeftFadingEdgeStrength() { 11174 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 11175 } 11176 11177 /** 11178 * Returns the strength, or intensity, of the right faded edge. The strength is 11179 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11180 * returns 0.0 or 1.0 but no value in between. 11181 * 11182 * Subclasses should override this method to provide a smoother fade transition 11183 * when scrolling occurs. 11184 * 11185 * @return the intensity of the right fade as a float between 0.0f and 1.0f 11186 */ 11187 protected float getRightFadingEdgeStrength() { 11188 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 11189 computeHorizontalScrollRange() ? 1.0f : 0.0f; 11190 } 11191 11192 /** 11193 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 11194 * scrollbar is not drawn by default.</p> 11195 * 11196 * @return true if the horizontal scrollbar should be painted, false 11197 * otherwise 11198 * 11199 * @see #setHorizontalScrollBarEnabled(boolean) 11200 */ 11201 public boolean isHorizontalScrollBarEnabled() { 11202 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 11203 } 11204 11205 /** 11206 * <p>Define whether the horizontal scrollbar should be drawn or not. The 11207 * scrollbar is not drawn by default.</p> 11208 * 11209 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 11210 * be painted 11211 * 11212 * @see #isHorizontalScrollBarEnabled() 11213 */ 11214 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 11215 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 11216 mViewFlags ^= SCROLLBARS_HORIZONTAL; 11217 computeOpaqueFlags(); 11218 resolvePadding(); 11219 } 11220 } 11221 11222 /** 11223 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 11224 * scrollbar is not drawn by default.</p> 11225 * 11226 * @return true if the vertical scrollbar should be painted, false 11227 * otherwise 11228 * 11229 * @see #setVerticalScrollBarEnabled(boolean) 11230 */ 11231 public boolean isVerticalScrollBarEnabled() { 11232 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 11233 } 11234 11235 /** 11236 * <p>Define whether the vertical scrollbar should be drawn or not. The 11237 * scrollbar is not drawn by default.</p> 11238 * 11239 * @param verticalScrollBarEnabled true if the vertical scrollbar should 11240 * be painted 11241 * 11242 * @see #isVerticalScrollBarEnabled() 11243 */ 11244 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 11245 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 11246 mViewFlags ^= SCROLLBARS_VERTICAL; 11247 computeOpaqueFlags(); 11248 resolvePadding(); 11249 } 11250 } 11251 11252 /** 11253 * @hide 11254 */ 11255 protected void recomputePadding() { 11256 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 11257 } 11258 11259 /** 11260 * Define whether scrollbars will fade when the view is not scrolling. 11261 * 11262 * @param fadeScrollbars wheter to enable fading 11263 * 11264 * @attr ref android.R.styleable#View_fadeScrollbars 11265 */ 11266 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 11267 initScrollCache(); 11268 final ScrollabilityCache scrollabilityCache = mScrollCache; 11269 scrollabilityCache.fadeScrollBars = fadeScrollbars; 11270 if (fadeScrollbars) { 11271 scrollabilityCache.state = ScrollabilityCache.OFF; 11272 } else { 11273 scrollabilityCache.state = ScrollabilityCache.ON; 11274 } 11275 } 11276 11277 /** 11278 * 11279 * Returns true if scrollbars will fade when this view is not scrolling 11280 * 11281 * @return true if scrollbar fading is enabled 11282 * 11283 * @attr ref android.R.styleable#View_fadeScrollbars 11284 */ 11285 public boolean isScrollbarFadingEnabled() { 11286 return mScrollCache != null && mScrollCache.fadeScrollBars; 11287 } 11288 11289 /** 11290 * 11291 * Returns the delay before scrollbars fade. 11292 * 11293 * @return the delay before scrollbars fade 11294 * 11295 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 11296 */ 11297 public int getScrollBarDefaultDelayBeforeFade() { 11298 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 11299 mScrollCache.scrollBarDefaultDelayBeforeFade; 11300 } 11301 11302 /** 11303 * Define the delay before scrollbars fade. 11304 * 11305 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 11306 * 11307 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 11308 */ 11309 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 11310 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 11311 } 11312 11313 /** 11314 * 11315 * Returns the scrollbar fade duration. 11316 * 11317 * @return the scrollbar fade duration 11318 * 11319 * @attr ref android.R.styleable#View_scrollbarFadeDuration 11320 */ 11321 public int getScrollBarFadeDuration() { 11322 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 11323 mScrollCache.scrollBarFadeDuration; 11324 } 11325 11326 /** 11327 * Define the scrollbar fade duration. 11328 * 11329 * @param scrollBarFadeDuration - the scrollbar fade duration 11330 * 11331 * @attr ref android.R.styleable#View_scrollbarFadeDuration 11332 */ 11333 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 11334 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 11335 } 11336 11337 /** 11338 * 11339 * Returns the scrollbar size. 11340 * 11341 * @return the scrollbar size 11342 * 11343 * @attr ref android.R.styleable#View_scrollbarSize 11344 */ 11345 public int getScrollBarSize() { 11346 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 11347 mScrollCache.scrollBarSize; 11348 } 11349 11350 /** 11351 * Define the scrollbar size. 11352 * 11353 * @param scrollBarSize - the scrollbar size 11354 * 11355 * @attr ref android.R.styleable#View_scrollbarSize 11356 */ 11357 public void setScrollBarSize(int scrollBarSize) { 11358 getScrollCache().scrollBarSize = scrollBarSize; 11359 } 11360 11361 /** 11362 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 11363 * inset. When inset, they add to the padding of the view. And the scrollbars 11364 * can be drawn inside the padding area or on the edge of the view. For example, 11365 * if a view has a background drawable and you want to draw the scrollbars 11366 * inside the padding specified by the drawable, you can use 11367 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 11368 * appear at the edge of the view, ignoring the padding, then you can use 11369 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 11370 * @param style the style of the scrollbars. Should be one of 11371 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 11372 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 11373 * @see #SCROLLBARS_INSIDE_OVERLAY 11374 * @see #SCROLLBARS_INSIDE_INSET 11375 * @see #SCROLLBARS_OUTSIDE_OVERLAY 11376 * @see #SCROLLBARS_OUTSIDE_INSET 11377 * 11378 * @attr ref android.R.styleable#View_scrollbarStyle 11379 */ 11380 public void setScrollBarStyle(int style) { 11381 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 11382 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 11383 computeOpaqueFlags(); 11384 resolvePadding(); 11385 } 11386 } 11387 11388 /** 11389 * <p>Returns the current scrollbar style.</p> 11390 * @return the current scrollbar style 11391 * @see #SCROLLBARS_INSIDE_OVERLAY 11392 * @see #SCROLLBARS_INSIDE_INSET 11393 * @see #SCROLLBARS_OUTSIDE_OVERLAY 11394 * @see #SCROLLBARS_OUTSIDE_INSET 11395 * 11396 * @attr ref android.R.styleable#View_scrollbarStyle 11397 */ 11398 @ViewDebug.ExportedProperty(mapping = { 11399 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 11400 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 11401 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 11402 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 11403 }) 11404 public int getScrollBarStyle() { 11405 return mViewFlags & SCROLLBARS_STYLE_MASK; 11406 } 11407 11408 /** 11409 * <p>Compute the horizontal range that the horizontal scrollbar 11410 * represents.</p> 11411 * 11412 * <p>The range is expressed in arbitrary units that must be the same as the 11413 * units used by {@link #computeHorizontalScrollExtent()} and 11414 * {@link #computeHorizontalScrollOffset()}.</p> 11415 * 11416 * <p>The default range is the drawing width of this view.</p> 11417 * 11418 * @return the total horizontal range represented by the horizontal 11419 * scrollbar 11420 * 11421 * @see #computeHorizontalScrollExtent() 11422 * @see #computeHorizontalScrollOffset() 11423 * @see android.widget.ScrollBarDrawable 11424 */ 11425 protected int computeHorizontalScrollRange() { 11426 return getWidth(); 11427 } 11428 11429 /** 11430 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 11431 * within the horizontal range. This value is used to compute the position 11432 * of the thumb within the scrollbar's track.</p> 11433 * 11434 * <p>The range is expressed in arbitrary units that must be the same as the 11435 * units used by {@link #computeHorizontalScrollRange()} and 11436 * {@link #computeHorizontalScrollExtent()}.</p> 11437 * 11438 * <p>The default offset is the scroll offset of this view.</p> 11439 * 11440 * @return the horizontal offset of the scrollbar's thumb 11441 * 11442 * @see #computeHorizontalScrollRange() 11443 * @see #computeHorizontalScrollExtent() 11444 * @see android.widget.ScrollBarDrawable 11445 */ 11446 protected int computeHorizontalScrollOffset() { 11447 return mScrollX; 11448 } 11449 11450 /** 11451 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 11452 * within the horizontal range. This value is used to compute the length 11453 * of the thumb within the scrollbar's track.</p> 11454 * 11455 * <p>The range is expressed in arbitrary units that must be the same as the 11456 * units used by {@link #computeHorizontalScrollRange()} and 11457 * {@link #computeHorizontalScrollOffset()}.</p> 11458 * 11459 * <p>The default extent is the drawing width of this view.</p> 11460 * 11461 * @return the horizontal extent of the scrollbar's thumb 11462 * 11463 * @see #computeHorizontalScrollRange() 11464 * @see #computeHorizontalScrollOffset() 11465 * @see android.widget.ScrollBarDrawable 11466 */ 11467 protected int computeHorizontalScrollExtent() { 11468 return getWidth(); 11469 } 11470 11471 /** 11472 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 11473 * 11474 * <p>The range is expressed in arbitrary units that must be the same as the 11475 * units used by {@link #computeVerticalScrollExtent()} and 11476 * {@link #computeVerticalScrollOffset()}.</p> 11477 * 11478 * @return the total vertical range represented by the vertical scrollbar 11479 * 11480 * <p>The default range is the drawing height of this view.</p> 11481 * 11482 * @see #computeVerticalScrollExtent() 11483 * @see #computeVerticalScrollOffset() 11484 * @see android.widget.ScrollBarDrawable 11485 */ 11486 protected int computeVerticalScrollRange() { 11487 return getHeight(); 11488 } 11489 11490 /** 11491 * <p>Compute the vertical offset of the vertical scrollbar's thumb 11492 * within the horizontal range. This value is used to compute the position 11493 * of the thumb within the scrollbar's track.</p> 11494 * 11495 * <p>The range is expressed in arbitrary units that must be the same as the 11496 * units used by {@link #computeVerticalScrollRange()} and 11497 * {@link #computeVerticalScrollExtent()}.</p> 11498 * 11499 * <p>The default offset is the scroll offset of this view.</p> 11500 * 11501 * @return the vertical offset of the scrollbar's thumb 11502 * 11503 * @see #computeVerticalScrollRange() 11504 * @see #computeVerticalScrollExtent() 11505 * @see android.widget.ScrollBarDrawable 11506 */ 11507 protected int computeVerticalScrollOffset() { 11508 return mScrollY; 11509 } 11510 11511 /** 11512 * <p>Compute the vertical extent of the horizontal scrollbar's thumb 11513 * within the vertical range. This value is used to compute the length 11514 * of the thumb within the scrollbar's track.</p> 11515 * 11516 * <p>The range is expressed in arbitrary units that must be the same as the 11517 * units used by {@link #computeVerticalScrollRange()} and 11518 * {@link #computeVerticalScrollOffset()}.</p> 11519 * 11520 * <p>The default extent is the drawing height of this view.</p> 11521 * 11522 * @return the vertical extent of the scrollbar's thumb 11523 * 11524 * @see #computeVerticalScrollRange() 11525 * @see #computeVerticalScrollOffset() 11526 * @see android.widget.ScrollBarDrawable 11527 */ 11528 protected int computeVerticalScrollExtent() { 11529 return getHeight(); 11530 } 11531 11532 /** 11533 * Check if this view can be scrolled horizontally in a certain direction. 11534 * 11535 * @param direction Negative to check scrolling left, positive to check scrolling right. 11536 * @return true if this view can be scrolled in the specified direction, false otherwise. 11537 */ 11538 public boolean canScrollHorizontally(int direction) { 11539 final int offset = computeHorizontalScrollOffset(); 11540 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 11541 if (range == 0) return false; 11542 if (direction < 0) { 11543 return offset > 0; 11544 } else { 11545 return offset < range - 1; 11546 } 11547 } 11548 11549 /** 11550 * Check if this view can be scrolled vertically in a certain direction. 11551 * 11552 * @param direction Negative to check scrolling up, positive to check scrolling down. 11553 * @return true if this view can be scrolled in the specified direction, false otherwise. 11554 */ 11555 public boolean canScrollVertically(int direction) { 11556 final int offset = computeVerticalScrollOffset(); 11557 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 11558 if (range == 0) return false; 11559 if (direction < 0) { 11560 return offset > 0; 11561 } else { 11562 return offset < range - 1; 11563 } 11564 } 11565 11566 /** 11567 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 11568 * scrollbars are painted only if they have been awakened first.</p> 11569 * 11570 * @param canvas the canvas on which to draw the scrollbars 11571 * 11572 * @see #awakenScrollBars(int) 11573 */ 11574 protected final void onDrawScrollBars(Canvas canvas) { 11575 // scrollbars are drawn only when the animation is running 11576 final ScrollabilityCache cache = mScrollCache; 11577 if (cache != null) { 11578 11579 int state = cache.state; 11580 11581 if (state == ScrollabilityCache.OFF) { 11582 return; 11583 } 11584 11585 boolean invalidate = false; 11586 11587 if (state == ScrollabilityCache.FADING) { 11588 // We're fading -- get our fade interpolation 11589 if (cache.interpolatorValues == null) { 11590 cache.interpolatorValues = new float[1]; 11591 } 11592 11593 float[] values = cache.interpolatorValues; 11594 11595 // Stops the animation if we're done 11596 if (cache.scrollBarInterpolator.timeToValues(values) == 11597 Interpolator.Result.FREEZE_END) { 11598 cache.state = ScrollabilityCache.OFF; 11599 } else { 11600 cache.scrollBar.setAlpha(Math.round(values[0])); 11601 } 11602 11603 // This will make the scroll bars inval themselves after 11604 // drawing. We only want this when we're fading so that 11605 // we prevent excessive redraws 11606 invalidate = true; 11607 } else { 11608 // We're just on -- but we may have been fading before so 11609 // reset alpha 11610 cache.scrollBar.setAlpha(255); 11611 } 11612 11613 11614 final int viewFlags = mViewFlags; 11615 11616 final boolean drawHorizontalScrollBar = 11617 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 11618 final boolean drawVerticalScrollBar = 11619 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 11620 && !isVerticalScrollBarHidden(); 11621 11622 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 11623 final int width = mRight - mLeft; 11624 final int height = mBottom - mTop; 11625 11626 final ScrollBarDrawable scrollBar = cache.scrollBar; 11627 11628 final int scrollX = mScrollX; 11629 final int scrollY = mScrollY; 11630 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 11631 11632 int left; 11633 int top; 11634 int right; 11635 int bottom; 11636 11637 if (drawHorizontalScrollBar) { 11638 int size = scrollBar.getSize(false); 11639 if (size <= 0) { 11640 size = cache.scrollBarSize; 11641 } 11642 11643 scrollBar.setParameters(computeHorizontalScrollRange(), 11644 computeHorizontalScrollOffset(), 11645 computeHorizontalScrollExtent(), false); 11646 final int verticalScrollBarGap = drawVerticalScrollBar ? 11647 getVerticalScrollbarWidth() : 0; 11648 top = scrollY + height - size - (mUserPaddingBottom & inside); 11649 left = scrollX + (mPaddingLeft & inside); 11650 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 11651 bottom = top + size; 11652 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 11653 if (invalidate) { 11654 invalidate(left, top, right, bottom); 11655 } 11656 } 11657 11658 if (drawVerticalScrollBar) { 11659 int size = scrollBar.getSize(true); 11660 if (size <= 0) { 11661 size = cache.scrollBarSize; 11662 } 11663 11664 scrollBar.setParameters(computeVerticalScrollRange(), 11665 computeVerticalScrollOffset(), 11666 computeVerticalScrollExtent(), true); 11667 int verticalScrollbarPosition = mVerticalScrollbarPosition; 11668 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 11669 verticalScrollbarPosition = isLayoutRtl() ? 11670 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 11671 } 11672 switch (verticalScrollbarPosition) { 11673 default: 11674 case SCROLLBAR_POSITION_RIGHT: 11675 left = scrollX + width - size - (mUserPaddingRight & inside); 11676 break; 11677 case SCROLLBAR_POSITION_LEFT: 11678 left = scrollX + (mUserPaddingLeft & inside); 11679 break; 11680 } 11681 top = scrollY + (mPaddingTop & inside); 11682 right = left + size; 11683 bottom = scrollY + height - (mUserPaddingBottom & inside); 11684 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 11685 if (invalidate) { 11686 invalidate(left, top, right, bottom); 11687 } 11688 } 11689 } 11690 } 11691 } 11692 11693 /** 11694 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 11695 * FastScroller is visible. 11696 * @return whether to temporarily hide the vertical scrollbar 11697 * @hide 11698 */ 11699 protected boolean isVerticalScrollBarHidden() { 11700 return false; 11701 } 11702 11703 /** 11704 * <p>Draw the horizontal scrollbar if 11705 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 11706 * 11707 * @param canvas the canvas on which to draw the scrollbar 11708 * @param scrollBar the scrollbar's drawable 11709 * 11710 * @see #isHorizontalScrollBarEnabled() 11711 * @see #computeHorizontalScrollRange() 11712 * @see #computeHorizontalScrollExtent() 11713 * @see #computeHorizontalScrollOffset() 11714 * @see android.widget.ScrollBarDrawable 11715 * @hide 11716 */ 11717 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 11718 int l, int t, int r, int b) { 11719 scrollBar.setBounds(l, t, r, b); 11720 scrollBar.draw(canvas); 11721 } 11722 11723 /** 11724 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 11725 * returns true.</p> 11726 * 11727 * @param canvas the canvas on which to draw the scrollbar 11728 * @param scrollBar the scrollbar's drawable 11729 * 11730 * @see #isVerticalScrollBarEnabled() 11731 * @see #computeVerticalScrollRange() 11732 * @see #computeVerticalScrollExtent() 11733 * @see #computeVerticalScrollOffset() 11734 * @see android.widget.ScrollBarDrawable 11735 * @hide 11736 */ 11737 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 11738 int l, int t, int r, int b) { 11739 scrollBar.setBounds(l, t, r, b); 11740 scrollBar.draw(canvas); 11741 } 11742 11743 /** 11744 * Implement this to do your drawing. 11745 * 11746 * @param canvas the canvas on which the background will be drawn 11747 */ 11748 protected void onDraw(Canvas canvas) { 11749 } 11750 11751 /* 11752 * Caller is responsible for calling requestLayout if necessary. 11753 * (This allows addViewInLayout to not request a new layout.) 11754 */ 11755 void assignParent(ViewParent parent) { 11756 if (mParent == null) { 11757 mParent = parent; 11758 } else if (parent == null) { 11759 mParent = null; 11760 } else { 11761 throw new RuntimeException("view " + this + " being added, but" 11762 + " it already has a parent"); 11763 } 11764 } 11765 11766 /** 11767 * This is called when the view is attached to a window. At this point it 11768 * has a Surface and will start drawing. Note that this function is 11769 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 11770 * however it may be called any time before the first onDraw -- including 11771 * before or after {@link #onMeasure(int, int)}. 11772 * 11773 * @see #onDetachedFromWindow() 11774 */ 11775 protected void onAttachedToWindow() { 11776 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 11777 mParent.requestTransparentRegion(this); 11778 } 11779 11780 if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 11781 initialAwakenScrollBars(); 11782 mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 11783 } 11784 11785 jumpDrawablesToCurrentState(); 11786 11787 clearAccessibilityFocus(); 11788 resetSubtreeAccessibilityStateChanged(); 11789 11790 if (isFocused()) { 11791 InputMethodManager imm = InputMethodManager.peekInstance(); 11792 imm.focusIn(this); 11793 } 11794 11795 if (mDisplayList != null) { 11796 mDisplayList.clearDirty(); 11797 } 11798 } 11799 11800 /** 11801 * Resolve all RTL related properties. 11802 * 11803 * @return true if resolution of RTL properties has been done 11804 * 11805 * @hide 11806 */ 11807 public boolean resolveRtlPropertiesIfNeeded() { 11808 if (!needRtlPropertiesResolution()) return false; 11809 11810 // Order is important here: LayoutDirection MUST be resolved first 11811 if (!isLayoutDirectionResolved()) { 11812 resolveLayoutDirection(); 11813 resolveLayoutParams(); 11814 } 11815 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 11816 if (!isTextDirectionResolved()) { 11817 resolveTextDirection(); 11818 } 11819 if (!isTextAlignmentResolved()) { 11820 resolveTextAlignment(); 11821 } 11822 if (!isPaddingResolved()) { 11823 resolvePadding(); 11824 } 11825 if (!isDrawablesResolved()) { 11826 resolveDrawables(); 11827 } 11828 onRtlPropertiesChanged(getLayoutDirection()); 11829 return true; 11830 } 11831 11832 /** 11833 * Reset resolution of all RTL related properties. 11834 * 11835 * @hide 11836 */ 11837 public void resetRtlProperties() { 11838 resetResolvedLayoutDirection(); 11839 resetResolvedTextDirection(); 11840 resetResolvedTextAlignment(); 11841 resetResolvedPadding(); 11842 resetResolvedDrawables(); 11843 } 11844 11845 /** 11846 * @see #onScreenStateChanged(int) 11847 */ 11848 void dispatchScreenStateChanged(int screenState) { 11849 onScreenStateChanged(screenState); 11850 } 11851 11852 /** 11853 * This method is called whenever the state of the screen this view is 11854 * attached to changes. A state change will usually occurs when the screen 11855 * turns on or off (whether it happens automatically or the user does it 11856 * manually.) 11857 * 11858 * @param screenState The new state of the screen. Can be either 11859 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 11860 */ 11861 public void onScreenStateChanged(int screenState) { 11862 } 11863 11864 /** 11865 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 11866 */ 11867 private boolean hasRtlSupport() { 11868 return mContext.getApplicationInfo().hasRtlSupport(); 11869 } 11870 11871 /** 11872 * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or 11873 * RTL not supported) 11874 */ 11875 private boolean isRtlCompatibilityMode() { 11876 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 11877 return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport(); 11878 } 11879 11880 /** 11881 * @return true if RTL properties need resolution. 11882 * 11883 */ 11884 private boolean needRtlPropertiesResolution() { 11885 return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED; 11886 } 11887 11888 /** 11889 * Called when any RTL property (layout direction or text direction or text alignment) has 11890 * been changed. 11891 * 11892 * Subclasses need to override this method to take care of cached information that depends on the 11893 * resolved layout direction, or to inform child views that inherit their layout direction. 11894 * 11895 * The default implementation does nothing. 11896 * 11897 * @param layoutDirection the direction of the layout 11898 * 11899 * @see #LAYOUT_DIRECTION_LTR 11900 * @see #LAYOUT_DIRECTION_RTL 11901 */ 11902 public void onRtlPropertiesChanged(int layoutDirection) { 11903 } 11904 11905 /** 11906 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 11907 * that the parent directionality can and will be resolved before its children. 11908 * 11909 * @return true if resolution has been done, false otherwise. 11910 * 11911 * @hide 11912 */ 11913 public boolean resolveLayoutDirection() { 11914 // Clear any previous layout direction resolution 11915 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 11916 11917 if (hasRtlSupport()) { 11918 // Set resolved depending on layout direction 11919 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 11920 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 11921 case LAYOUT_DIRECTION_INHERIT: 11922 // We cannot resolve yet. LTR is by default and let the resolution happen again 11923 // later to get the correct resolved value 11924 if (!canResolveLayoutDirection()) return false; 11925 11926 // Parent has not yet resolved, LTR is still the default 11927 if (!mParent.isLayoutDirectionResolved()) return false; 11928 11929 if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 11930 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 11931 } 11932 break; 11933 case LAYOUT_DIRECTION_RTL: 11934 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 11935 break; 11936 case LAYOUT_DIRECTION_LOCALE: 11937 if((LAYOUT_DIRECTION_RTL == 11938 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) { 11939 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 11940 } 11941 break; 11942 default: 11943 // Nothing to do, LTR by default 11944 } 11945 } 11946 11947 // Set to resolved 11948 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 11949 return true; 11950 } 11951 11952 /** 11953 * Check if layout direction resolution can be done. 11954 * 11955 * @return true if layout direction resolution can be done otherwise return false. 11956 * 11957 * @hide 11958 */ 11959 public boolean canResolveLayoutDirection() { 11960 switch (getRawLayoutDirection()) { 11961 case LAYOUT_DIRECTION_INHERIT: 11962 return (mParent != null) && mParent.canResolveLayoutDirection(); 11963 default: 11964 return true; 11965 } 11966 } 11967 11968 /** 11969 * Reset the resolved layout direction. Layout direction will be resolved during a call to 11970 * {@link #onMeasure(int, int)}. 11971 * 11972 * @hide 11973 */ 11974 public void resetResolvedLayoutDirection() { 11975 // Reset the current resolved bits 11976 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 11977 } 11978 11979 /** 11980 * @return true if the layout direction is inherited. 11981 * 11982 * @hide 11983 */ 11984 public boolean isLayoutDirectionInherited() { 11985 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT); 11986 } 11987 11988 /** 11989 * @return true if layout direction has been resolved. 11990 * @hide 11991 */ 11992 public boolean isLayoutDirectionResolved() { 11993 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED; 11994 } 11995 11996 /** 11997 * Return if padding has been resolved 11998 * 11999 * @hide 12000 */ 12001 boolean isPaddingResolved() { 12002 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED; 12003 } 12004 12005 /** 12006 * Resolve padding depending on layout direction. 12007 * 12008 * @hide 12009 */ 12010 public void resolvePadding() { 12011 if (!isRtlCompatibilityMode()) { 12012 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 12013 // If start / end padding are defined, they will be resolved (hence overriding) to 12014 // left / right or right / left depending on the resolved layout direction. 12015 // If start / end padding are not defined, use the left / right ones. 12016 int resolvedLayoutDirection = getLayoutDirection(); 12017 switch (resolvedLayoutDirection) { 12018 case LAYOUT_DIRECTION_RTL: 12019 if (mUserPaddingStart != UNDEFINED_PADDING) { 12020 mUserPaddingRight = mUserPaddingStart; 12021 } else { 12022 mUserPaddingRight = mUserPaddingRightInitial; 12023 } 12024 if (mUserPaddingEnd != UNDEFINED_PADDING) { 12025 mUserPaddingLeft = mUserPaddingEnd; 12026 } else { 12027 mUserPaddingLeft = mUserPaddingLeftInitial; 12028 } 12029 break; 12030 case LAYOUT_DIRECTION_LTR: 12031 default: 12032 if (mUserPaddingStart != UNDEFINED_PADDING) { 12033 mUserPaddingLeft = mUserPaddingStart; 12034 } else { 12035 mUserPaddingLeft = mUserPaddingLeftInitial; 12036 } 12037 if (mUserPaddingEnd != UNDEFINED_PADDING) { 12038 mUserPaddingRight = mUserPaddingEnd; 12039 } else { 12040 mUserPaddingRight = mUserPaddingRightInitial; 12041 } 12042 } 12043 12044 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 12045 12046 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, 12047 mUserPaddingBottom); 12048 onRtlPropertiesChanged(resolvedLayoutDirection); 12049 } 12050 12051 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 12052 } 12053 12054 /** 12055 * Reset the resolved layout direction. 12056 * 12057 * @hide 12058 */ 12059 public void resetResolvedPadding() { 12060 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 12061 } 12062 12063 /** 12064 * This is called when the view is detached from a window. At this point it 12065 * no longer has a surface for drawing. 12066 * 12067 * @see #onAttachedToWindow() 12068 */ 12069 protected void onDetachedFromWindow() { 12070 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 12071 12072 removeUnsetPressCallback(); 12073 removeLongPressCallback(); 12074 removePerformClickCallback(); 12075 removeSendViewScrolledAccessibilityEventCallback(); 12076 12077 destroyDrawingCache(); 12078 12079 destroyLayer(false); 12080 12081 cleanupDraw(); 12082 12083 mCurrentAnimation = null; 12084 mCurrentScene = null; 12085 } 12086 12087 private void cleanupDraw() { 12088 if (mAttachInfo != null) { 12089 if (mDisplayList != null) { 12090 mDisplayList.markDirty(); 12091 mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList); 12092 } 12093 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 12094 } else { 12095 // Should never happen 12096 clearDisplayList(); 12097 } 12098 } 12099 12100 void invalidateInheritedLayoutMode(int layoutModeOfRoot) { 12101 } 12102 12103 /** 12104 * @return The number of times this view has been attached to a window 12105 */ 12106 protected int getWindowAttachCount() { 12107 return mWindowAttachCount; 12108 } 12109 12110 /** 12111 * Retrieve a unique token identifying the window this view is attached to. 12112 * @return Return the window's token for use in 12113 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 12114 */ 12115 public IBinder getWindowToken() { 12116 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 12117 } 12118 12119 /** 12120 * Retrieve the {@link WindowId} for the window this view is 12121 * currently attached to. 12122 */ 12123 public WindowId getWindowId() { 12124 if (mAttachInfo == null) { 12125 return null; 12126 } 12127 if (mAttachInfo.mWindowId == null) { 12128 try { 12129 mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId( 12130 mAttachInfo.mWindowToken); 12131 mAttachInfo.mWindowId = new WindowId( 12132 mAttachInfo.mIWindowId); 12133 } catch (RemoteException e) { 12134 } 12135 } 12136 return mAttachInfo.mWindowId; 12137 } 12138 12139 /** 12140 * Retrieve a unique token identifying the top-level "real" window of 12141 * the window that this view is attached to. That is, this is like 12142 * {@link #getWindowToken}, except if the window this view in is a panel 12143 * window (attached to another containing window), then the token of 12144 * the containing window is returned instead. 12145 * 12146 * @return Returns the associated window token, either 12147 * {@link #getWindowToken()} or the containing window's token. 12148 */ 12149 public IBinder getApplicationWindowToken() { 12150 AttachInfo ai = mAttachInfo; 12151 if (ai != null) { 12152 IBinder appWindowToken = ai.mPanelParentWindowToken; 12153 if (appWindowToken == null) { 12154 appWindowToken = ai.mWindowToken; 12155 } 12156 return appWindowToken; 12157 } 12158 return null; 12159 } 12160 12161 /** 12162 * Gets the logical display to which the view's window has been attached. 12163 * 12164 * @return The logical display, or null if the view is not currently attached to a window. 12165 */ 12166 public Display getDisplay() { 12167 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 12168 } 12169 12170 /** 12171 * Retrieve private session object this view hierarchy is using to 12172 * communicate with the window manager. 12173 * @return the session object to communicate with the window manager 12174 */ 12175 /*package*/ IWindowSession getWindowSession() { 12176 return mAttachInfo != null ? mAttachInfo.mSession : null; 12177 } 12178 12179 /** 12180 * @param info the {@link android.view.View.AttachInfo} to associated with 12181 * this view 12182 */ 12183 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 12184 //System.out.println("Attached! " + this); 12185 mAttachInfo = info; 12186 if (mOverlay != null) { 12187 mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility); 12188 } 12189 mWindowAttachCount++; 12190 // We will need to evaluate the drawable state at least once. 12191 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 12192 if (mFloatingTreeObserver != null) { 12193 info.mTreeObserver.merge(mFloatingTreeObserver); 12194 mFloatingTreeObserver = null; 12195 } 12196 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 12197 mAttachInfo.mScrollContainers.add(this); 12198 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 12199 } 12200 performCollectViewAttributes(mAttachInfo, visibility); 12201 onAttachedToWindow(); 12202 12203 ListenerInfo li = mListenerInfo; 12204 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 12205 li != null ? li.mOnAttachStateChangeListeners : null; 12206 if (listeners != null && listeners.size() > 0) { 12207 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 12208 // perform the dispatching. The iterator is a safe guard against listeners that 12209 // could mutate the list by calling the various add/remove methods. This prevents 12210 // the array from being modified while we iterate it. 12211 for (OnAttachStateChangeListener listener : listeners) { 12212 listener.onViewAttachedToWindow(this); 12213 } 12214 } 12215 12216 int vis = info.mWindowVisibility; 12217 if (vis != GONE) { 12218 onWindowVisibilityChanged(vis); 12219 } 12220 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 12221 // If nobody has evaluated the drawable state yet, then do it now. 12222 refreshDrawableState(); 12223 } 12224 needGlobalAttributesUpdate(false); 12225 } 12226 12227 void dispatchDetachedFromWindow() { 12228 AttachInfo info = mAttachInfo; 12229 if (info != null) { 12230 int vis = info.mWindowVisibility; 12231 if (vis != GONE) { 12232 onWindowVisibilityChanged(GONE); 12233 } 12234 } 12235 12236 onDetachedFromWindow(); 12237 12238 ListenerInfo li = mListenerInfo; 12239 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 12240 li != null ? li.mOnAttachStateChangeListeners : null; 12241 if (listeners != null && listeners.size() > 0) { 12242 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 12243 // perform the dispatching. The iterator is a safe guard against listeners that 12244 // could mutate the list by calling the various add/remove methods. This prevents 12245 // the array from being modified while we iterate it. 12246 for (OnAttachStateChangeListener listener : listeners) { 12247 listener.onViewDetachedFromWindow(this); 12248 } 12249 } 12250 12251 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 12252 mAttachInfo.mScrollContainers.remove(this); 12253 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 12254 } 12255 12256 mAttachInfo = null; 12257 if (mOverlay != null) { 12258 mOverlay.getOverlayView().dispatchDetachedFromWindow(); 12259 } 12260 } 12261 12262 /** 12263 * Store this view hierarchy's frozen state into the given container. 12264 * 12265 * @param container The SparseArray in which to save the view's state. 12266 * 12267 * @see #restoreHierarchyState(android.util.SparseArray) 12268 * @see #dispatchSaveInstanceState(android.util.SparseArray) 12269 * @see #onSaveInstanceState() 12270 */ 12271 public void saveHierarchyState(SparseArray<Parcelable> container) { 12272 dispatchSaveInstanceState(container); 12273 } 12274 12275 /** 12276 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 12277 * this view and its children. May be overridden to modify how freezing happens to a 12278 * view's children; for example, some views may want to not store state for their children. 12279 * 12280 * @param container The SparseArray in which to save the view's state. 12281 * 12282 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 12283 * @see #saveHierarchyState(android.util.SparseArray) 12284 * @see #onSaveInstanceState() 12285 */ 12286 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 12287 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 12288 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 12289 Parcelable state = onSaveInstanceState(); 12290 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 12291 throw new IllegalStateException( 12292 "Derived class did not call super.onSaveInstanceState()"); 12293 } 12294 if (state != null) { 12295 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 12296 // + ": " + state); 12297 container.put(mID, state); 12298 } 12299 } 12300 } 12301 12302 /** 12303 * Hook allowing a view to generate a representation of its internal state 12304 * that can later be used to create a new instance with that same state. 12305 * This state should only contain information that is not persistent or can 12306 * not be reconstructed later. For example, you will never store your 12307 * current position on screen because that will be computed again when a 12308 * new instance of the view is placed in its view hierarchy. 12309 * <p> 12310 * Some examples of things you may store here: the current cursor position 12311 * in a text view (but usually not the text itself since that is stored in a 12312 * content provider or other persistent storage), the currently selected 12313 * item in a list view. 12314 * 12315 * @return Returns a Parcelable object containing the view's current dynamic 12316 * state, or null if there is nothing interesting to save. The 12317 * default implementation returns null. 12318 * @see #onRestoreInstanceState(android.os.Parcelable) 12319 * @see #saveHierarchyState(android.util.SparseArray) 12320 * @see #dispatchSaveInstanceState(android.util.SparseArray) 12321 * @see #setSaveEnabled(boolean) 12322 */ 12323 protected Parcelable onSaveInstanceState() { 12324 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 12325 return BaseSavedState.EMPTY_STATE; 12326 } 12327 12328 /** 12329 * Restore this view hierarchy's frozen state from the given container. 12330 * 12331 * @param container The SparseArray which holds previously frozen states. 12332 * 12333 * @see #saveHierarchyState(android.util.SparseArray) 12334 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 12335 * @see #onRestoreInstanceState(android.os.Parcelable) 12336 */ 12337 public void restoreHierarchyState(SparseArray<Parcelable> container) { 12338 dispatchRestoreInstanceState(container); 12339 } 12340 12341 /** 12342 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 12343 * state for this view and its children. May be overridden to modify how restoring 12344 * happens to a view's children; for example, some views may want to not store state 12345 * for their children. 12346 * 12347 * @param container The SparseArray which holds previously saved state. 12348 * 12349 * @see #dispatchSaveInstanceState(android.util.SparseArray) 12350 * @see #restoreHierarchyState(android.util.SparseArray) 12351 * @see #onRestoreInstanceState(android.os.Parcelable) 12352 */ 12353 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 12354 if (mID != NO_ID) { 12355 Parcelable state = container.get(mID); 12356 if (state != null) { 12357 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 12358 // + ": " + state); 12359 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 12360 onRestoreInstanceState(state); 12361 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 12362 throw new IllegalStateException( 12363 "Derived class did not call super.onRestoreInstanceState()"); 12364 } 12365 } 12366 } 12367 } 12368 12369 /** 12370 * Hook allowing a view to re-apply a representation of its internal state that had previously 12371 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 12372 * null state. 12373 * 12374 * @param state The frozen state that had previously been returned by 12375 * {@link #onSaveInstanceState}. 12376 * 12377 * @see #onSaveInstanceState() 12378 * @see #restoreHierarchyState(android.util.SparseArray) 12379 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 12380 */ 12381 protected void onRestoreInstanceState(Parcelable state) { 12382 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 12383 if (state != BaseSavedState.EMPTY_STATE && state != null) { 12384 throw new IllegalArgumentException("Wrong state class, expecting View State but " 12385 + "received " + state.getClass().toString() + " instead. This usually happens " 12386 + "when two views of different type have the same id in the same hierarchy. " 12387 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 12388 + "other views do not use the same id."); 12389 } 12390 } 12391 12392 /** 12393 * <p>Return the time at which the drawing of the view hierarchy started.</p> 12394 * 12395 * @return the drawing start time in milliseconds 12396 */ 12397 public long getDrawingTime() { 12398 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 12399 } 12400 12401 /** 12402 * <p>Enables or disables the duplication of the parent's state into this view. When 12403 * duplication is enabled, this view gets its drawable state from its parent rather 12404 * than from its own internal properties.</p> 12405 * 12406 * <p>Note: in the current implementation, setting this property to true after the 12407 * view was added to a ViewGroup might have no effect at all. This property should 12408 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 12409 * 12410 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 12411 * property is enabled, an exception will be thrown.</p> 12412 * 12413 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 12414 * parent, these states should not be affected by this method.</p> 12415 * 12416 * @param enabled True to enable duplication of the parent's drawable state, false 12417 * to disable it. 12418 * 12419 * @see #getDrawableState() 12420 * @see #isDuplicateParentStateEnabled() 12421 */ 12422 public void setDuplicateParentStateEnabled(boolean enabled) { 12423 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 12424 } 12425 12426 /** 12427 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 12428 * 12429 * @return True if this view's drawable state is duplicated from the parent, 12430 * false otherwise 12431 * 12432 * @see #getDrawableState() 12433 * @see #setDuplicateParentStateEnabled(boolean) 12434 */ 12435 public boolean isDuplicateParentStateEnabled() { 12436 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 12437 } 12438 12439 /** 12440 * <p>Specifies the type of layer backing this view. The layer can be 12441 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 12442 * {@link #LAYER_TYPE_HARDWARE}.</p> 12443 * 12444 * <p>A layer is associated with an optional {@link android.graphics.Paint} 12445 * instance that controls how the layer is composed on screen. The following 12446 * properties of the paint are taken into account when composing the layer:</p> 12447 * <ul> 12448 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 12449 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 12450 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 12451 * </ul> 12452 * 12453 * <p>If this view has an alpha value set to < 1.0 by calling 12454 * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded 12455 * by this view's alpha value.</p> 12456 * 12457 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE}, 12458 * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE} 12459 * for more information on when and how to use layers.</p> 12460 * 12461 * @param layerType The type of layer to use with this view, must be one of 12462 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 12463 * {@link #LAYER_TYPE_HARDWARE} 12464 * @param paint The paint used to compose the layer. This argument is optional 12465 * and can be null. It is ignored when the layer type is 12466 * {@link #LAYER_TYPE_NONE} 12467 * 12468 * @see #getLayerType() 12469 * @see #LAYER_TYPE_NONE 12470 * @see #LAYER_TYPE_SOFTWARE 12471 * @see #LAYER_TYPE_HARDWARE 12472 * @see #setAlpha(float) 12473 * 12474 * @attr ref android.R.styleable#View_layerType 12475 */ 12476 public void setLayerType(int layerType, Paint paint) { 12477 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 12478 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 12479 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 12480 } 12481 12482 if (layerType == mLayerType) { 12483 if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) { 12484 mLayerPaint = paint == null ? new Paint() : paint; 12485 invalidateParentCaches(); 12486 invalidate(true); 12487 } 12488 return; 12489 } 12490 12491 // Destroy any previous software drawing cache if needed 12492 switch (mLayerType) { 12493 case LAYER_TYPE_HARDWARE: 12494 destroyLayer(false); 12495 // fall through - non-accelerated views may use software layer mechanism instead 12496 case LAYER_TYPE_SOFTWARE: 12497 destroyDrawingCache(); 12498 break; 12499 default: 12500 break; 12501 } 12502 12503 mLayerType = layerType; 12504 final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE; 12505 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 12506 mLocalDirtyRect = layerDisabled ? null : new Rect(); 12507 12508 invalidateParentCaches(); 12509 invalidate(true); 12510 } 12511 12512 /** 12513 * Updates the {@link Paint} object used with the current layer (used only if the current 12514 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 12515 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 12516 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 12517 * ensure that the view gets redrawn immediately. 12518 * 12519 * <p>A layer is associated with an optional {@link android.graphics.Paint} 12520 * instance that controls how the layer is composed on screen. The following 12521 * properties of the paint are taken into account when composing the layer:</p> 12522 * <ul> 12523 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 12524 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 12525 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 12526 * </ul> 12527 * 12528 * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the 12529 * alpha value of the layer's paint is superceded by this view's alpha value.</p> 12530 * 12531 * @param paint The paint used to compose the layer. This argument is optional 12532 * and can be null. It is ignored when the layer type is 12533 * {@link #LAYER_TYPE_NONE} 12534 * 12535 * @see #setLayerType(int, android.graphics.Paint) 12536 */ 12537 public void setLayerPaint(Paint paint) { 12538 int layerType = getLayerType(); 12539 if (layerType != LAYER_TYPE_NONE) { 12540 mLayerPaint = paint == null ? new Paint() : paint; 12541 if (layerType == LAYER_TYPE_HARDWARE) { 12542 HardwareLayer layer = getHardwareLayer(); 12543 if (layer != null) { 12544 layer.setLayerPaint(paint); 12545 } 12546 invalidateViewProperty(false, false); 12547 } else { 12548 invalidate(); 12549 } 12550 } 12551 } 12552 12553 /** 12554 * Indicates whether this view has a static layer. A view with layer type 12555 * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are 12556 * dynamic. 12557 */ 12558 boolean hasStaticLayer() { 12559 return true; 12560 } 12561 12562 /** 12563 * Indicates what type of layer is currently associated with this view. By default 12564 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 12565 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 12566 * for more information on the different types of layers. 12567 * 12568 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 12569 * {@link #LAYER_TYPE_HARDWARE} 12570 * 12571 * @see #setLayerType(int, android.graphics.Paint) 12572 * @see #buildLayer() 12573 * @see #LAYER_TYPE_NONE 12574 * @see #LAYER_TYPE_SOFTWARE 12575 * @see #LAYER_TYPE_HARDWARE 12576 */ 12577 public int getLayerType() { 12578 return mLayerType; 12579 } 12580 12581 /** 12582 * Forces this view's layer to be created and this view to be rendered 12583 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 12584 * invoking this method will have no effect. 12585 * 12586 * This method can for instance be used to render a view into its layer before 12587 * starting an animation. If this view is complex, rendering into the layer 12588 * before starting the animation will avoid skipping frames. 12589 * 12590 * @throws IllegalStateException If this view is not attached to a window 12591 * 12592 * @see #setLayerType(int, android.graphics.Paint) 12593 */ 12594 public void buildLayer() { 12595 if (mLayerType == LAYER_TYPE_NONE) return; 12596 12597 if (mAttachInfo == null) { 12598 throw new IllegalStateException("This view must be attached to a window first"); 12599 } 12600 12601 switch (mLayerType) { 12602 case LAYER_TYPE_HARDWARE: 12603 if (mAttachInfo.mHardwareRenderer != null && 12604 mAttachInfo.mHardwareRenderer.isEnabled() && 12605 mAttachInfo.mHardwareRenderer.validate()) { 12606 getHardwareLayer(); 12607 } 12608 break; 12609 case LAYER_TYPE_SOFTWARE: 12610 buildDrawingCache(true); 12611 break; 12612 } 12613 } 12614 12615 /** 12616 * <p>Returns a hardware layer that can be used to draw this view again 12617 * without executing its draw method.</p> 12618 * 12619 * @return A HardwareLayer ready to render, or null if an error occurred. 12620 */ 12621 HardwareLayer getHardwareLayer() { 12622 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null || 12623 !mAttachInfo.mHardwareRenderer.isEnabled()) { 12624 return null; 12625 } 12626 12627 if (!mAttachInfo.mHardwareRenderer.validate()) return null; 12628 12629 final int width = mRight - mLeft; 12630 final int height = mBottom - mTop; 12631 12632 if (width == 0 || height == 0) { 12633 return null; 12634 } 12635 12636 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) { 12637 if (mHardwareLayer == null) { 12638 mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer( 12639 width, height, isOpaque()); 12640 mLocalDirtyRect.set(0, 0, width, height); 12641 } else { 12642 if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) { 12643 if (mHardwareLayer.resize(width, height)) { 12644 mLocalDirtyRect.set(0, 0, width, height); 12645 } 12646 } 12647 12648 // This should not be necessary but applications that change 12649 // the parameters of their background drawable without calling 12650 // this.setBackground(Drawable) can leave the view in a bad state 12651 // (for instance isOpaque() returns true, but the background is 12652 // not opaque.) 12653 computeOpaqueFlags(); 12654 12655 final boolean opaque = isOpaque(); 12656 if (mHardwareLayer.isValid() && mHardwareLayer.isOpaque() != opaque) { 12657 mHardwareLayer.setOpaque(opaque); 12658 mLocalDirtyRect.set(0, 0, width, height); 12659 } 12660 } 12661 12662 // The layer is not valid if the underlying GPU resources cannot be allocated 12663 if (!mHardwareLayer.isValid()) { 12664 return null; 12665 } 12666 12667 mHardwareLayer.setLayerPaint(mLayerPaint); 12668 mHardwareLayer.redrawLater(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect); 12669 ViewRootImpl viewRoot = getViewRootImpl(); 12670 if (viewRoot != null) viewRoot.pushHardwareLayerUpdate(mHardwareLayer); 12671 12672 mLocalDirtyRect.setEmpty(); 12673 } 12674 12675 return mHardwareLayer; 12676 } 12677 12678 /** 12679 * Destroys this View's hardware layer if possible. 12680 * 12681 * @return True if the layer was destroyed, false otherwise. 12682 * 12683 * @see #setLayerType(int, android.graphics.Paint) 12684 * @see #LAYER_TYPE_HARDWARE 12685 */ 12686 boolean destroyLayer(boolean valid) { 12687 if (mHardwareLayer != null) { 12688 AttachInfo info = mAttachInfo; 12689 if (info != null && info.mHardwareRenderer != null && 12690 info.mHardwareRenderer.isEnabled() && 12691 (valid || info.mHardwareRenderer.validate())) { 12692 mHardwareLayer.destroy(); 12693 mHardwareLayer = null; 12694 12695 if (mDisplayList != null) { 12696 mDisplayList.reset(); 12697 } 12698 invalidate(true); 12699 invalidateParentCaches(); 12700 } 12701 return true; 12702 } 12703 return false; 12704 } 12705 12706 /** 12707 * Destroys all hardware rendering resources. This method is invoked 12708 * when the system needs to reclaim resources. Upon execution of this 12709 * method, you should free any OpenGL resources created by the view. 12710 * 12711 * Note: you <strong>must</strong> call 12712 * <code>super.destroyHardwareResources()</code> when overriding 12713 * this method. 12714 * 12715 * @hide 12716 */ 12717 protected void destroyHardwareResources() { 12718 clearDisplayList(); 12719 destroyLayer(true); 12720 } 12721 12722 /** 12723 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 12724 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 12725 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 12726 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 12727 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 12728 * null.</p> 12729 * 12730 * <p>Enabling the drawing cache is similar to 12731 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 12732 * acceleration is turned off. When hardware acceleration is turned on, enabling the 12733 * drawing cache has no effect on rendering because the system uses a different mechanism 12734 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 12735 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 12736 * for information on how to enable software and hardware layers.</p> 12737 * 12738 * <p>This API can be used to manually generate 12739 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 12740 * {@link #getDrawingCache()}.</p> 12741 * 12742 * @param enabled true to enable the drawing cache, false otherwise 12743 * 12744 * @see #isDrawingCacheEnabled() 12745 * @see #getDrawingCache() 12746 * @see #buildDrawingCache() 12747 * @see #setLayerType(int, android.graphics.Paint) 12748 */ 12749 public void setDrawingCacheEnabled(boolean enabled) { 12750 mCachingFailed = false; 12751 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 12752 } 12753 12754 /** 12755 * <p>Indicates whether the drawing cache is enabled for this view.</p> 12756 * 12757 * @return true if the drawing cache is enabled 12758 * 12759 * @see #setDrawingCacheEnabled(boolean) 12760 * @see #getDrawingCache() 12761 */ 12762 @ViewDebug.ExportedProperty(category = "drawing") 12763 public boolean isDrawingCacheEnabled() { 12764 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 12765 } 12766 12767 /** 12768 * Debugging utility which recursively outputs the dirty state of a view and its 12769 * descendants. 12770 * 12771 * @hide 12772 */ 12773 @SuppressWarnings({"UnusedDeclaration"}) 12774 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 12775 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 12776 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 12777 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 12778 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 12779 if (clear) { 12780 mPrivateFlags &= clearMask; 12781 } 12782 if (this instanceof ViewGroup) { 12783 ViewGroup parent = (ViewGroup) this; 12784 final int count = parent.getChildCount(); 12785 for (int i = 0; i < count; i++) { 12786 final View child = parent.getChildAt(i); 12787 child.outputDirtyFlags(indent + " ", clear, clearMask); 12788 } 12789 } 12790 } 12791 12792 /** 12793 * This method is used by ViewGroup to cause its children to restore or recreate their 12794 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 12795 * to recreate its own display list, which would happen if it went through the normal 12796 * draw/dispatchDraw mechanisms. 12797 * 12798 * @hide 12799 */ 12800 protected void dispatchGetDisplayList() {} 12801 12802 /** 12803 * A view that is not attached or hardware accelerated cannot create a display list. 12804 * This method checks these conditions and returns the appropriate result. 12805 * 12806 * @return true if view has the ability to create a display list, false otherwise. 12807 * 12808 * @hide 12809 */ 12810 public boolean canHaveDisplayList() { 12811 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 12812 } 12813 12814 /** 12815 * @return The {@link HardwareRenderer} associated with that view or null if 12816 * hardware rendering is not supported or this view is not attached 12817 * to a window. 12818 * 12819 * @hide 12820 */ 12821 public HardwareRenderer getHardwareRenderer() { 12822 if (mAttachInfo != null) { 12823 return mAttachInfo.mHardwareRenderer; 12824 } 12825 return null; 12826 } 12827 12828 /** 12829 * Returns a DisplayList. If the incoming displayList is null, one will be created. 12830 * Otherwise, the same display list will be returned (after having been rendered into 12831 * along the way, depending on the invalidation state of the view). 12832 * 12833 * @param displayList The previous version of this displayList, could be null. 12834 * @param isLayer Whether the requester of the display list is a layer. If so, 12835 * the view will avoid creating a layer inside the resulting display list. 12836 * @return A new or reused DisplayList object. 12837 */ 12838 private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) { 12839 if (!canHaveDisplayList()) { 12840 return null; 12841 } 12842 12843 if (((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || 12844 displayList == null || !displayList.isValid() || 12845 (!isLayer && mRecreateDisplayList))) { 12846 // Don't need to recreate the display list, just need to tell our 12847 // children to restore/recreate theirs 12848 if (displayList != null && displayList.isValid() && 12849 !isLayer && !mRecreateDisplayList) { 12850 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 12851 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 12852 dispatchGetDisplayList(); 12853 12854 return displayList; 12855 } 12856 12857 if (!isLayer) { 12858 // If we got here, we're recreating it. Mark it as such to ensure that 12859 // we copy in child display lists into ours in drawChild() 12860 mRecreateDisplayList = true; 12861 } 12862 if (displayList == null) { 12863 final String name = getClass().getSimpleName(); 12864 displayList = mAttachInfo.mHardwareRenderer.createDisplayList(name); 12865 // If we're creating a new display list, make sure our parent gets invalidated 12866 // since they will need to recreate their display list to account for this 12867 // new child display list. 12868 invalidateParentCaches(); 12869 } 12870 12871 boolean caching = false; 12872 int width = mRight - mLeft; 12873 int height = mBottom - mTop; 12874 int layerType = getLayerType(); 12875 12876 final HardwareCanvas canvas = displayList.start(width, height); 12877 12878 try { 12879 if (!isLayer && layerType != LAYER_TYPE_NONE) { 12880 if (layerType == LAYER_TYPE_HARDWARE) { 12881 final HardwareLayer layer = getHardwareLayer(); 12882 if (layer != null && layer.isValid()) { 12883 canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint); 12884 } else { 12885 canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint, 12886 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | 12887 Canvas.CLIP_TO_LAYER_SAVE_FLAG); 12888 } 12889 caching = true; 12890 } else { 12891 buildDrawingCache(true); 12892 Bitmap cache = getDrawingCache(true); 12893 if (cache != null) { 12894 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 12895 caching = true; 12896 } 12897 } 12898 } else { 12899 12900 computeScroll(); 12901 12902 canvas.translate(-mScrollX, -mScrollY); 12903 if (!isLayer) { 12904 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 12905 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 12906 } 12907 12908 // Fast path for layouts with no backgrounds 12909 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 12910 dispatchDraw(canvas); 12911 if (mOverlay != null && !mOverlay.isEmpty()) { 12912 mOverlay.getOverlayView().draw(canvas); 12913 } 12914 } else { 12915 draw(canvas); 12916 } 12917 } 12918 } finally { 12919 displayList.end(); 12920 displayList.setCaching(caching); 12921 if (isLayer) { 12922 displayList.setLeftTopRightBottom(0, 0, width, height); 12923 } else { 12924 setDisplayListProperties(displayList); 12925 } 12926 } 12927 } else if (!isLayer) { 12928 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 12929 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 12930 } 12931 12932 return displayList; 12933 } 12934 12935 /** 12936 * Get the DisplayList for the HardwareLayer 12937 * 12938 * @param layer The HardwareLayer whose DisplayList we want 12939 * @return A DisplayList fopr the specified HardwareLayer 12940 */ 12941 private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) { 12942 DisplayList displayList = getDisplayList(layer.getDisplayList(), true); 12943 layer.setDisplayList(displayList); 12944 return displayList; 12945 } 12946 12947 12948 /** 12949 * <p>Returns a display list that can be used to draw this view again 12950 * without executing its draw method.</p> 12951 * 12952 * @return A DisplayList ready to replay, or null if caching is not enabled. 12953 * 12954 * @hide 12955 */ 12956 public DisplayList getDisplayList() { 12957 mDisplayList = getDisplayList(mDisplayList, false); 12958 return mDisplayList; 12959 } 12960 12961 private void clearDisplayList() { 12962 if (mDisplayList != null) { 12963 mDisplayList.clear(); 12964 } 12965 } 12966 12967 /** 12968 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 12969 * 12970 * @return A non-scaled bitmap representing this view or null if cache is disabled. 12971 * 12972 * @see #getDrawingCache(boolean) 12973 */ 12974 public Bitmap getDrawingCache() { 12975 return getDrawingCache(false); 12976 } 12977 12978 /** 12979 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 12980 * is null when caching is disabled. If caching is enabled and the cache is not ready, 12981 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 12982 * draw from the cache when the cache is enabled. To benefit from the cache, you must 12983 * request the drawing cache by calling this method and draw it on screen if the 12984 * returned bitmap is not null.</p> 12985 * 12986 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 12987 * this method will create a bitmap of the same size as this view. Because this bitmap 12988 * will be drawn scaled by the parent ViewGroup, the result on screen might show 12989 * scaling artifacts. To avoid such artifacts, you should call this method by setting 12990 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 12991 * size than the view. This implies that your application must be able to handle this 12992 * size.</p> 12993 * 12994 * @param autoScale Indicates whether the generated bitmap should be scaled based on 12995 * the current density of the screen when the application is in compatibility 12996 * mode. 12997 * 12998 * @return A bitmap representing this view or null if cache is disabled. 12999 * 13000 * @see #setDrawingCacheEnabled(boolean) 13001 * @see #isDrawingCacheEnabled() 13002 * @see #buildDrawingCache(boolean) 13003 * @see #destroyDrawingCache() 13004 */ 13005 public Bitmap getDrawingCache(boolean autoScale) { 13006 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 13007 return null; 13008 } 13009 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 13010 buildDrawingCache(autoScale); 13011 } 13012 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 13013 } 13014 13015 /** 13016 * <p>Frees the resources used by the drawing cache. If you call 13017 * {@link #buildDrawingCache()} manually without calling 13018 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 13019 * should cleanup the cache with this method afterwards.</p> 13020 * 13021 * @see #setDrawingCacheEnabled(boolean) 13022 * @see #buildDrawingCache() 13023 * @see #getDrawingCache() 13024 */ 13025 public void destroyDrawingCache() { 13026 if (mDrawingCache != null) { 13027 mDrawingCache.recycle(); 13028 mDrawingCache = null; 13029 } 13030 if (mUnscaledDrawingCache != null) { 13031 mUnscaledDrawingCache.recycle(); 13032 mUnscaledDrawingCache = null; 13033 } 13034 } 13035 13036 /** 13037 * Setting a solid background color for the drawing cache's bitmaps will improve 13038 * performance and memory usage. Note, though that this should only be used if this 13039 * view will always be drawn on top of a solid color. 13040 * 13041 * @param color The background color to use for the drawing cache's bitmap 13042 * 13043 * @see #setDrawingCacheEnabled(boolean) 13044 * @see #buildDrawingCache() 13045 * @see #getDrawingCache() 13046 */ 13047 public void setDrawingCacheBackgroundColor(int color) { 13048 if (color != mDrawingCacheBackgroundColor) { 13049 mDrawingCacheBackgroundColor = color; 13050 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 13051 } 13052 } 13053 13054 /** 13055 * @see #setDrawingCacheBackgroundColor(int) 13056 * 13057 * @return The background color to used for the drawing cache's bitmap 13058 */ 13059 public int getDrawingCacheBackgroundColor() { 13060 return mDrawingCacheBackgroundColor; 13061 } 13062 13063 /** 13064 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 13065 * 13066 * @see #buildDrawingCache(boolean) 13067 */ 13068 public void buildDrawingCache() { 13069 buildDrawingCache(false); 13070 } 13071 13072 /** 13073 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 13074 * 13075 * <p>If you call {@link #buildDrawingCache()} manually without calling 13076 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 13077 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 13078 * 13079 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 13080 * this method will create a bitmap of the same size as this view. Because this bitmap 13081 * will be drawn scaled by the parent ViewGroup, the result on screen might show 13082 * scaling artifacts. To avoid such artifacts, you should call this method by setting 13083 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 13084 * size than the view. This implies that your application must be able to handle this 13085 * size.</p> 13086 * 13087 * <p>You should avoid calling this method when hardware acceleration is enabled. If 13088 * you do not need the drawing cache bitmap, calling this method will increase memory 13089 * usage and cause the view to be rendered in software once, thus negatively impacting 13090 * performance.</p> 13091 * 13092 * @see #getDrawingCache() 13093 * @see #destroyDrawingCache() 13094 */ 13095 public void buildDrawingCache(boolean autoScale) { 13096 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 13097 mDrawingCache == null : mUnscaledDrawingCache == null)) { 13098 mCachingFailed = false; 13099 13100 int width = mRight - mLeft; 13101 int height = mBottom - mTop; 13102 13103 final AttachInfo attachInfo = mAttachInfo; 13104 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 13105 13106 if (autoScale && scalingRequired) { 13107 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 13108 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 13109 } 13110 13111 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 13112 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 13113 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 13114 13115 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 13116 final long drawingCacheSize = 13117 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 13118 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 13119 if (width > 0 && height > 0) { 13120 Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs " 13121 + projectedBitmapSize + " bytes, only " 13122 + drawingCacheSize + " available"); 13123 } 13124 destroyDrawingCache(); 13125 mCachingFailed = true; 13126 return; 13127 } 13128 13129 boolean clear = true; 13130 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 13131 13132 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 13133 Bitmap.Config quality; 13134 if (!opaque) { 13135 // Never pick ARGB_4444 because it looks awful 13136 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 13137 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 13138 case DRAWING_CACHE_QUALITY_AUTO: 13139 quality = Bitmap.Config.ARGB_8888; 13140 break; 13141 case DRAWING_CACHE_QUALITY_LOW: 13142 quality = Bitmap.Config.ARGB_8888; 13143 break; 13144 case DRAWING_CACHE_QUALITY_HIGH: 13145 quality = Bitmap.Config.ARGB_8888; 13146 break; 13147 default: 13148 quality = Bitmap.Config.ARGB_8888; 13149 break; 13150 } 13151 } else { 13152 // Optimization for translucent windows 13153 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 13154 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 13155 } 13156 13157 // Try to cleanup memory 13158 if (bitmap != null) bitmap.recycle(); 13159 13160 try { 13161 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 13162 width, height, quality); 13163 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 13164 if (autoScale) { 13165 mDrawingCache = bitmap; 13166 } else { 13167 mUnscaledDrawingCache = bitmap; 13168 } 13169 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 13170 } catch (OutOfMemoryError e) { 13171 // If there is not enough memory to create the bitmap cache, just 13172 // ignore the issue as bitmap caches are not required to draw the 13173 // view hierarchy 13174 if (autoScale) { 13175 mDrawingCache = null; 13176 } else { 13177 mUnscaledDrawingCache = null; 13178 } 13179 mCachingFailed = true; 13180 return; 13181 } 13182 13183 clear = drawingCacheBackgroundColor != 0; 13184 } 13185 13186 Canvas canvas; 13187 if (attachInfo != null) { 13188 canvas = attachInfo.mCanvas; 13189 if (canvas == null) { 13190 canvas = new Canvas(); 13191 } 13192 canvas.setBitmap(bitmap); 13193 // Temporarily clobber the cached Canvas in case one of our children 13194 // is also using a drawing cache. Without this, the children would 13195 // steal the canvas by attaching their own bitmap to it and bad, bad 13196 // thing would happen (invisible views, corrupted drawings, etc.) 13197 attachInfo.mCanvas = null; 13198 } else { 13199 // This case should hopefully never or seldom happen 13200 canvas = new Canvas(bitmap); 13201 } 13202 13203 if (clear) { 13204 bitmap.eraseColor(drawingCacheBackgroundColor); 13205 } 13206 13207 computeScroll(); 13208 final int restoreCount = canvas.save(); 13209 13210 if (autoScale && scalingRequired) { 13211 final float scale = attachInfo.mApplicationScale; 13212 canvas.scale(scale, scale); 13213 } 13214 13215 canvas.translate(-mScrollX, -mScrollY); 13216 13217 mPrivateFlags |= PFLAG_DRAWN; 13218 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 13219 mLayerType != LAYER_TYPE_NONE) { 13220 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 13221 } 13222 13223 // Fast path for layouts with no backgrounds 13224 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 13225 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13226 dispatchDraw(canvas); 13227 if (mOverlay != null && !mOverlay.isEmpty()) { 13228 mOverlay.getOverlayView().draw(canvas); 13229 } 13230 } else { 13231 draw(canvas); 13232 } 13233 13234 canvas.restoreToCount(restoreCount); 13235 canvas.setBitmap(null); 13236 13237 if (attachInfo != null) { 13238 // Restore the cached Canvas for our siblings 13239 attachInfo.mCanvas = canvas; 13240 } 13241 } 13242 } 13243 13244 /** 13245 * Create a snapshot of the view into a bitmap. We should probably make 13246 * some form of this public, but should think about the API. 13247 */ 13248 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 13249 int width = mRight - mLeft; 13250 int height = mBottom - mTop; 13251 13252 final AttachInfo attachInfo = mAttachInfo; 13253 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 13254 width = (int) ((width * scale) + 0.5f); 13255 height = (int) ((height * scale) + 0.5f); 13256 13257 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 13258 width > 0 ? width : 1, height > 0 ? height : 1, quality); 13259 if (bitmap == null) { 13260 throw new OutOfMemoryError(); 13261 } 13262 13263 Resources resources = getResources(); 13264 if (resources != null) { 13265 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 13266 } 13267 13268 Canvas canvas; 13269 if (attachInfo != null) { 13270 canvas = attachInfo.mCanvas; 13271 if (canvas == null) { 13272 canvas = new Canvas(); 13273 } 13274 canvas.setBitmap(bitmap); 13275 // Temporarily clobber the cached Canvas in case one of our children 13276 // is also using a drawing cache. Without this, the children would 13277 // steal the canvas by attaching their own bitmap to it and bad, bad 13278 // things would happen (invisible views, corrupted drawings, etc.) 13279 attachInfo.mCanvas = null; 13280 } else { 13281 // This case should hopefully never or seldom happen 13282 canvas = new Canvas(bitmap); 13283 } 13284 13285 if ((backgroundColor & 0xff000000) != 0) { 13286 bitmap.eraseColor(backgroundColor); 13287 } 13288 13289 computeScroll(); 13290 final int restoreCount = canvas.save(); 13291 canvas.scale(scale, scale); 13292 canvas.translate(-mScrollX, -mScrollY); 13293 13294 // Temporarily remove the dirty mask 13295 int flags = mPrivateFlags; 13296 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13297 13298 // Fast path for layouts with no backgrounds 13299 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 13300 dispatchDraw(canvas); 13301 } else { 13302 draw(canvas); 13303 } 13304 13305 mPrivateFlags = flags; 13306 13307 canvas.restoreToCount(restoreCount); 13308 canvas.setBitmap(null); 13309 13310 if (attachInfo != null) { 13311 // Restore the cached Canvas for our siblings 13312 attachInfo.mCanvas = canvas; 13313 } 13314 13315 return bitmap; 13316 } 13317 13318 /** 13319 * Indicates whether this View is currently in edit mode. A View is usually 13320 * in edit mode when displayed within a developer tool. For instance, if 13321 * this View is being drawn by a visual user interface builder, this method 13322 * should return true. 13323 * 13324 * Subclasses should check the return value of this method to provide 13325 * different behaviors if their normal behavior might interfere with the 13326 * host environment. For instance: the class spawns a thread in its 13327 * constructor, the drawing code relies on device-specific features, etc. 13328 * 13329 * This method is usually checked in the drawing code of custom widgets. 13330 * 13331 * @return True if this View is in edit mode, false otherwise. 13332 */ 13333 public boolean isInEditMode() { 13334 return false; 13335 } 13336 13337 /** 13338 * If the View draws content inside its padding and enables fading edges, 13339 * it needs to support padding offsets. Padding offsets are added to the 13340 * fading edges to extend the length of the fade so that it covers pixels 13341 * drawn inside the padding. 13342 * 13343 * Subclasses of this class should override this method if they need 13344 * to draw content inside the padding. 13345 * 13346 * @return True if padding offset must be applied, false otherwise. 13347 * 13348 * @see #getLeftPaddingOffset() 13349 * @see #getRightPaddingOffset() 13350 * @see #getTopPaddingOffset() 13351 * @see #getBottomPaddingOffset() 13352 * 13353 * @since CURRENT 13354 */ 13355 protected boolean isPaddingOffsetRequired() { 13356 return false; 13357 } 13358 13359 /** 13360 * Amount by which to extend the left fading region. Called only when 13361 * {@link #isPaddingOffsetRequired()} returns true. 13362 * 13363 * @return The left padding offset in pixels. 13364 * 13365 * @see #isPaddingOffsetRequired() 13366 * 13367 * @since CURRENT 13368 */ 13369 protected int getLeftPaddingOffset() { 13370 return 0; 13371 } 13372 13373 /** 13374 * Amount by which to extend the right fading region. Called only when 13375 * {@link #isPaddingOffsetRequired()} returns true. 13376 * 13377 * @return The right padding offset in pixels. 13378 * 13379 * @see #isPaddingOffsetRequired() 13380 * 13381 * @since CURRENT 13382 */ 13383 protected int getRightPaddingOffset() { 13384 return 0; 13385 } 13386 13387 /** 13388 * Amount by which to extend the top fading region. Called only when 13389 * {@link #isPaddingOffsetRequired()} returns true. 13390 * 13391 * @return The top padding offset in pixels. 13392 * 13393 * @see #isPaddingOffsetRequired() 13394 * 13395 * @since CURRENT 13396 */ 13397 protected int getTopPaddingOffset() { 13398 return 0; 13399 } 13400 13401 /** 13402 * Amount by which to extend the bottom fading region. Called only when 13403 * {@link #isPaddingOffsetRequired()} returns true. 13404 * 13405 * @return The bottom padding offset in pixels. 13406 * 13407 * @see #isPaddingOffsetRequired() 13408 * 13409 * @since CURRENT 13410 */ 13411 protected int getBottomPaddingOffset() { 13412 return 0; 13413 } 13414 13415 /** 13416 * @hide 13417 * @param offsetRequired 13418 */ 13419 protected int getFadeTop(boolean offsetRequired) { 13420 int top = mPaddingTop; 13421 if (offsetRequired) top += getTopPaddingOffset(); 13422 return top; 13423 } 13424 13425 /** 13426 * @hide 13427 * @param offsetRequired 13428 */ 13429 protected int getFadeHeight(boolean offsetRequired) { 13430 int padding = mPaddingTop; 13431 if (offsetRequired) padding += getTopPaddingOffset(); 13432 return mBottom - mTop - mPaddingBottom - padding; 13433 } 13434 13435 /** 13436 * <p>Indicates whether this view is attached to a hardware accelerated 13437 * window or not.</p> 13438 * 13439 * <p>Even if this method returns true, it does not mean that every call 13440 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 13441 * accelerated {@link android.graphics.Canvas}. For instance, if this view 13442 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 13443 * window is hardware accelerated, 13444 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 13445 * return false, and this method will return true.</p> 13446 * 13447 * @return True if the view is attached to a window and the window is 13448 * hardware accelerated; false in any other case. 13449 */ 13450 public boolean isHardwareAccelerated() { 13451 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 13452 } 13453 13454 /** 13455 * Sets a rectangular area on this view to which the view will be clipped 13456 * when it is drawn. Setting the value to null will remove the clip bounds 13457 * and the view will draw normally, using its full bounds. 13458 * 13459 * @param clipBounds The rectangular area, in the local coordinates of 13460 * this view, to which future drawing operations will be clipped. 13461 */ 13462 public void setClipBounds(Rect clipBounds) { 13463 if (clipBounds != null) { 13464 if (clipBounds.equals(mClipBounds)) { 13465 return; 13466 } 13467 if (mClipBounds == null) { 13468 invalidate(); 13469 mClipBounds = new Rect(clipBounds); 13470 } else { 13471 invalidate(Math.min(mClipBounds.left, clipBounds.left), 13472 Math.min(mClipBounds.top, clipBounds.top), 13473 Math.max(mClipBounds.right, clipBounds.right), 13474 Math.max(mClipBounds.bottom, clipBounds.bottom)); 13475 mClipBounds.set(clipBounds); 13476 } 13477 } else { 13478 if (mClipBounds != null) { 13479 invalidate(); 13480 mClipBounds = null; 13481 } 13482 } 13483 } 13484 13485 /** 13486 * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}. 13487 * 13488 * @return A copy of the current clip bounds if clip bounds are set, 13489 * otherwise null. 13490 */ 13491 public Rect getClipBounds() { 13492 return (mClipBounds != null) ? new Rect(mClipBounds) : null; 13493 } 13494 13495 /** 13496 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 13497 * case of an active Animation being run on the view. 13498 */ 13499 private boolean drawAnimation(ViewGroup parent, long drawingTime, 13500 Animation a, boolean scalingRequired) { 13501 Transformation invalidationTransform; 13502 final int flags = parent.mGroupFlags; 13503 final boolean initialized = a.isInitialized(); 13504 if (!initialized) { 13505 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 13506 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 13507 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 13508 onAnimationStart(); 13509 } 13510 13511 boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f); 13512 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 13513 if (parent.mInvalidationTransformation == null) { 13514 parent.mInvalidationTransformation = new Transformation(); 13515 } 13516 invalidationTransform = parent.mInvalidationTransformation; 13517 a.getTransformation(drawingTime, invalidationTransform, 1f); 13518 } else { 13519 invalidationTransform = parent.mChildTransformation; 13520 } 13521 13522 if (more) { 13523 if (!a.willChangeBounds()) { 13524 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 13525 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 13526 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 13527 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 13528 // The child need to draw an animation, potentially offscreen, so 13529 // make sure we do not cancel invalidate requests 13530 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 13531 parent.invalidate(mLeft, mTop, mRight, mBottom); 13532 } 13533 } else { 13534 if (parent.mInvalidateRegion == null) { 13535 parent.mInvalidateRegion = new RectF(); 13536 } 13537 final RectF region = parent.mInvalidateRegion; 13538 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 13539 invalidationTransform); 13540 13541 // The child need to draw an animation, potentially offscreen, so 13542 // make sure we do not cancel invalidate requests 13543 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 13544 13545 final int left = mLeft + (int) region.left; 13546 final int top = mTop + (int) region.top; 13547 parent.invalidate(left, top, left + (int) (region.width() + .5f), 13548 top + (int) (region.height() + .5f)); 13549 } 13550 } 13551 return more; 13552 } 13553 13554 /** 13555 * This method is called by getDisplayList() when a display list is created or re-rendered. 13556 * It sets or resets the current value of all properties on that display list (resetting is 13557 * necessary when a display list is being re-created, because we need to make sure that 13558 * previously-set transform values 13559 */ 13560 void setDisplayListProperties(DisplayList displayList) { 13561 if (displayList != null) { 13562 displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 13563 displayList.setHasOverlappingRendering(hasOverlappingRendering()); 13564 if (mParent instanceof ViewGroup) { 13565 displayList.setClipToBounds( 13566 (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0); 13567 } 13568 float alpha = 1; 13569 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 13570 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 13571 ViewGroup parentVG = (ViewGroup) mParent; 13572 final boolean hasTransform = 13573 parentVG.getChildStaticTransformation(this, parentVG.mChildTransformation); 13574 if (hasTransform) { 13575 Transformation transform = parentVG.mChildTransformation; 13576 final int transformType = parentVG.mChildTransformation.getTransformationType(); 13577 if (transformType != Transformation.TYPE_IDENTITY) { 13578 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 13579 alpha = transform.getAlpha(); 13580 } 13581 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 13582 displayList.setMatrix(transform.getMatrix()); 13583 } 13584 } 13585 } 13586 } 13587 if (mTransformationInfo != null) { 13588 alpha *= mTransformationInfo.mAlpha; 13589 if (alpha < 1) { 13590 final int multipliedAlpha = (int) (255 * alpha); 13591 if (onSetAlpha(multipliedAlpha)) { 13592 alpha = 1; 13593 } 13594 } 13595 displayList.setTransformationInfo(alpha, 13596 mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY, 13597 mTransformationInfo.mRotation, mTransformationInfo.mRotationX, 13598 mTransformationInfo.mRotationY, mTransformationInfo.mScaleX, 13599 mTransformationInfo.mScaleY); 13600 if (mTransformationInfo.mCamera == null) { 13601 mTransformationInfo.mCamera = new Camera(); 13602 mTransformationInfo.matrix3D = new Matrix(); 13603 } 13604 displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ()); 13605 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == PFLAG_PIVOT_EXPLICITLY_SET) { 13606 displayList.setPivotX(getPivotX()); 13607 displayList.setPivotY(getPivotY()); 13608 } 13609 } else if (alpha < 1) { 13610 displayList.setAlpha(alpha); 13611 } 13612 } 13613 } 13614 13615 /** 13616 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 13617 * This draw() method is an implementation detail and is not intended to be overridden or 13618 * to be called from anywhere else other than ViewGroup.drawChild(). 13619 */ 13620 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 13621 boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 13622 boolean more = false; 13623 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 13624 final int flags = parent.mGroupFlags; 13625 13626 if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) { 13627 parent.mChildTransformation.clear(); 13628 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 13629 } 13630 13631 Transformation transformToApply = null; 13632 boolean concatMatrix = false; 13633 13634 boolean scalingRequired = false; 13635 boolean caching; 13636 int layerType = getLayerType(); 13637 13638 final boolean hardwareAccelerated = canvas.isHardwareAccelerated(); 13639 if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 || 13640 (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) { 13641 caching = true; 13642 // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList 13643 if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired; 13644 } else { 13645 caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated; 13646 } 13647 13648 final Animation a = getAnimation(); 13649 if (a != null) { 13650 more = drawAnimation(parent, drawingTime, a, scalingRequired); 13651 concatMatrix = a.willChangeTransformationMatrix(); 13652 if (concatMatrix) { 13653 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 13654 } 13655 transformToApply = parent.mChildTransformation; 13656 } else { 13657 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) == 13658 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM && mDisplayList != null) { 13659 // No longer animating: clear out old animation matrix 13660 mDisplayList.setAnimationMatrix(null); 13661 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 13662 } 13663 if (!useDisplayListProperties && 13664 (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 13665 final boolean hasTransform = 13666 parent.getChildStaticTransformation(this, parent.mChildTransformation); 13667 if (hasTransform) { 13668 final int transformType = parent.mChildTransformation.getTransformationType(); 13669 transformToApply = transformType != Transformation.TYPE_IDENTITY ? 13670 parent.mChildTransformation : null; 13671 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 13672 } 13673 } 13674 } 13675 13676 concatMatrix |= !childHasIdentityMatrix; 13677 13678 // Sets the flag as early as possible to allow draw() implementations 13679 // to call invalidate() successfully when doing animations 13680 mPrivateFlags |= PFLAG_DRAWN; 13681 13682 if (!concatMatrix && 13683 (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 13684 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 13685 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 13686 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 13687 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 13688 return more; 13689 } 13690 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 13691 13692 if (hardwareAccelerated) { 13693 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 13694 // retain the flag's value temporarily in the mRecreateDisplayList flag 13695 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED; 13696 mPrivateFlags &= ~PFLAG_INVALIDATED; 13697 } 13698 13699 DisplayList displayList = null; 13700 Bitmap cache = null; 13701 boolean hasDisplayList = false; 13702 if (caching) { 13703 if (!hardwareAccelerated) { 13704 if (layerType != LAYER_TYPE_NONE) { 13705 layerType = LAYER_TYPE_SOFTWARE; 13706 buildDrawingCache(true); 13707 } 13708 cache = getDrawingCache(true); 13709 } else { 13710 switch (layerType) { 13711 case LAYER_TYPE_SOFTWARE: 13712 if (useDisplayListProperties) { 13713 hasDisplayList = canHaveDisplayList(); 13714 } else { 13715 buildDrawingCache(true); 13716 cache = getDrawingCache(true); 13717 } 13718 break; 13719 case LAYER_TYPE_HARDWARE: 13720 if (useDisplayListProperties) { 13721 hasDisplayList = canHaveDisplayList(); 13722 } 13723 break; 13724 case LAYER_TYPE_NONE: 13725 // Delay getting the display list until animation-driven alpha values are 13726 // set up and possibly passed on to the view 13727 hasDisplayList = canHaveDisplayList(); 13728 break; 13729 } 13730 } 13731 } 13732 useDisplayListProperties &= hasDisplayList; 13733 if (useDisplayListProperties) { 13734 displayList = getDisplayList(); 13735 if (!displayList.isValid()) { 13736 // Uncommon, but possible. If a view is removed from the hierarchy during the call 13737 // to getDisplayList(), the display list will be marked invalid and we should not 13738 // try to use it again. 13739 displayList = null; 13740 hasDisplayList = false; 13741 useDisplayListProperties = false; 13742 } 13743 } 13744 13745 int sx = 0; 13746 int sy = 0; 13747 if (!hasDisplayList) { 13748 computeScroll(); 13749 sx = mScrollX; 13750 sy = mScrollY; 13751 } 13752 13753 final boolean hasNoCache = cache == null || hasDisplayList; 13754 final boolean offsetForScroll = cache == null && !hasDisplayList && 13755 layerType != LAYER_TYPE_HARDWARE; 13756 13757 int restoreTo = -1; 13758 if (!useDisplayListProperties || transformToApply != null) { 13759 restoreTo = canvas.save(); 13760 } 13761 if (offsetForScroll) { 13762 canvas.translate(mLeft - sx, mTop - sy); 13763 } else { 13764 if (!useDisplayListProperties) { 13765 canvas.translate(mLeft, mTop); 13766 } 13767 if (scalingRequired) { 13768 if (useDisplayListProperties) { 13769 // TODO: Might not need this if we put everything inside the DL 13770 restoreTo = canvas.save(); 13771 } 13772 // mAttachInfo cannot be null, otherwise scalingRequired == false 13773 final float scale = 1.0f / mAttachInfo.mApplicationScale; 13774 canvas.scale(scale, scale); 13775 } 13776 } 13777 13778 float alpha = useDisplayListProperties ? 1 : getAlpha(); 13779 if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() || 13780 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 13781 if (transformToApply != null || !childHasIdentityMatrix) { 13782 int transX = 0; 13783 int transY = 0; 13784 13785 if (offsetForScroll) { 13786 transX = -sx; 13787 transY = -sy; 13788 } 13789 13790 if (transformToApply != null) { 13791 if (concatMatrix) { 13792 if (useDisplayListProperties) { 13793 displayList.setAnimationMatrix(transformToApply.getMatrix()); 13794 } else { 13795 // Undo the scroll translation, apply the transformation matrix, 13796 // then redo the scroll translate to get the correct result. 13797 canvas.translate(-transX, -transY); 13798 canvas.concat(transformToApply.getMatrix()); 13799 canvas.translate(transX, transY); 13800 } 13801 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 13802 } 13803 13804 float transformAlpha = transformToApply.getAlpha(); 13805 if (transformAlpha < 1) { 13806 alpha *= transformAlpha; 13807 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 13808 } 13809 } 13810 13811 if (!childHasIdentityMatrix && !useDisplayListProperties) { 13812 canvas.translate(-transX, -transY); 13813 canvas.concat(getMatrix()); 13814 canvas.translate(transX, transY); 13815 } 13816 } 13817 13818 // Deal with alpha if it is or used to be <1 13819 if (alpha < 1 || 13820 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 13821 if (alpha < 1) { 13822 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 13823 } else { 13824 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 13825 } 13826 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 13827 if (hasNoCache) { 13828 final int multipliedAlpha = (int) (255 * alpha); 13829 if (!onSetAlpha(multipliedAlpha)) { 13830 int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 13831 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 || 13832 layerType != LAYER_TYPE_NONE) { 13833 layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG; 13834 } 13835 if (useDisplayListProperties) { 13836 displayList.setAlpha(alpha * getAlpha()); 13837 } else if (layerType == LAYER_TYPE_NONE) { 13838 final int scrollX = hasDisplayList ? 0 : sx; 13839 final int scrollY = hasDisplayList ? 0 : sy; 13840 canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft, 13841 scrollY + mBottom - mTop, multipliedAlpha, layerFlags); 13842 } 13843 } else { 13844 // Alpha is handled by the child directly, clobber the layer's alpha 13845 mPrivateFlags |= PFLAG_ALPHA_SET; 13846 } 13847 } 13848 } 13849 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 13850 onSetAlpha(255); 13851 mPrivateFlags &= ~PFLAG_ALPHA_SET; 13852 } 13853 13854 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN && 13855 !useDisplayListProperties && cache == null) { 13856 if (offsetForScroll) { 13857 canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop)); 13858 } else { 13859 if (!scalingRequired || cache == null) { 13860 canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop); 13861 } else { 13862 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 13863 } 13864 } 13865 } 13866 13867 if (!useDisplayListProperties && hasDisplayList) { 13868 displayList = getDisplayList(); 13869 if (!displayList.isValid()) { 13870 // Uncommon, but possible. If a view is removed from the hierarchy during the call 13871 // to getDisplayList(), the display list will be marked invalid and we should not 13872 // try to use it again. 13873 displayList = null; 13874 hasDisplayList = false; 13875 } 13876 } 13877 13878 if (hasNoCache) { 13879 boolean layerRendered = false; 13880 if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) { 13881 final HardwareLayer layer = getHardwareLayer(); 13882 if (layer != null && layer.isValid()) { 13883 mLayerPaint.setAlpha((int) (alpha * 255)); 13884 ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint); 13885 layerRendered = true; 13886 } else { 13887 final int scrollX = hasDisplayList ? 0 : sx; 13888 final int scrollY = hasDisplayList ? 0 : sy; 13889 canvas.saveLayer(scrollX, scrollY, 13890 scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint, 13891 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG); 13892 } 13893 } 13894 13895 if (!layerRendered) { 13896 if (!hasDisplayList) { 13897 // Fast path for layouts with no backgrounds 13898 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 13899 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13900 dispatchDraw(canvas); 13901 } else { 13902 draw(canvas); 13903 } 13904 } else { 13905 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13906 ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags); 13907 } 13908 } 13909 } else if (cache != null) { 13910 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13911 Paint cachePaint; 13912 13913 if (layerType == LAYER_TYPE_NONE) { 13914 cachePaint = parent.mCachePaint; 13915 if (cachePaint == null) { 13916 cachePaint = new Paint(); 13917 cachePaint.setDither(false); 13918 parent.mCachePaint = cachePaint; 13919 } 13920 if (alpha < 1) { 13921 cachePaint.setAlpha((int) (alpha * 255)); 13922 parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 13923 } else if ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) { 13924 cachePaint.setAlpha(255); 13925 parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 13926 } 13927 } else { 13928 cachePaint = mLayerPaint; 13929 cachePaint.setAlpha((int) (alpha * 255)); 13930 } 13931 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 13932 } 13933 13934 if (restoreTo >= 0) { 13935 canvas.restoreToCount(restoreTo); 13936 } 13937 13938 if (a != null && !more) { 13939 if (!hardwareAccelerated && !a.getFillAfter()) { 13940 onSetAlpha(255); 13941 } 13942 parent.finishAnimatingView(this, a); 13943 } 13944 13945 if (more && hardwareAccelerated) { 13946 // invalidation is the trigger to recreate display lists, so if we're using 13947 // display lists to render, force an invalidate to allow the animation to 13948 // continue drawing another frame 13949 parent.invalidate(true); 13950 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 13951 // alpha animations should cause the child to recreate its display list 13952 invalidate(true); 13953 } 13954 } 13955 13956 mRecreateDisplayList = false; 13957 13958 return more; 13959 } 13960 13961 /** 13962 * Manually render this view (and all of its children) to the given Canvas. 13963 * The view must have already done a full layout before this function is 13964 * called. When implementing a view, implement 13965 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 13966 * If you do need to override this method, call the superclass version. 13967 * 13968 * @param canvas The Canvas to which the View is rendered. 13969 */ 13970 public void draw(Canvas canvas) { 13971 if (mClipBounds != null) { 13972 canvas.clipRect(mClipBounds); 13973 } 13974 final int privateFlags = mPrivateFlags; 13975 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 13976 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 13977 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 13978 13979 /* 13980 * Draw traversal performs several drawing steps which must be executed 13981 * in the appropriate order: 13982 * 13983 * 1. Draw the background 13984 * 2. If necessary, save the canvas' layers to prepare for fading 13985 * 3. Draw view's content 13986 * 4. Draw children 13987 * 5. If necessary, draw the fading edges and restore layers 13988 * 6. Draw decorations (scrollbars for instance) 13989 */ 13990 13991 // Step 1, draw the background, if needed 13992 int saveCount; 13993 13994 if (!dirtyOpaque) { 13995 final Drawable background = mBackground; 13996 if (background != null) { 13997 final int scrollX = mScrollX; 13998 final int scrollY = mScrollY; 13999 14000 if (mBackgroundSizeChanged) { 14001 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 14002 mBackgroundSizeChanged = false; 14003 } 14004 14005 if ((scrollX | scrollY) == 0) { 14006 background.draw(canvas); 14007 } else { 14008 canvas.translate(scrollX, scrollY); 14009 background.draw(canvas); 14010 canvas.translate(-scrollX, -scrollY); 14011 } 14012 } 14013 } 14014 14015 // skip step 2 & 5 if possible (common case) 14016 final int viewFlags = mViewFlags; 14017 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 14018 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 14019 if (!verticalEdges && !horizontalEdges) { 14020 // Step 3, draw the content 14021 if (!dirtyOpaque) onDraw(canvas); 14022 14023 // Step 4, draw the children 14024 dispatchDraw(canvas); 14025 14026 // Step 6, draw decorations (scrollbars) 14027 onDrawScrollBars(canvas); 14028 14029 if (mOverlay != null && !mOverlay.isEmpty()) { 14030 mOverlay.getOverlayView().dispatchDraw(canvas); 14031 } 14032 14033 // we're done... 14034 return; 14035 } 14036 14037 /* 14038 * Here we do the full fledged routine... 14039 * (this is an uncommon case where speed matters less, 14040 * this is why we repeat some of the tests that have been 14041 * done above) 14042 */ 14043 14044 boolean drawTop = false; 14045 boolean drawBottom = false; 14046 boolean drawLeft = false; 14047 boolean drawRight = false; 14048 14049 float topFadeStrength = 0.0f; 14050 float bottomFadeStrength = 0.0f; 14051 float leftFadeStrength = 0.0f; 14052 float rightFadeStrength = 0.0f; 14053 14054 // Step 2, save the canvas' layers 14055 int paddingLeft = mPaddingLeft; 14056 14057 final boolean offsetRequired = isPaddingOffsetRequired(); 14058 if (offsetRequired) { 14059 paddingLeft += getLeftPaddingOffset(); 14060 } 14061 14062 int left = mScrollX + paddingLeft; 14063 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 14064 int top = mScrollY + getFadeTop(offsetRequired); 14065 int bottom = top + getFadeHeight(offsetRequired); 14066 14067 if (offsetRequired) { 14068 right += getRightPaddingOffset(); 14069 bottom += getBottomPaddingOffset(); 14070 } 14071 14072 final ScrollabilityCache scrollabilityCache = mScrollCache; 14073 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 14074 int length = (int) fadeHeight; 14075 14076 // clip the fade length if top and bottom fades overlap 14077 // overlapping fades produce odd-looking artifacts 14078 if (verticalEdges && (top + length > bottom - length)) { 14079 length = (bottom - top) / 2; 14080 } 14081 14082 // also clip horizontal fades if necessary 14083 if (horizontalEdges && (left + length > right - length)) { 14084 length = (right - left) / 2; 14085 } 14086 14087 if (verticalEdges) { 14088 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 14089 drawTop = topFadeStrength * fadeHeight > 1.0f; 14090 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 14091 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 14092 } 14093 14094 if (horizontalEdges) { 14095 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 14096 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 14097 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 14098 drawRight = rightFadeStrength * fadeHeight > 1.0f; 14099 } 14100 14101 saveCount = canvas.getSaveCount(); 14102 14103 int solidColor = getSolidColor(); 14104 if (solidColor == 0) { 14105 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 14106 14107 if (drawTop) { 14108 canvas.saveLayer(left, top, right, top + length, null, flags); 14109 } 14110 14111 if (drawBottom) { 14112 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 14113 } 14114 14115 if (drawLeft) { 14116 canvas.saveLayer(left, top, left + length, bottom, null, flags); 14117 } 14118 14119 if (drawRight) { 14120 canvas.saveLayer(right - length, top, right, bottom, null, flags); 14121 } 14122 } else { 14123 scrollabilityCache.setFadeColor(solidColor); 14124 } 14125 14126 // Step 3, draw the content 14127 if (!dirtyOpaque) onDraw(canvas); 14128 14129 // Step 4, draw the children 14130 dispatchDraw(canvas); 14131 14132 // Step 5, draw the fade effect and restore layers 14133 final Paint p = scrollabilityCache.paint; 14134 final Matrix matrix = scrollabilityCache.matrix; 14135 final Shader fade = scrollabilityCache.shader; 14136 14137 if (drawTop) { 14138 matrix.setScale(1, fadeHeight * topFadeStrength); 14139 matrix.postTranslate(left, top); 14140 fade.setLocalMatrix(matrix); 14141 canvas.drawRect(left, top, right, top + length, p); 14142 } 14143 14144 if (drawBottom) { 14145 matrix.setScale(1, fadeHeight * bottomFadeStrength); 14146 matrix.postRotate(180); 14147 matrix.postTranslate(left, bottom); 14148 fade.setLocalMatrix(matrix); 14149 canvas.drawRect(left, bottom - length, right, bottom, p); 14150 } 14151 14152 if (drawLeft) { 14153 matrix.setScale(1, fadeHeight * leftFadeStrength); 14154 matrix.postRotate(-90); 14155 matrix.postTranslate(left, top); 14156 fade.setLocalMatrix(matrix); 14157 canvas.drawRect(left, top, left + length, bottom, p); 14158 } 14159 14160 if (drawRight) { 14161 matrix.setScale(1, fadeHeight * rightFadeStrength); 14162 matrix.postRotate(90); 14163 matrix.postTranslate(right, top); 14164 fade.setLocalMatrix(matrix); 14165 canvas.drawRect(right - length, top, right, bottom, p); 14166 } 14167 14168 canvas.restoreToCount(saveCount); 14169 14170 // Step 6, draw decorations (scrollbars) 14171 onDrawScrollBars(canvas); 14172 14173 if (mOverlay != null && !mOverlay.isEmpty()) { 14174 mOverlay.getOverlayView().dispatchDraw(canvas); 14175 } 14176 } 14177 14178 /** 14179 * Returns the overlay for this view, creating it if it does not yet exist. 14180 * Adding drawables to the overlay will cause them to be displayed whenever 14181 * the view itself is redrawn. Objects in the overlay should be actively 14182 * managed: remove them when they should not be displayed anymore. The 14183 * overlay will always have the same size as its host view. 14184 * 14185 * <p>Note: Overlays do not currently work correctly with {@link 14186 * SurfaceView} or {@link TextureView}; contents in overlays for these 14187 * types of views may not display correctly.</p> 14188 * 14189 * @return The ViewOverlay object for this view. 14190 * @see ViewOverlay 14191 */ 14192 public ViewOverlay getOverlay() { 14193 if (mOverlay == null) { 14194 mOverlay = new ViewOverlay(mContext, this); 14195 } 14196 return mOverlay; 14197 } 14198 14199 /** 14200 * Override this if your view is known to always be drawn on top of a solid color background, 14201 * and needs to draw fading edges. Returning a non-zero color enables the view system to 14202 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 14203 * should be set to 0xFF. 14204 * 14205 * @see #setVerticalFadingEdgeEnabled(boolean) 14206 * @see #setHorizontalFadingEdgeEnabled(boolean) 14207 * 14208 * @return The known solid color background for this view, or 0 if the color may vary 14209 */ 14210 @ViewDebug.ExportedProperty(category = "drawing") 14211 public int getSolidColor() { 14212 return 0; 14213 } 14214 14215 /** 14216 * Build a human readable string representation of the specified view flags. 14217 * 14218 * @param flags the view flags to convert to a string 14219 * @return a String representing the supplied flags 14220 */ 14221 private static String printFlags(int flags) { 14222 String output = ""; 14223 int numFlags = 0; 14224 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 14225 output += "TAKES_FOCUS"; 14226 numFlags++; 14227 } 14228 14229 switch (flags & VISIBILITY_MASK) { 14230 case INVISIBLE: 14231 if (numFlags > 0) { 14232 output += " "; 14233 } 14234 output += "INVISIBLE"; 14235 // USELESS HERE numFlags++; 14236 break; 14237 case GONE: 14238 if (numFlags > 0) { 14239 output += " "; 14240 } 14241 output += "GONE"; 14242 // USELESS HERE numFlags++; 14243 break; 14244 default: 14245 break; 14246 } 14247 return output; 14248 } 14249 14250 /** 14251 * Build a human readable string representation of the specified private 14252 * view flags. 14253 * 14254 * @param privateFlags the private view flags to convert to a string 14255 * @return a String representing the supplied flags 14256 */ 14257 private static String printPrivateFlags(int privateFlags) { 14258 String output = ""; 14259 int numFlags = 0; 14260 14261 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 14262 output += "WANTS_FOCUS"; 14263 numFlags++; 14264 } 14265 14266 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 14267 if (numFlags > 0) { 14268 output += " "; 14269 } 14270 output += "FOCUSED"; 14271 numFlags++; 14272 } 14273 14274 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 14275 if (numFlags > 0) { 14276 output += " "; 14277 } 14278 output += "SELECTED"; 14279 numFlags++; 14280 } 14281 14282 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 14283 if (numFlags > 0) { 14284 output += " "; 14285 } 14286 output += "IS_ROOT_NAMESPACE"; 14287 numFlags++; 14288 } 14289 14290 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 14291 if (numFlags > 0) { 14292 output += " "; 14293 } 14294 output += "HAS_BOUNDS"; 14295 numFlags++; 14296 } 14297 14298 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 14299 if (numFlags > 0) { 14300 output += " "; 14301 } 14302 output += "DRAWN"; 14303 // USELESS HERE numFlags++; 14304 } 14305 return output; 14306 } 14307 14308 /** 14309 * <p>Indicates whether or not this view's layout will be requested during 14310 * the next hierarchy layout pass.</p> 14311 * 14312 * @return true if the layout will be forced during next layout pass 14313 */ 14314 public boolean isLayoutRequested() { 14315 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 14316 } 14317 14318 /** 14319 * Return true if o is a ViewGroup that is laying out using optical bounds. 14320 * @hide 14321 */ 14322 public static boolean isLayoutModeOptical(Object o) { 14323 return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical(); 14324 } 14325 14326 private boolean setOpticalFrame(int left, int top, int right, int bottom) { 14327 Insets parentInsets = mParent instanceof View ? 14328 ((View) mParent).getOpticalInsets() : Insets.NONE; 14329 Insets childInsets = getOpticalInsets(); 14330 return setFrame( 14331 left + parentInsets.left - childInsets.left, 14332 top + parentInsets.top - childInsets.top, 14333 right + parentInsets.left + childInsets.right, 14334 bottom + parentInsets.top + childInsets.bottom); 14335 } 14336 14337 /** 14338 * Assign a size and position to a view and all of its 14339 * descendants 14340 * 14341 * <p>This is the second phase of the layout mechanism. 14342 * (The first is measuring). In this phase, each parent calls 14343 * layout on all of its children to position them. 14344 * This is typically done using the child measurements 14345 * that were stored in the measure pass().</p> 14346 * 14347 * <p>Derived classes should not override this method. 14348 * Derived classes with children should override 14349 * onLayout. In that method, they should 14350 * call layout on each of their children.</p> 14351 * 14352 * @param l Left position, relative to parent 14353 * @param t Top position, relative to parent 14354 * @param r Right position, relative to parent 14355 * @param b Bottom position, relative to parent 14356 */ 14357 @SuppressWarnings({"unchecked"}) 14358 public void layout(int l, int t, int r, int b) { 14359 int oldL = mLeft; 14360 int oldT = mTop; 14361 int oldB = mBottom; 14362 int oldR = mRight; 14363 boolean changed = isLayoutModeOptical(mParent) ? 14364 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); 14365 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 14366 onLayout(changed, l, t, r, b); 14367 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 14368 14369 ListenerInfo li = mListenerInfo; 14370 if (li != null && li.mOnLayoutChangeListeners != null) { 14371 ArrayList<OnLayoutChangeListener> listenersCopy = 14372 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 14373 int numListeners = listenersCopy.size(); 14374 for (int i = 0; i < numListeners; ++i) { 14375 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 14376 } 14377 } 14378 } 14379 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 14380 } 14381 14382 /** 14383 * Called from layout when this view should 14384 * assign a size and position to each of its children. 14385 * 14386 * Derived classes with children should override 14387 * this method and call layout on each of 14388 * their children. 14389 * @param changed This is a new size or position for this view 14390 * @param left Left position, relative to parent 14391 * @param top Top position, relative to parent 14392 * @param right Right position, relative to parent 14393 * @param bottom Bottom position, relative to parent 14394 */ 14395 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 14396 } 14397 14398 /** 14399 * Assign a size and position to this view. 14400 * 14401 * This is called from layout. 14402 * 14403 * @param left Left position, relative to parent 14404 * @param top Top position, relative to parent 14405 * @param right Right position, relative to parent 14406 * @param bottom Bottom position, relative to parent 14407 * @return true if the new size and position are different than the 14408 * previous ones 14409 * {@hide} 14410 */ 14411 protected boolean setFrame(int left, int top, int right, int bottom) { 14412 boolean changed = false; 14413 14414 if (DBG) { 14415 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 14416 + right + "," + bottom + ")"); 14417 } 14418 14419 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 14420 changed = true; 14421 14422 // Remember our drawn bit 14423 int drawn = mPrivateFlags & PFLAG_DRAWN; 14424 14425 int oldWidth = mRight - mLeft; 14426 int oldHeight = mBottom - mTop; 14427 int newWidth = right - left; 14428 int newHeight = bottom - top; 14429 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 14430 14431 // Invalidate our old position 14432 invalidate(sizeChanged); 14433 14434 mLeft = left; 14435 mTop = top; 14436 mRight = right; 14437 mBottom = bottom; 14438 if (mDisplayList != null) { 14439 mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 14440 } 14441 14442 mPrivateFlags |= PFLAG_HAS_BOUNDS; 14443 14444 14445 if (sizeChanged) { 14446 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 14447 // A change in dimension means an auto-centered pivot point changes, too 14448 if (mTransformationInfo != null) { 14449 mTransformationInfo.mMatrixDirty = true; 14450 } 14451 } 14452 sizeChange(newWidth, newHeight, oldWidth, oldHeight); 14453 } 14454 14455 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 14456 // If we are visible, force the DRAWN bit to on so that 14457 // this invalidate will go through (at least to our parent). 14458 // This is because someone may have invalidated this view 14459 // before this call to setFrame came in, thereby clearing 14460 // the DRAWN bit. 14461 mPrivateFlags |= PFLAG_DRAWN; 14462 invalidate(sizeChanged); 14463 // parent display list may need to be recreated based on a change in the bounds 14464 // of any child 14465 invalidateParentCaches(); 14466 } 14467 14468 // Reset drawn bit to original value (invalidate turns it off) 14469 mPrivateFlags |= drawn; 14470 14471 mBackgroundSizeChanged = true; 14472 14473 notifySubtreeAccessibilityStateChangedIfNeeded(); 14474 } 14475 return changed; 14476 } 14477 14478 private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) { 14479 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 14480 if (mOverlay != null) { 14481 mOverlay.getOverlayView().setRight(newWidth); 14482 mOverlay.getOverlayView().setBottom(newHeight); 14483 } 14484 } 14485 14486 /** 14487 * Finalize inflating a view from XML. This is called as the last phase 14488 * of inflation, after all child views have been added. 14489 * 14490 * <p>Even if the subclass overrides onFinishInflate, they should always be 14491 * sure to call the super method, so that we get called. 14492 */ 14493 protected void onFinishInflate() { 14494 } 14495 14496 /** 14497 * Returns the resources associated with this view. 14498 * 14499 * @return Resources object. 14500 */ 14501 public Resources getResources() { 14502 return mResources; 14503 } 14504 14505 /** 14506 * Invalidates the specified Drawable. 14507 * 14508 * @param drawable the drawable to invalidate 14509 */ 14510 public void invalidateDrawable(Drawable drawable) { 14511 if (verifyDrawable(drawable)) { 14512 final Rect dirty = drawable.getBounds(); 14513 final int scrollX = mScrollX; 14514 final int scrollY = mScrollY; 14515 14516 invalidate(dirty.left + scrollX, dirty.top + scrollY, 14517 dirty.right + scrollX, dirty.bottom + scrollY); 14518 } 14519 } 14520 14521 /** 14522 * Schedules an action on a drawable to occur at a specified time. 14523 * 14524 * @param who the recipient of the action 14525 * @param what the action to run on the drawable 14526 * @param when the time at which the action must occur. Uses the 14527 * {@link SystemClock#uptimeMillis} timebase. 14528 */ 14529 public void scheduleDrawable(Drawable who, Runnable what, long when) { 14530 if (verifyDrawable(who) && what != null) { 14531 final long delay = when - SystemClock.uptimeMillis(); 14532 if (mAttachInfo != null) { 14533 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 14534 Choreographer.CALLBACK_ANIMATION, what, who, 14535 Choreographer.subtractFrameDelay(delay)); 14536 } else { 14537 ViewRootImpl.getRunQueue().postDelayed(what, delay); 14538 } 14539 } 14540 } 14541 14542 /** 14543 * Cancels a scheduled action on a drawable. 14544 * 14545 * @param who the recipient of the action 14546 * @param what the action to cancel 14547 */ 14548 public void unscheduleDrawable(Drawable who, Runnable what) { 14549 if (verifyDrawable(who) && what != null) { 14550 if (mAttachInfo != null) { 14551 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 14552 Choreographer.CALLBACK_ANIMATION, what, who); 14553 } else { 14554 ViewRootImpl.getRunQueue().removeCallbacks(what); 14555 } 14556 } 14557 } 14558 14559 /** 14560 * Unschedule any events associated with the given Drawable. This can be 14561 * used when selecting a new Drawable into a view, so that the previous 14562 * one is completely unscheduled. 14563 * 14564 * @param who The Drawable to unschedule. 14565 * 14566 * @see #drawableStateChanged 14567 */ 14568 public void unscheduleDrawable(Drawable who) { 14569 if (mAttachInfo != null && who != null) { 14570 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 14571 Choreographer.CALLBACK_ANIMATION, null, who); 14572 } 14573 } 14574 14575 /** 14576 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 14577 * that the View directionality can and will be resolved before its Drawables. 14578 * 14579 * Will call {@link View#onResolveDrawables} when resolution is done. 14580 * 14581 * @hide 14582 */ 14583 protected void resolveDrawables() { 14584 if (canResolveLayoutDirection()) { 14585 if (mBackground != null) { 14586 mBackground.setLayoutDirection(getLayoutDirection()); 14587 } 14588 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED; 14589 onResolveDrawables(getLayoutDirection()); 14590 } 14591 } 14592 14593 /** 14594 * Called when layout direction has been resolved. 14595 * 14596 * The default implementation does nothing. 14597 * 14598 * @param layoutDirection The resolved layout direction. 14599 * 14600 * @see #LAYOUT_DIRECTION_LTR 14601 * @see #LAYOUT_DIRECTION_RTL 14602 * 14603 * @hide 14604 */ 14605 public void onResolveDrawables(int layoutDirection) { 14606 } 14607 14608 /** 14609 * @hide 14610 */ 14611 protected void resetResolvedDrawables() { 14612 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED; 14613 } 14614 14615 private boolean isDrawablesResolved() { 14616 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED; 14617 } 14618 14619 /** 14620 * If your view subclass is displaying its own Drawable objects, it should 14621 * override this function and return true for any Drawable it is 14622 * displaying. This allows animations for those drawables to be 14623 * scheduled. 14624 * 14625 * <p>Be sure to call through to the super class when overriding this 14626 * function. 14627 * 14628 * @param who The Drawable to verify. Return true if it is one you are 14629 * displaying, else return the result of calling through to the 14630 * super class. 14631 * 14632 * @return boolean If true than the Drawable is being displayed in the 14633 * view; else false and it is not allowed to animate. 14634 * 14635 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 14636 * @see #drawableStateChanged() 14637 */ 14638 protected boolean verifyDrawable(Drawable who) { 14639 return who == mBackground; 14640 } 14641 14642 /** 14643 * This function is called whenever the state of the view changes in such 14644 * a way that it impacts the state of drawables being shown. 14645 * 14646 * <p>Be sure to call through to the superclass when overriding this 14647 * function. 14648 * 14649 * @see Drawable#setState(int[]) 14650 */ 14651 protected void drawableStateChanged() { 14652 Drawable d = mBackground; 14653 if (d != null && d.isStateful()) { 14654 d.setState(getDrawableState()); 14655 } 14656 } 14657 14658 /** 14659 * Call this to force a view to update its drawable state. This will cause 14660 * drawableStateChanged to be called on this view. Views that are interested 14661 * in the new state should call getDrawableState. 14662 * 14663 * @see #drawableStateChanged 14664 * @see #getDrawableState 14665 */ 14666 public void refreshDrawableState() { 14667 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 14668 drawableStateChanged(); 14669 14670 ViewParent parent = mParent; 14671 if (parent != null) { 14672 parent.childDrawableStateChanged(this); 14673 } 14674 } 14675 14676 /** 14677 * Return an array of resource IDs of the drawable states representing the 14678 * current state of the view. 14679 * 14680 * @return The current drawable state 14681 * 14682 * @see Drawable#setState(int[]) 14683 * @see #drawableStateChanged() 14684 * @see #onCreateDrawableState(int) 14685 */ 14686 public final int[] getDrawableState() { 14687 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 14688 return mDrawableState; 14689 } else { 14690 mDrawableState = onCreateDrawableState(0); 14691 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 14692 return mDrawableState; 14693 } 14694 } 14695 14696 /** 14697 * Generate the new {@link android.graphics.drawable.Drawable} state for 14698 * this view. This is called by the view 14699 * system when the cached Drawable state is determined to be invalid. To 14700 * retrieve the current state, you should use {@link #getDrawableState}. 14701 * 14702 * @param extraSpace if non-zero, this is the number of extra entries you 14703 * would like in the returned array in which you can place your own 14704 * states. 14705 * 14706 * @return Returns an array holding the current {@link Drawable} state of 14707 * the view. 14708 * 14709 * @see #mergeDrawableStates(int[], int[]) 14710 */ 14711 protected int[] onCreateDrawableState(int extraSpace) { 14712 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 14713 mParent instanceof View) { 14714 return ((View) mParent).onCreateDrawableState(extraSpace); 14715 } 14716 14717 int[] drawableState; 14718 14719 int privateFlags = mPrivateFlags; 14720 14721 int viewStateIndex = 0; 14722 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 14723 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 14724 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 14725 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 14726 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 14727 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 14728 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 14729 HardwareRenderer.isAvailable()) { 14730 // This is set if HW acceleration is requested, even if the current 14731 // process doesn't allow it. This is just to allow app preview 14732 // windows to better match their app. 14733 viewStateIndex |= VIEW_STATE_ACCELERATED; 14734 } 14735 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 14736 14737 final int privateFlags2 = mPrivateFlags2; 14738 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 14739 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 14740 14741 drawableState = VIEW_STATE_SETS[viewStateIndex]; 14742 14743 //noinspection ConstantIfStatement 14744 if (false) { 14745 Log.i("View", "drawableStateIndex=" + viewStateIndex); 14746 Log.i("View", toString() 14747 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 14748 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 14749 + " fo=" + hasFocus() 14750 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 14751 + " wf=" + hasWindowFocus() 14752 + ": " + Arrays.toString(drawableState)); 14753 } 14754 14755 if (extraSpace == 0) { 14756 return drawableState; 14757 } 14758 14759 final int[] fullState; 14760 if (drawableState != null) { 14761 fullState = new int[drawableState.length + extraSpace]; 14762 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 14763 } else { 14764 fullState = new int[extraSpace]; 14765 } 14766 14767 return fullState; 14768 } 14769 14770 /** 14771 * Merge your own state values in <var>additionalState</var> into the base 14772 * state values <var>baseState</var> that were returned by 14773 * {@link #onCreateDrawableState(int)}. 14774 * 14775 * @param baseState The base state values returned by 14776 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 14777 * own additional state values. 14778 * 14779 * @param additionalState The additional state values you would like 14780 * added to <var>baseState</var>; this array is not modified. 14781 * 14782 * @return As a convenience, the <var>baseState</var> array you originally 14783 * passed into the function is returned. 14784 * 14785 * @see #onCreateDrawableState(int) 14786 */ 14787 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 14788 final int N = baseState.length; 14789 int i = N - 1; 14790 while (i >= 0 && baseState[i] == 0) { 14791 i--; 14792 } 14793 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 14794 return baseState; 14795 } 14796 14797 /** 14798 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 14799 * on all Drawable objects associated with this view. 14800 */ 14801 public void jumpDrawablesToCurrentState() { 14802 if (mBackground != null) { 14803 mBackground.jumpToCurrentState(); 14804 } 14805 } 14806 14807 /** 14808 * Sets the background color for this view. 14809 * @param color the color of the background 14810 */ 14811 @RemotableViewMethod 14812 public void setBackgroundColor(int color) { 14813 if (mBackground instanceof ColorDrawable) { 14814 ((ColorDrawable) mBackground.mutate()).setColor(color); 14815 computeOpaqueFlags(); 14816 mBackgroundResource = 0; 14817 } else { 14818 setBackground(new ColorDrawable(color)); 14819 } 14820 } 14821 14822 /** 14823 * Set the background to a given resource. The resource should refer to 14824 * a Drawable object or 0 to remove the background. 14825 * @param resid The identifier of the resource. 14826 * 14827 * @attr ref android.R.styleable#View_background 14828 */ 14829 @RemotableViewMethod 14830 public void setBackgroundResource(int resid) { 14831 if (resid != 0 && resid == mBackgroundResource) { 14832 return; 14833 } 14834 14835 Drawable d= null; 14836 if (resid != 0) { 14837 d = mResources.getDrawable(resid); 14838 } 14839 setBackground(d); 14840 14841 mBackgroundResource = resid; 14842 } 14843 14844 /** 14845 * Set the background to a given Drawable, or remove the background. If the 14846 * background has padding, this View's padding is set to the background's 14847 * padding. However, when a background is removed, this View's padding isn't 14848 * touched. If setting the padding is desired, please use 14849 * {@link #setPadding(int, int, int, int)}. 14850 * 14851 * @param background The Drawable to use as the background, or null to remove the 14852 * background 14853 */ 14854 public void setBackground(Drawable background) { 14855 //noinspection deprecation 14856 setBackgroundDrawable(background); 14857 } 14858 14859 /** 14860 * @deprecated use {@link #setBackground(Drawable)} instead 14861 */ 14862 @Deprecated 14863 public void setBackgroundDrawable(Drawable background) { 14864 computeOpaqueFlags(); 14865 14866 if (background == mBackground) { 14867 return; 14868 } 14869 14870 boolean requestLayout = false; 14871 14872 mBackgroundResource = 0; 14873 14874 /* 14875 * Regardless of whether we're setting a new background or not, we want 14876 * to clear the previous drawable. 14877 */ 14878 if (mBackground != null) { 14879 mBackground.setCallback(null); 14880 unscheduleDrawable(mBackground); 14881 } 14882 14883 if (background != null) { 14884 Rect padding = sThreadLocal.get(); 14885 if (padding == null) { 14886 padding = new Rect(); 14887 sThreadLocal.set(padding); 14888 } 14889 resetResolvedDrawables(); 14890 background.setLayoutDirection(getLayoutDirection()); 14891 if (background.getPadding(padding)) { 14892 resetResolvedPadding(); 14893 switch (background.getLayoutDirection()) { 14894 case LAYOUT_DIRECTION_RTL: 14895 mUserPaddingLeftInitial = padding.right; 14896 mUserPaddingRightInitial = padding.left; 14897 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 14898 break; 14899 case LAYOUT_DIRECTION_LTR: 14900 default: 14901 mUserPaddingLeftInitial = padding.left; 14902 mUserPaddingRightInitial = padding.right; 14903 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 14904 } 14905 } 14906 14907 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 14908 // if it has a different minimum size, we should layout again 14909 if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() || 14910 mBackground.getMinimumWidth() != background.getMinimumWidth()) { 14911 requestLayout = true; 14912 } 14913 14914 background.setCallback(this); 14915 if (background.isStateful()) { 14916 background.setState(getDrawableState()); 14917 } 14918 background.setVisible(getVisibility() == VISIBLE, false); 14919 mBackground = background; 14920 14921 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 14922 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 14923 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 14924 requestLayout = true; 14925 } 14926 } else { 14927 /* Remove the background */ 14928 mBackground = null; 14929 14930 if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) { 14931 /* 14932 * This view ONLY drew the background before and we're removing 14933 * the background, so now it won't draw anything 14934 * (hence we SKIP_DRAW) 14935 */ 14936 mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND; 14937 mPrivateFlags |= PFLAG_SKIP_DRAW; 14938 } 14939 14940 /* 14941 * When the background is set, we try to apply its padding to this 14942 * View. When the background is removed, we don't touch this View's 14943 * padding. This is noted in the Javadocs. Hence, we don't need to 14944 * requestLayout(), the invalidate() below is sufficient. 14945 */ 14946 14947 // The old background's minimum size could have affected this 14948 // View's layout, so let's requestLayout 14949 requestLayout = true; 14950 } 14951 14952 computeOpaqueFlags(); 14953 14954 if (requestLayout) { 14955 requestLayout(); 14956 } 14957 14958 mBackgroundSizeChanged = true; 14959 invalidate(true); 14960 } 14961 14962 /** 14963 * Gets the background drawable 14964 * 14965 * @return The drawable used as the background for this view, if any. 14966 * 14967 * @see #setBackground(Drawable) 14968 * 14969 * @attr ref android.R.styleable#View_background 14970 */ 14971 public Drawable getBackground() { 14972 return mBackground; 14973 } 14974 14975 /** 14976 * Sets the padding. The view may add on the space required to display 14977 * the scrollbars, depending on the style and visibility of the scrollbars. 14978 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 14979 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 14980 * from the values set in this call. 14981 * 14982 * @attr ref android.R.styleable#View_padding 14983 * @attr ref android.R.styleable#View_paddingBottom 14984 * @attr ref android.R.styleable#View_paddingLeft 14985 * @attr ref android.R.styleable#View_paddingRight 14986 * @attr ref android.R.styleable#View_paddingTop 14987 * @param left the left padding in pixels 14988 * @param top the top padding in pixels 14989 * @param right the right padding in pixels 14990 * @param bottom the bottom padding in pixels 14991 */ 14992 public void setPadding(int left, int top, int right, int bottom) { 14993 resetResolvedPadding(); 14994 14995 mUserPaddingStart = UNDEFINED_PADDING; 14996 mUserPaddingEnd = UNDEFINED_PADDING; 14997 14998 mUserPaddingLeftInitial = left; 14999 mUserPaddingRightInitial = right; 15000 15001 internalSetPadding(left, top, right, bottom); 15002 } 15003 15004 /** 15005 * @hide 15006 */ 15007 protected void internalSetPadding(int left, int top, int right, int bottom) { 15008 mUserPaddingLeft = left; 15009 mUserPaddingRight = right; 15010 mUserPaddingBottom = bottom; 15011 15012 final int viewFlags = mViewFlags; 15013 boolean changed = false; 15014 15015 // Common case is there are no scroll bars. 15016 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 15017 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 15018 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 15019 ? 0 : getVerticalScrollbarWidth(); 15020 switch (mVerticalScrollbarPosition) { 15021 case SCROLLBAR_POSITION_DEFAULT: 15022 if (isLayoutRtl()) { 15023 left += offset; 15024 } else { 15025 right += offset; 15026 } 15027 break; 15028 case SCROLLBAR_POSITION_RIGHT: 15029 right += offset; 15030 break; 15031 case SCROLLBAR_POSITION_LEFT: 15032 left += offset; 15033 break; 15034 } 15035 } 15036 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 15037 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 15038 ? 0 : getHorizontalScrollbarHeight(); 15039 } 15040 } 15041 15042 if (mPaddingLeft != left) { 15043 changed = true; 15044 mPaddingLeft = left; 15045 } 15046 if (mPaddingTop != top) { 15047 changed = true; 15048 mPaddingTop = top; 15049 } 15050 if (mPaddingRight != right) { 15051 changed = true; 15052 mPaddingRight = right; 15053 } 15054 if (mPaddingBottom != bottom) { 15055 changed = true; 15056 mPaddingBottom = bottom; 15057 } 15058 15059 if (changed) { 15060 requestLayout(); 15061 } 15062 } 15063 15064 /** 15065 * Sets the relative padding. The view may add on the space required to display 15066 * the scrollbars, depending on the style and visibility of the scrollbars. 15067 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 15068 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 15069 * from the values set in this call. 15070 * 15071 * @attr ref android.R.styleable#View_padding 15072 * @attr ref android.R.styleable#View_paddingBottom 15073 * @attr ref android.R.styleable#View_paddingStart 15074 * @attr ref android.R.styleable#View_paddingEnd 15075 * @attr ref android.R.styleable#View_paddingTop 15076 * @param start the start padding in pixels 15077 * @param top the top padding in pixels 15078 * @param end the end padding in pixels 15079 * @param bottom the bottom padding in pixels 15080 */ 15081 public void setPaddingRelative(int start, int top, int end, int bottom) { 15082 resetResolvedPadding(); 15083 15084 mUserPaddingStart = start; 15085 mUserPaddingEnd = end; 15086 15087 switch(getLayoutDirection()) { 15088 case LAYOUT_DIRECTION_RTL: 15089 mUserPaddingLeftInitial = end; 15090 mUserPaddingRightInitial = start; 15091 internalSetPadding(end, top, start, bottom); 15092 break; 15093 case LAYOUT_DIRECTION_LTR: 15094 default: 15095 mUserPaddingLeftInitial = start; 15096 mUserPaddingRightInitial = end; 15097 internalSetPadding(start, top, end, bottom); 15098 } 15099 } 15100 15101 /** 15102 * Returns the top padding of this view. 15103 * 15104 * @return the top padding in pixels 15105 */ 15106 public int getPaddingTop() { 15107 return mPaddingTop; 15108 } 15109 15110 /** 15111 * Returns the bottom padding of this view. If there are inset and enabled 15112 * scrollbars, this value may include the space required to display the 15113 * scrollbars as well. 15114 * 15115 * @return the bottom padding in pixels 15116 */ 15117 public int getPaddingBottom() { 15118 return mPaddingBottom; 15119 } 15120 15121 /** 15122 * Returns the left padding of this view. If there are inset and enabled 15123 * scrollbars, this value may include the space required to display the 15124 * scrollbars as well. 15125 * 15126 * @return the left padding in pixels 15127 */ 15128 public int getPaddingLeft() { 15129 if (!isPaddingResolved()) { 15130 resolvePadding(); 15131 } 15132 return mPaddingLeft; 15133 } 15134 15135 /** 15136 * Returns the start padding of this view depending on its resolved layout direction. 15137 * If there are inset and enabled scrollbars, this value may include the space 15138 * required to display the scrollbars as well. 15139 * 15140 * @return the start padding in pixels 15141 */ 15142 public int getPaddingStart() { 15143 if (!isPaddingResolved()) { 15144 resolvePadding(); 15145 } 15146 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 15147 mPaddingRight : mPaddingLeft; 15148 } 15149 15150 /** 15151 * Returns the right padding of this view. If there are inset and enabled 15152 * scrollbars, this value may include the space required to display the 15153 * scrollbars as well. 15154 * 15155 * @return the right padding in pixels 15156 */ 15157 public int getPaddingRight() { 15158 if (!isPaddingResolved()) { 15159 resolvePadding(); 15160 } 15161 return mPaddingRight; 15162 } 15163 15164 /** 15165 * Returns the end padding of this view depending on its resolved layout direction. 15166 * If there are inset and enabled scrollbars, this value may include the space 15167 * required to display the scrollbars as well. 15168 * 15169 * @return the end padding in pixels 15170 */ 15171 public int getPaddingEnd() { 15172 if (!isPaddingResolved()) { 15173 resolvePadding(); 15174 } 15175 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 15176 mPaddingLeft : mPaddingRight; 15177 } 15178 15179 /** 15180 * Return if the padding as been set thru relative values 15181 * {@link #setPaddingRelative(int, int, int, int)} or thru 15182 * @attr ref android.R.styleable#View_paddingStart or 15183 * @attr ref android.R.styleable#View_paddingEnd 15184 * 15185 * @return true if the padding is relative or false if it is not. 15186 */ 15187 public boolean isPaddingRelative() { 15188 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 15189 } 15190 15191 Insets computeOpticalInsets() { 15192 return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets(); 15193 } 15194 15195 /** 15196 * @hide 15197 */ 15198 public void resetPaddingToInitialValues() { 15199 if (isRtlCompatibilityMode()) { 15200 mPaddingLeft = mUserPaddingLeftInitial; 15201 mPaddingRight = mUserPaddingRightInitial; 15202 return; 15203 } 15204 if (isLayoutRtl()) { 15205 mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial; 15206 mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial; 15207 } else { 15208 mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial; 15209 mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial; 15210 } 15211 } 15212 15213 /** 15214 * @hide 15215 */ 15216 public Insets getOpticalInsets() { 15217 if (mLayoutInsets == null) { 15218 mLayoutInsets = computeOpticalInsets(); 15219 } 15220 return mLayoutInsets; 15221 } 15222 15223 /** 15224 * Changes the selection state of this view. A view can be selected or not. 15225 * Note that selection is not the same as focus. Views are typically 15226 * selected in the context of an AdapterView like ListView or GridView; 15227 * the selected view is the view that is highlighted. 15228 * 15229 * @param selected true if the view must be selected, false otherwise 15230 */ 15231 public void setSelected(boolean selected) { 15232 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 15233 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 15234 if (!selected) resetPressedState(); 15235 invalidate(true); 15236 refreshDrawableState(); 15237 dispatchSetSelected(selected); 15238 notifyViewAccessibilityStateChangedIfNeeded(); 15239 } 15240 } 15241 15242 /** 15243 * Dispatch setSelected to all of this View's children. 15244 * 15245 * @see #setSelected(boolean) 15246 * 15247 * @param selected The new selected state 15248 */ 15249 protected void dispatchSetSelected(boolean selected) { 15250 } 15251 15252 /** 15253 * Indicates the selection state of this view. 15254 * 15255 * @return true if the view is selected, false otherwise 15256 */ 15257 @ViewDebug.ExportedProperty 15258 public boolean isSelected() { 15259 return (mPrivateFlags & PFLAG_SELECTED) != 0; 15260 } 15261 15262 /** 15263 * Changes the activated state of this view. A view can be activated or not. 15264 * Note that activation is not the same as selection. Selection is 15265 * a transient property, representing the view (hierarchy) the user is 15266 * currently interacting with. Activation is a longer-term state that the 15267 * user can move views in and out of. For example, in a list view with 15268 * single or multiple selection enabled, the views in the current selection 15269 * set are activated. (Um, yeah, we are deeply sorry about the terminology 15270 * here.) The activated state is propagated down to children of the view it 15271 * is set on. 15272 * 15273 * @param activated true if the view must be activated, false otherwise 15274 */ 15275 public void setActivated(boolean activated) { 15276 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 15277 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 15278 invalidate(true); 15279 refreshDrawableState(); 15280 dispatchSetActivated(activated); 15281 } 15282 } 15283 15284 /** 15285 * Dispatch setActivated to all of this View's children. 15286 * 15287 * @see #setActivated(boolean) 15288 * 15289 * @param activated The new activated state 15290 */ 15291 protected void dispatchSetActivated(boolean activated) { 15292 } 15293 15294 /** 15295 * Indicates the activation state of this view. 15296 * 15297 * @return true if the view is activated, false otherwise 15298 */ 15299 @ViewDebug.ExportedProperty 15300 public boolean isActivated() { 15301 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 15302 } 15303 15304 /** 15305 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 15306 * observer can be used to get notifications when global events, like 15307 * layout, happen. 15308 * 15309 * The returned ViewTreeObserver observer is not guaranteed to remain 15310 * valid for the lifetime of this View. If the caller of this method keeps 15311 * a long-lived reference to ViewTreeObserver, it should always check for 15312 * the return value of {@link ViewTreeObserver#isAlive()}. 15313 * 15314 * @return The ViewTreeObserver for this view's hierarchy. 15315 */ 15316 public ViewTreeObserver getViewTreeObserver() { 15317 if (mAttachInfo != null) { 15318 return mAttachInfo.mTreeObserver; 15319 } 15320 if (mFloatingTreeObserver == null) { 15321 mFloatingTreeObserver = new ViewTreeObserver(); 15322 } 15323 return mFloatingTreeObserver; 15324 } 15325 15326 /** 15327 * <p>Finds the topmost view in the current view hierarchy.</p> 15328 * 15329 * @return the topmost view containing this view 15330 */ 15331 public View getRootView() { 15332 if (mAttachInfo != null) { 15333 final View v = mAttachInfo.mRootView; 15334 if (v != null) { 15335 return v; 15336 } 15337 } 15338 15339 View parent = this; 15340 15341 while (parent.mParent != null && parent.mParent instanceof View) { 15342 parent = (View) parent.mParent; 15343 } 15344 15345 return parent; 15346 } 15347 15348 /** 15349 * <p>Computes the coordinates of this view on the screen. The argument 15350 * must be an array of two integers. After the method returns, the array 15351 * contains the x and y location in that order.</p> 15352 * 15353 * @param location an array of two integers in which to hold the coordinates 15354 */ 15355 public void getLocationOnScreen(int[] location) { 15356 getLocationInWindow(location); 15357 15358 final AttachInfo info = mAttachInfo; 15359 if (info != null) { 15360 location[0] += info.mWindowLeft; 15361 location[1] += info.mWindowTop; 15362 } 15363 } 15364 15365 /** 15366 * <p>Computes the coordinates of this view in its window. The argument 15367 * must be an array of two integers. After the method returns, the array 15368 * contains the x and y location in that order.</p> 15369 * 15370 * @param location an array of two integers in which to hold the coordinates 15371 */ 15372 public void getLocationInWindow(int[] location) { 15373 if (location == null || location.length < 2) { 15374 throw new IllegalArgumentException("location must be an array of two integers"); 15375 } 15376 15377 if (mAttachInfo == null) { 15378 // When the view is not attached to a window, this method does not make sense 15379 location[0] = location[1] = 0; 15380 return; 15381 } 15382 15383 float[] position = mAttachInfo.mTmpTransformLocation; 15384 position[0] = position[1] = 0.0f; 15385 15386 if (!hasIdentityMatrix()) { 15387 getMatrix().mapPoints(position); 15388 } 15389 15390 position[0] += mLeft; 15391 position[1] += mTop; 15392 15393 ViewParent viewParent = mParent; 15394 while (viewParent instanceof View) { 15395 final View view = (View) viewParent; 15396 15397 position[0] -= view.mScrollX; 15398 position[1] -= view.mScrollY; 15399 15400 if (!view.hasIdentityMatrix()) { 15401 view.getMatrix().mapPoints(position); 15402 } 15403 15404 position[0] += view.mLeft; 15405 position[1] += view.mTop; 15406 15407 viewParent = view.mParent; 15408 } 15409 15410 if (viewParent instanceof ViewRootImpl) { 15411 // *cough* 15412 final ViewRootImpl vr = (ViewRootImpl) viewParent; 15413 position[1] -= vr.mCurScrollY; 15414 } 15415 15416 location[0] = (int) (position[0] + 0.5f); 15417 location[1] = (int) (position[1] + 0.5f); 15418 } 15419 15420 /** 15421 * {@hide} 15422 * @param id the id of the view to be found 15423 * @return the view of the specified id, null if cannot be found 15424 */ 15425 protected View findViewTraversal(int id) { 15426 if (id == mID) { 15427 return this; 15428 } 15429 return null; 15430 } 15431 15432 /** 15433 * {@hide} 15434 * @param tag the tag of the view to be found 15435 * @return the view of specified tag, null if cannot be found 15436 */ 15437 protected View findViewWithTagTraversal(Object tag) { 15438 if (tag != null && tag.equals(mTag)) { 15439 return this; 15440 } 15441 return null; 15442 } 15443 15444 /** 15445 * {@hide} 15446 * @param predicate The predicate to evaluate. 15447 * @param childToSkip If not null, ignores this child during the recursive traversal. 15448 * @return The first view that matches the predicate or null. 15449 */ 15450 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 15451 if (predicate.apply(this)) { 15452 return this; 15453 } 15454 return null; 15455 } 15456 15457 /** 15458 * Look for a child view with the given id. If this view has the given 15459 * id, return this view. 15460 * 15461 * @param id The id to search for. 15462 * @return The view that has the given id in the hierarchy or null 15463 */ 15464 public final View findViewById(int id) { 15465 if (id < 0) { 15466 return null; 15467 } 15468 return findViewTraversal(id); 15469 } 15470 15471 /** 15472 * Finds a view by its unuque and stable accessibility id. 15473 * 15474 * @param accessibilityId The searched accessibility id. 15475 * @return The found view. 15476 */ 15477 final View findViewByAccessibilityId(int accessibilityId) { 15478 if (accessibilityId < 0) { 15479 return null; 15480 } 15481 return findViewByAccessibilityIdTraversal(accessibilityId); 15482 } 15483 15484 /** 15485 * Performs the traversal to find a view by its unuque and stable accessibility id. 15486 * 15487 * <strong>Note:</strong>This method does not stop at the root namespace 15488 * boundary since the user can touch the screen at an arbitrary location 15489 * potentially crossing the root namespace bounday which will send an 15490 * accessibility event to accessibility services and they should be able 15491 * to obtain the event source. Also accessibility ids are guaranteed to be 15492 * unique in the window. 15493 * 15494 * @param accessibilityId The accessibility id. 15495 * @return The found view. 15496 * 15497 * @hide 15498 */ 15499 public View findViewByAccessibilityIdTraversal(int accessibilityId) { 15500 if (getAccessibilityViewId() == accessibilityId) { 15501 return this; 15502 } 15503 return null; 15504 } 15505 15506 /** 15507 * Look for a child view with the given tag. If this view has the given 15508 * tag, return this view. 15509 * 15510 * @param tag The tag to search for, using "tag.equals(getTag())". 15511 * @return The View that has the given tag in the hierarchy or null 15512 */ 15513 public final View findViewWithTag(Object tag) { 15514 if (tag == null) { 15515 return null; 15516 } 15517 return findViewWithTagTraversal(tag); 15518 } 15519 15520 /** 15521 * {@hide} 15522 * Look for a child view that matches the specified predicate. 15523 * If this view matches the predicate, return this view. 15524 * 15525 * @param predicate The predicate to evaluate. 15526 * @return The first view that matches the predicate or null. 15527 */ 15528 public final View findViewByPredicate(Predicate<View> predicate) { 15529 return findViewByPredicateTraversal(predicate, null); 15530 } 15531 15532 /** 15533 * {@hide} 15534 * Look for a child view that matches the specified predicate, 15535 * starting with the specified view and its descendents and then 15536 * recusively searching the ancestors and siblings of that view 15537 * until this view is reached. 15538 * 15539 * This method is useful in cases where the predicate does not match 15540 * a single unique view (perhaps multiple views use the same id) 15541 * and we are trying to find the view that is "closest" in scope to the 15542 * starting view. 15543 * 15544 * @param start The view to start from. 15545 * @param predicate The predicate to evaluate. 15546 * @return The first view that matches the predicate or null. 15547 */ 15548 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 15549 View childToSkip = null; 15550 for (;;) { 15551 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 15552 if (view != null || start == this) { 15553 return view; 15554 } 15555 15556 ViewParent parent = start.getParent(); 15557 if (parent == null || !(parent instanceof View)) { 15558 return null; 15559 } 15560 15561 childToSkip = start; 15562 start = (View) parent; 15563 } 15564 } 15565 15566 /** 15567 * Sets the identifier for this view. The identifier does not have to be 15568 * unique in this view's hierarchy. The identifier should be a positive 15569 * number. 15570 * 15571 * @see #NO_ID 15572 * @see #getId() 15573 * @see #findViewById(int) 15574 * 15575 * @param id a number used to identify the view 15576 * 15577 * @attr ref android.R.styleable#View_id 15578 */ 15579 public void setId(int id) { 15580 mID = id; 15581 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 15582 mID = generateViewId(); 15583 } 15584 } 15585 15586 /** 15587 * {@hide} 15588 * 15589 * @param isRoot true if the view belongs to the root namespace, false 15590 * otherwise 15591 */ 15592 public void setIsRootNamespace(boolean isRoot) { 15593 if (isRoot) { 15594 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 15595 } else { 15596 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 15597 } 15598 } 15599 15600 /** 15601 * {@hide} 15602 * 15603 * @return true if the view belongs to the root namespace, false otherwise 15604 */ 15605 public boolean isRootNamespace() { 15606 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 15607 } 15608 15609 /** 15610 * Returns this view's identifier. 15611 * 15612 * @return a positive integer used to identify the view or {@link #NO_ID} 15613 * if the view has no ID 15614 * 15615 * @see #setId(int) 15616 * @see #findViewById(int) 15617 * @attr ref android.R.styleable#View_id 15618 */ 15619 @ViewDebug.CapturedViewProperty 15620 public int getId() { 15621 return mID; 15622 } 15623 15624 /** 15625 * Returns this view's tag. 15626 * 15627 * @return the Object stored in this view as a tag 15628 * 15629 * @see #setTag(Object) 15630 * @see #getTag(int) 15631 */ 15632 @ViewDebug.ExportedProperty 15633 public Object getTag() { 15634 return mTag; 15635 } 15636 15637 /** 15638 * Sets the tag associated with this view. A tag can be used to mark 15639 * a view in its hierarchy and does not have to be unique within the 15640 * hierarchy. Tags can also be used to store data within a view without 15641 * resorting to another data structure. 15642 * 15643 * @param tag an Object to tag the view with 15644 * 15645 * @see #getTag() 15646 * @see #setTag(int, Object) 15647 */ 15648 public void setTag(final Object tag) { 15649 mTag = tag; 15650 } 15651 15652 /** 15653 * Returns the tag associated with this view and the specified key. 15654 * 15655 * @param key The key identifying the tag 15656 * 15657 * @return the Object stored in this view as a tag 15658 * 15659 * @see #setTag(int, Object) 15660 * @see #getTag() 15661 */ 15662 public Object getTag(int key) { 15663 if (mKeyedTags != null) return mKeyedTags.get(key); 15664 return null; 15665 } 15666 15667 /** 15668 * Sets a tag associated with this view and a key. A tag can be used 15669 * to mark a view in its hierarchy and does not have to be unique within 15670 * the hierarchy. Tags can also be used to store data within a view 15671 * without resorting to another data structure. 15672 * 15673 * The specified key should be an id declared in the resources of the 15674 * application to ensure it is unique (see the <a 15675 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 15676 * Keys identified as belonging to 15677 * the Android framework or not associated with any package will cause 15678 * an {@link IllegalArgumentException} to be thrown. 15679 * 15680 * @param key The key identifying the tag 15681 * @param tag An Object to tag the view with 15682 * 15683 * @throws IllegalArgumentException If they specified key is not valid 15684 * 15685 * @see #setTag(Object) 15686 * @see #getTag(int) 15687 */ 15688 public void setTag(int key, final Object tag) { 15689 // If the package id is 0x00 or 0x01, it's either an undefined package 15690 // or a framework id 15691 if ((key >>> 24) < 2) { 15692 throw new IllegalArgumentException("The key must be an application-specific " 15693 + "resource id."); 15694 } 15695 15696 setKeyedTag(key, tag); 15697 } 15698 15699 /** 15700 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 15701 * framework id. 15702 * 15703 * @hide 15704 */ 15705 public void setTagInternal(int key, Object tag) { 15706 if ((key >>> 24) != 0x1) { 15707 throw new IllegalArgumentException("The key must be a framework-specific " 15708 + "resource id."); 15709 } 15710 15711 setKeyedTag(key, tag); 15712 } 15713 15714 private void setKeyedTag(int key, Object tag) { 15715 if (mKeyedTags == null) { 15716 mKeyedTags = new SparseArray<Object>(2); 15717 } 15718 15719 mKeyedTags.put(key, tag); 15720 } 15721 15722 /** 15723 * Prints information about this view in the log output, with the tag 15724 * {@link #VIEW_LOG_TAG}. 15725 * 15726 * @hide 15727 */ 15728 public void debug() { 15729 debug(0); 15730 } 15731 15732 /** 15733 * Prints information about this view in the log output, with the tag 15734 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 15735 * indentation defined by the <code>depth</code>. 15736 * 15737 * @param depth the indentation level 15738 * 15739 * @hide 15740 */ 15741 protected void debug(int depth) { 15742 String output = debugIndent(depth - 1); 15743 15744 output += "+ " + this; 15745 int id = getId(); 15746 if (id != -1) { 15747 output += " (id=" + id + ")"; 15748 } 15749 Object tag = getTag(); 15750 if (tag != null) { 15751 output += " (tag=" + tag + ")"; 15752 } 15753 Log.d(VIEW_LOG_TAG, output); 15754 15755 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 15756 output = debugIndent(depth) + " FOCUSED"; 15757 Log.d(VIEW_LOG_TAG, output); 15758 } 15759 15760 output = debugIndent(depth); 15761 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 15762 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 15763 + "} "; 15764 Log.d(VIEW_LOG_TAG, output); 15765 15766 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 15767 || mPaddingBottom != 0) { 15768 output = debugIndent(depth); 15769 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 15770 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 15771 Log.d(VIEW_LOG_TAG, output); 15772 } 15773 15774 output = debugIndent(depth); 15775 output += "mMeasureWidth=" + mMeasuredWidth + 15776 " mMeasureHeight=" + mMeasuredHeight; 15777 Log.d(VIEW_LOG_TAG, output); 15778 15779 output = debugIndent(depth); 15780 if (mLayoutParams == null) { 15781 output += "BAD! no layout params"; 15782 } else { 15783 output = mLayoutParams.debug(output); 15784 } 15785 Log.d(VIEW_LOG_TAG, output); 15786 15787 output = debugIndent(depth); 15788 output += "flags={"; 15789 output += View.printFlags(mViewFlags); 15790 output += "}"; 15791 Log.d(VIEW_LOG_TAG, output); 15792 15793 output = debugIndent(depth); 15794 output += "privateFlags={"; 15795 output += View.printPrivateFlags(mPrivateFlags); 15796 output += "}"; 15797 Log.d(VIEW_LOG_TAG, output); 15798 } 15799 15800 /** 15801 * Creates a string of whitespaces used for indentation. 15802 * 15803 * @param depth the indentation level 15804 * @return a String containing (depth * 2 + 3) * 2 white spaces 15805 * 15806 * @hide 15807 */ 15808 protected static String debugIndent(int depth) { 15809 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 15810 for (int i = 0; i < (depth * 2) + 3; i++) { 15811 spaces.append(' ').append(' '); 15812 } 15813 return spaces.toString(); 15814 } 15815 15816 /** 15817 * <p>Return the offset of the widget's text baseline from the widget's top 15818 * boundary. If this widget does not support baseline alignment, this 15819 * method returns -1. </p> 15820 * 15821 * @return the offset of the baseline within the widget's bounds or -1 15822 * if baseline alignment is not supported 15823 */ 15824 @ViewDebug.ExportedProperty(category = "layout") 15825 public int getBaseline() { 15826 return -1; 15827 } 15828 15829 /** 15830 * Returns whether the view hierarchy is currently undergoing a layout pass. This 15831 * information is useful to avoid situations such as calling {@link #requestLayout()} during 15832 * a layout pass. 15833 * 15834 * @return whether the view hierarchy is currently undergoing a layout pass 15835 */ 15836 public boolean isInLayout() { 15837 ViewRootImpl viewRoot = getViewRootImpl(); 15838 return (viewRoot != null && viewRoot.isInLayout()); 15839 } 15840 15841 /** 15842 * Call this when something has changed which has invalidated the 15843 * layout of this view. This will schedule a layout pass of the view 15844 * tree. This should not be called while the view hierarchy is currently in a layout 15845 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 15846 * end of the current layout pass (and then layout will run again) or after the current 15847 * frame is drawn and the next layout occurs. 15848 * 15849 * <p>Subclasses which override this method should call the superclass method to 15850 * handle possible request-during-layout errors correctly.</p> 15851 */ 15852 public void requestLayout() { 15853 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) { 15854 // Only trigger request-during-layout logic if this is the view requesting it, 15855 // not the views in its parent hierarchy 15856 ViewRootImpl viewRoot = getViewRootImpl(); 15857 if (viewRoot != null && viewRoot.isInLayout()) { 15858 if (!viewRoot.requestLayoutDuringLayout(this)) { 15859 return; 15860 } 15861 } 15862 mAttachInfo.mViewRequestingLayout = this; 15863 } 15864 15865 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 15866 mPrivateFlags |= PFLAG_INVALIDATED; 15867 15868 if (mParent != null && !mParent.isLayoutRequested()) { 15869 mParent.requestLayout(); 15870 } 15871 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) { 15872 mAttachInfo.mViewRequestingLayout = null; 15873 } 15874 } 15875 15876 /** 15877 * Forces this view to be laid out during the next layout pass. 15878 * This method does not call requestLayout() or forceLayout() 15879 * on the parent. 15880 */ 15881 public void forceLayout() { 15882 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 15883 mPrivateFlags |= PFLAG_INVALIDATED; 15884 } 15885 15886 /** 15887 * <p> 15888 * This is called to find out how big a view should be. The parent 15889 * supplies constraint information in the width and height parameters. 15890 * </p> 15891 * 15892 * <p> 15893 * The actual measurement work of a view is performed in 15894 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 15895 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 15896 * </p> 15897 * 15898 * 15899 * @param widthMeasureSpec Horizontal space requirements as imposed by the 15900 * parent 15901 * @param heightMeasureSpec Vertical space requirements as imposed by the 15902 * parent 15903 * 15904 * @see #onMeasure(int, int) 15905 */ 15906 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 15907 boolean optical = isLayoutModeOptical(this); 15908 if (optical != isLayoutModeOptical(mParent)) { 15909 Insets insets = getOpticalInsets(); 15910 int oWidth = insets.left + insets.right; 15911 int oHeight = insets.top + insets.bottom; 15912 widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth); 15913 heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight); 15914 } 15915 if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT || 15916 widthMeasureSpec != mOldWidthMeasureSpec || 15917 heightMeasureSpec != mOldHeightMeasureSpec) { 15918 15919 // first clears the measured dimension flag 15920 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 15921 15922 resolveRtlPropertiesIfNeeded(); 15923 15924 // measure ourselves, this should set the measured dimension flag back 15925 onMeasure(widthMeasureSpec, heightMeasureSpec); 15926 15927 // flag not set, setMeasuredDimension() was not invoked, we raise 15928 // an exception to warn the developer 15929 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 15930 throw new IllegalStateException("onMeasure() did not set the" 15931 + " measured dimension by calling" 15932 + " setMeasuredDimension()"); 15933 } 15934 15935 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 15936 } 15937 15938 mOldWidthMeasureSpec = widthMeasureSpec; 15939 mOldHeightMeasureSpec = heightMeasureSpec; 15940 } 15941 15942 /** 15943 * <p> 15944 * Measure the view and its content to determine the measured width and the 15945 * measured height. This method is invoked by {@link #measure(int, int)} and 15946 * should be overriden by subclasses to provide accurate and efficient 15947 * measurement of their contents. 15948 * </p> 15949 * 15950 * <p> 15951 * <strong>CONTRACT:</strong> When overriding this method, you 15952 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 15953 * measured width and height of this view. Failure to do so will trigger an 15954 * <code>IllegalStateException</code>, thrown by 15955 * {@link #measure(int, int)}. Calling the superclass' 15956 * {@link #onMeasure(int, int)} is a valid use. 15957 * </p> 15958 * 15959 * <p> 15960 * The base class implementation of measure defaults to the background size, 15961 * unless a larger size is allowed by the MeasureSpec. Subclasses should 15962 * override {@link #onMeasure(int, int)} to provide better measurements of 15963 * their content. 15964 * </p> 15965 * 15966 * <p> 15967 * If this method is overridden, it is the subclass's responsibility to make 15968 * sure the measured height and width are at least the view's minimum height 15969 * and width ({@link #getSuggestedMinimumHeight()} and 15970 * {@link #getSuggestedMinimumWidth()}). 15971 * </p> 15972 * 15973 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 15974 * The requirements are encoded with 15975 * {@link android.view.View.MeasureSpec}. 15976 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 15977 * The requirements are encoded with 15978 * {@link android.view.View.MeasureSpec}. 15979 * 15980 * @see #getMeasuredWidth() 15981 * @see #getMeasuredHeight() 15982 * @see #setMeasuredDimension(int, int) 15983 * @see #getSuggestedMinimumHeight() 15984 * @see #getSuggestedMinimumWidth() 15985 * @see android.view.View.MeasureSpec#getMode(int) 15986 * @see android.view.View.MeasureSpec#getSize(int) 15987 */ 15988 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 15989 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 15990 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 15991 } 15992 15993 /** 15994 * <p>This method must be called by {@link #onMeasure(int, int)} to store the 15995 * measured width and measured height. Failing to do so will trigger an 15996 * exception at measurement time.</p> 15997 * 15998 * @param measuredWidth The measured width of this view. May be a complex 15999 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 16000 * {@link #MEASURED_STATE_TOO_SMALL}. 16001 * @param measuredHeight The measured height of this view. May be a complex 16002 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 16003 * {@link #MEASURED_STATE_TOO_SMALL}. 16004 */ 16005 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 16006 boolean optical = isLayoutModeOptical(this); 16007 if (optical != isLayoutModeOptical(mParent)) { 16008 Insets insets = getOpticalInsets(); 16009 int opticalWidth = insets.left + insets.right; 16010 int opticalHeight = insets.top + insets.bottom; 16011 16012 measuredWidth += optical ? opticalWidth : -opticalWidth; 16013 measuredHeight += optical ? opticalHeight : -opticalHeight; 16014 } 16015 mMeasuredWidth = measuredWidth; 16016 mMeasuredHeight = measuredHeight; 16017 16018 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 16019 } 16020 16021 /** 16022 * Merge two states as returned by {@link #getMeasuredState()}. 16023 * @param curState The current state as returned from a view or the result 16024 * of combining multiple views. 16025 * @param newState The new view state to combine. 16026 * @return Returns a new integer reflecting the combination of the two 16027 * states. 16028 */ 16029 public static int combineMeasuredStates(int curState, int newState) { 16030 return curState | newState; 16031 } 16032 16033 /** 16034 * Version of {@link #resolveSizeAndState(int, int, int)} 16035 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 16036 */ 16037 public static int resolveSize(int size, int measureSpec) { 16038 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 16039 } 16040 16041 /** 16042 * Utility to reconcile a desired size and state, with constraints imposed 16043 * by a MeasureSpec. Will take the desired size, unless a different size 16044 * is imposed by the constraints. The returned value is a compound integer, 16045 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 16046 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 16047 * size is smaller than the size the view wants to be. 16048 * 16049 * @param size How big the view wants to be 16050 * @param measureSpec Constraints imposed by the parent 16051 * @return Size information bit mask as defined by 16052 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 16053 */ 16054 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 16055 int result = size; 16056 int specMode = MeasureSpec.getMode(measureSpec); 16057 int specSize = MeasureSpec.getSize(measureSpec); 16058 switch (specMode) { 16059 case MeasureSpec.UNSPECIFIED: 16060 result = size; 16061 break; 16062 case MeasureSpec.AT_MOST: 16063 if (specSize < size) { 16064 result = specSize | MEASURED_STATE_TOO_SMALL; 16065 } else { 16066 result = size; 16067 } 16068 break; 16069 case MeasureSpec.EXACTLY: 16070 result = specSize; 16071 break; 16072 } 16073 return result | (childMeasuredState&MEASURED_STATE_MASK); 16074 } 16075 16076 /** 16077 * Utility to return a default size. Uses the supplied size if the 16078 * MeasureSpec imposed no constraints. Will get larger if allowed 16079 * by the MeasureSpec. 16080 * 16081 * @param size Default size for this view 16082 * @param measureSpec Constraints imposed by the parent 16083 * @return The size this view should be. 16084 */ 16085 public static int getDefaultSize(int size, int measureSpec) { 16086 int result = size; 16087 int specMode = MeasureSpec.getMode(measureSpec); 16088 int specSize = MeasureSpec.getSize(measureSpec); 16089 16090 switch (specMode) { 16091 case MeasureSpec.UNSPECIFIED: 16092 result = size; 16093 break; 16094 case MeasureSpec.AT_MOST: 16095 case MeasureSpec.EXACTLY: 16096 result = specSize; 16097 break; 16098 } 16099 return result; 16100 } 16101 16102 /** 16103 * Returns the suggested minimum height that the view should use. This 16104 * returns the maximum of the view's minimum height 16105 * and the background's minimum height 16106 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 16107 * <p> 16108 * When being used in {@link #onMeasure(int, int)}, the caller should still 16109 * ensure the returned height is within the requirements of the parent. 16110 * 16111 * @return The suggested minimum height of the view. 16112 */ 16113 protected int getSuggestedMinimumHeight() { 16114 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 16115 16116 } 16117 16118 /** 16119 * Returns the suggested minimum width that the view should use. This 16120 * returns the maximum of the view's minimum width) 16121 * and the background's minimum width 16122 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 16123 * <p> 16124 * When being used in {@link #onMeasure(int, int)}, the caller should still 16125 * ensure the returned width is within the requirements of the parent. 16126 * 16127 * @return The suggested minimum width of the view. 16128 */ 16129 protected int getSuggestedMinimumWidth() { 16130 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 16131 } 16132 16133 /** 16134 * Returns the minimum height of the view. 16135 * 16136 * @return the minimum height the view will try to be. 16137 * 16138 * @see #setMinimumHeight(int) 16139 * 16140 * @attr ref android.R.styleable#View_minHeight 16141 */ 16142 public int getMinimumHeight() { 16143 return mMinHeight; 16144 } 16145 16146 /** 16147 * Sets the minimum height of the view. It is not guaranteed the view will 16148 * be able to achieve this minimum height (for example, if its parent layout 16149 * constrains it with less available height). 16150 * 16151 * @param minHeight The minimum height the view will try to be. 16152 * 16153 * @see #getMinimumHeight() 16154 * 16155 * @attr ref android.R.styleable#View_minHeight 16156 */ 16157 public void setMinimumHeight(int minHeight) { 16158 mMinHeight = minHeight; 16159 requestLayout(); 16160 } 16161 16162 /** 16163 * Returns the minimum width of the view. 16164 * 16165 * @return the minimum width the view will try to be. 16166 * 16167 * @see #setMinimumWidth(int) 16168 * 16169 * @attr ref android.R.styleable#View_minWidth 16170 */ 16171 public int getMinimumWidth() { 16172 return mMinWidth; 16173 } 16174 16175 /** 16176 * Sets the minimum width of the view. It is not guaranteed the view will 16177 * be able to achieve this minimum width (for example, if its parent layout 16178 * constrains it with less available width). 16179 * 16180 * @param minWidth The minimum width the view will try to be. 16181 * 16182 * @see #getMinimumWidth() 16183 * 16184 * @attr ref android.R.styleable#View_minWidth 16185 */ 16186 public void setMinimumWidth(int minWidth) { 16187 mMinWidth = minWidth; 16188 requestLayout(); 16189 16190 } 16191 16192 /** 16193 * Get the animation currently associated with this view. 16194 * 16195 * @return The animation that is currently playing or 16196 * scheduled to play for this view. 16197 */ 16198 public Animation getAnimation() { 16199 return mCurrentAnimation; 16200 } 16201 16202 /** 16203 * Start the specified animation now. 16204 * 16205 * @param animation the animation to start now 16206 */ 16207 public void startAnimation(Animation animation) { 16208 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 16209 setAnimation(animation); 16210 invalidateParentCaches(); 16211 invalidate(true); 16212 } 16213 16214 /** 16215 * Cancels any animations for this view. 16216 */ 16217 public void clearAnimation() { 16218 if (mCurrentAnimation != null) { 16219 mCurrentAnimation.detach(); 16220 } 16221 mCurrentAnimation = null; 16222 invalidateParentIfNeeded(); 16223 } 16224 16225 /** 16226 * Sets the next animation to play for this view. 16227 * If you want the animation to play immediately, use 16228 * {@link #startAnimation(android.view.animation.Animation)} instead. 16229 * This method provides allows fine-grained 16230 * control over the start time and invalidation, but you 16231 * must make sure that 1) the animation has a start time set, and 16232 * 2) the view's parent (which controls animations on its children) 16233 * will be invalidated when the animation is supposed to 16234 * start. 16235 * 16236 * @param animation The next animation, or null. 16237 */ 16238 public void setAnimation(Animation animation) { 16239 mCurrentAnimation = animation; 16240 16241 if (animation != null) { 16242 // If the screen is off assume the animation start time is now instead of 16243 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 16244 // would cause the animation to start when the screen turns back on 16245 if (mAttachInfo != null && !mAttachInfo.mScreenOn && 16246 animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 16247 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 16248 } 16249 animation.reset(); 16250 } 16251 } 16252 16253 /** 16254 * Invoked by a parent ViewGroup to notify the start of the animation 16255 * currently associated with this view. If you override this method, 16256 * always call super.onAnimationStart(); 16257 * 16258 * @see #setAnimation(android.view.animation.Animation) 16259 * @see #getAnimation() 16260 */ 16261 protected void onAnimationStart() { 16262 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 16263 } 16264 16265 /** 16266 * Invoked by a parent ViewGroup to notify the end of the animation 16267 * currently associated with this view. If you override this method, 16268 * always call super.onAnimationEnd(); 16269 * 16270 * @see #setAnimation(android.view.animation.Animation) 16271 * @see #getAnimation() 16272 */ 16273 protected void onAnimationEnd() { 16274 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 16275 } 16276 16277 /** 16278 * Invoked if there is a Transform that involves alpha. Subclass that can 16279 * draw themselves with the specified alpha should return true, and then 16280 * respect that alpha when their onDraw() is called. If this returns false 16281 * then the view may be redirected to draw into an offscreen buffer to 16282 * fulfill the request, which will look fine, but may be slower than if the 16283 * subclass handles it internally. The default implementation returns false. 16284 * 16285 * @param alpha The alpha (0..255) to apply to the view's drawing 16286 * @return true if the view can draw with the specified alpha. 16287 */ 16288 protected boolean onSetAlpha(int alpha) { 16289 return false; 16290 } 16291 16292 /** 16293 * This is used by the RootView to perform an optimization when 16294 * the view hierarchy contains one or several SurfaceView. 16295 * SurfaceView is always considered transparent, but its children are not, 16296 * therefore all View objects remove themselves from the global transparent 16297 * region (passed as a parameter to this function). 16298 * 16299 * @param region The transparent region for this ViewAncestor (window). 16300 * 16301 * @return Returns true if the effective visibility of the view at this 16302 * point is opaque, regardless of the transparent region; returns false 16303 * if it is possible for underlying windows to be seen behind the view. 16304 * 16305 * {@hide} 16306 */ 16307 public boolean gatherTransparentRegion(Region region) { 16308 final AttachInfo attachInfo = mAttachInfo; 16309 if (region != null && attachInfo != null) { 16310 final int pflags = mPrivateFlags; 16311 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 16312 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 16313 // remove it from the transparent region. 16314 final int[] location = attachInfo.mTransparentLocation; 16315 getLocationInWindow(location); 16316 region.op(location[0], location[1], location[0] + mRight - mLeft, 16317 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 16318 } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) { 16319 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 16320 // exists, so we remove the background drawable's non-transparent 16321 // parts from this transparent region. 16322 applyDrawableToTransparentRegion(mBackground, region); 16323 } 16324 } 16325 return true; 16326 } 16327 16328 /** 16329 * Play a sound effect for this view. 16330 * 16331 * <p>The framework will play sound effects for some built in actions, such as 16332 * clicking, but you may wish to play these effects in your widget, 16333 * for instance, for internal navigation. 16334 * 16335 * <p>The sound effect will only be played if sound effects are enabled by the user, and 16336 * {@link #isSoundEffectsEnabled()} is true. 16337 * 16338 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 16339 */ 16340 public void playSoundEffect(int soundConstant) { 16341 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 16342 return; 16343 } 16344 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 16345 } 16346 16347 /** 16348 * BZZZTT!!1! 16349 * 16350 * <p>Provide haptic feedback to the user for this view. 16351 * 16352 * <p>The framework will provide haptic feedback for some built in actions, 16353 * such as long presses, but you may wish to provide feedback for your 16354 * own widget. 16355 * 16356 * <p>The feedback will only be performed if 16357 * {@link #isHapticFeedbackEnabled()} is true. 16358 * 16359 * @param feedbackConstant One of the constants defined in 16360 * {@link HapticFeedbackConstants} 16361 */ 16362 public boolean performHapticFeedback(int feedbackConstant) { 16363 return performHapticFeedback(feedbackConstant, 0); 16364 } 16365 16366 /** 16367 * BZZZTT!!1! 16368 * 16369 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 16370 * 16371 * @param feedbackConstant One of the constants defined in 16372 * {@link HapticFeedbackConstants} 16373 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 16374 */ 16375 public boolean performHapticFeedback(int feedbackConstant, int flags) { 16376 if (mAttachInfo == null) { 16377 return false; 16378 } 16379 //noinspection SimplifiableIfStatement 16380 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 16381 && !isHapticFeedbackEnabled()) { 16382 return false; 16383 } 16384 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 16385 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 16386 } 16387 16388 /** 16389 * Request that the visibility of the status bar or other screen/window 16390 * decorations be changed. 16391 * 16392 * <p>This method is used to put the over device UI into temporary modes 16393 * where the user's attention is focused more on the application content, 16394 * by dimming or hiding surrounding system affordances. This is typically 16395 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 16396 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 16397 * to be placed behind the action bar (and with these flags other system 16398 * affordances) so that smooth transitions between hiding and showing them 16399 * can be done. 16400 * 16401 * <p>Two representative examples of the use of system UI visibility is 16402 * implementing a content browsing application (like a magazine reader) 16403 * and a video playing application. 16404 * 16405 * <p>The first code shows a typical implementation of a View in a content 16406 * browsing application. In this implementation, the application goes 16407 * into a content-oriented mode by hiding the status bar and action bar, 16408 * and putting the navigation elements into lights out mode. The user can 16409 * then interact with content while in this mode. Such an application should 16410 * provide an easy way for the user to toggle out of the mode (such as to 16411 * check information in the status bar or access notifications). In the 16412 * implementation here, this is done simply by tapping on the content. 16413 * 16414 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 16415 * content} 16416 * 16417 * <p>This second code sample shows a typical implementation of a View 16418 * in a video playing application. In this situation, while the video is 16419 * playing the application would like to go into a complete full-screen mode, 16420 * to use as much of the display as possible for the video. When in this state 16421 * the user can not interact with the application; the system intercepts 16422 * touching on the screen to pop the UI out of full screen mode. See 16423 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 16424 * 16425 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 16426 * content} 16427 * 16428 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 16429 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 16430 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 16431 * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}. 16432 */ 16433 public void setSystemUiVisibility(int visibility) { 16434 if (visibility != mSystemUiVisibility) { 16435 mSystemUiVisibility = visibility; 16436 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 16437 mParent.recomputeViewAttributes(this); 16438 } 16439 } 16440 } 16441 16442 /** 16443 * Returns the last {@link #setSystemUiVisibility(int) that this view has requested. 16444 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 16445 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 16446 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 16447 * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}. 16448 */ 16449 public int getSystemUiVisibility() { 16450 return mSystemUiVisibility; 16451 } 16452 16453 /** 16454 * Returns the current system UI visibility that is currently set for 16455 * the entire window. This is the combination of the 16456 * {@link #setSystemUiVisibility(int)} values supplied by all of the 16457 * views in the window. 16458 */ 16459 public int getWindowSystemUiVisibility() { 16460 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 16461 } 16462 16463 /** 16464 * Override to find out when the window's requested system UI visibility 16465 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 16466 * This is different from the callbacks recieved through 16467 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 16468 * in that this is only telling you about the local request of the window, 16469 * not the actual values applied by the system. 16470 */ 16471 public void onWindowSystemUiVisibilityChanged(int visible) { 16472 } 16473 16474 /** 16475 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 16476 * the view hierarchy. 16477 */ 16478 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 16479 onWindowSystemUiVisibilityChanged(visible); 16480 } 16481 16482 /** 16483 * Set a listener to receive callbacks when the visibility of the system bar changes. 16484 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 16485 */ 16486 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 16487 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 16488 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 16489 mParent.recomputeViewAttributes(this); 16490 } 16491 } 16492 16493 /** 16494 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 16495 * the view hierarchy. 16496 */ 16497 public void dispatchSystemUiVisibilityChanged(int visibility) { 16498 ListenerInfo li = mListenerInfo; 16499 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 16500 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 16501 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 16502 } 16503 } 16504 16505 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 16506 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 16507 if (val != mSystemUiVisibility) { 16508 setSystemUiVisibility(val); 16509 return true; 16510 } 16511 return false; 16512 } 16513 16514 /** @hide */ 16515 public void setDisabledSystemUiVisibility(int flags) { 16516 if (mAttachInfo != null) { 16517 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 16518 mAttachInfo.mDisabledSystemUiVisibility = flags; 16519 if (mParent != null) { 16520 mParent.recomputeViewAttributes(this); 16521 } 16522 } 16523 } 16524 } 16525 16526 /** 16527 * Creates an image that the system displays during the drag and drop 16528 * operation. This is called a "drag shadow". The default implementation 16529 * for a DragShadowBuilder based on a View returns an image that has exactly the same 16530 * appearance as the given View. The default also positions the center of the drag shadow 16531 * directly under the touch point. If no View is provided (the constructor with no parameters 16532 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 16533 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 16534 * default is an invisible drag shadow. 16535 * <p> 16536 * You are not required to use the View you provide to the constructor as the basis of the 16537 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 16538 * anything you want as the drag shadow. 16539 * </p> 16540 * <p> 16541 * You pass a DragShadowBuilder object to the system when you start the drag. The system 16542 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 16543 * size and position of the drag shadow. It uses this data to construct a 16544 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 16545 * so that your application can draw the shadow image in the Canvas. 16546 * </p> 16547 * 16548 * <div class="special reference"> 16549 * <h3>Developer Guides</h3> 16550 * <p>For a guide to implementing drag and drop features, read the 16551 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 16552 * </div> 16553 */ 16554 public static class DragShadowBuilder { 16555 private final WeakReference<View> mView; 16556 16557 /** 16558 * Constructs a shadow image builder based on a View. By default, the resulting drag 16559 * shadow will have the same appearance and dimensions as the View, with the touch point 16560 * over the center of the View. 16561 * @param view A View. Any View in scope can be used. 16562 */ 16563 public DragShadowBuilder(View view) { 16564 mView = new WeakReference<View>(view); 16565 } 16566 16567 /** 16568 * Construct a shadow builder object with no associated View. This 16569 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 16570 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 16571 * to supply the drag shadow's dimensions and appearance without 16572 * reference to any View object. If they are not overridden, then the result is an 16573 * invisible drag shadow. 16574 */ 16575 public DragShadowBuilder() { 16576 mView = new WeakReference<View>(null); 16577 } 16578 16579 /** 16580 * Returns the View object that had been passed to the 16581 * {@link #View.DragShadowBuilder(View)} 16582 * constructor. If that View parameter was {@code null} or if the 16583 * {@link #View.DragShadowBuilder()} 16584 * constructor was used to instantiate the builder object, this method will return 16585 * null. 16586 * 16587 * @return The View object associate with this builder object. 16588 */ 16589 @SuppressWarnings({"JavadocReference"}) 16590 final public View getView() { 16591 return mView.get(); 16592 } 16593 16594 /** 16595 * Provides the metrics for the shadow image. These include the dimensions of 16596 * the shadow image, and the point within that shadow that should 16597 * be centered under the touch location while dragging. 16598 * <p> 16599 * The default implementation sets the dimensions of the shadow to be the 16600 * same as the dimensions of the View itself and centers the shadow under 16601 * the touch point. 16602 * </p> 16603 * 16604 * @param shadowSize A {@link android.graphics.Point} containing the width and height 16605 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 16606 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 16607 * image. 16608 * 16609 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 16610 * shadow image that should be underneath the touch point during the drag and drop 16611 * operation. Your application must set {@link android.graphics.Point#x} to the 16612 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 16613 */ 16614 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 16615 final View view = mView.get(); 16616 if (view != null) { 16617 shadowSize.set(view.getWidth(), view.getHeight()); 16618 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 16619 } else { 16620 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 16621 } 16622 } 16623 16624 /** 16625 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 16626 * based on the dimensions it received from the 16627 * {@link #onProvideShadowMetrics(Point, Point)} callback. 16628 * 16629 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 16630 */ 16631 public void onDrawShadow(Canvas canvas) { 16632 final View view = mView.get(); 16633 if (view != null) { 16634 view.draw(canvas); 16635 } else { 16636 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 16637 } 16638 } 16639 } 16640 16641 /** 16642 * Starts a drag and drop operation. When your application calls this method, it passes a 16643 * {@link android.view.View.DragShadowBuilder} object to the system. The 16644 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 16645 * to get metrics for the drag shadow, and then calls the object's 16646 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 16647 * <p> 16648 * Once the system has the drag shadow, it begins the drag and drop operation by sending 16649 * drag events to all the View objects in your application that are currently visible. It does 16650 * this either by calling the View object's drag listener (an implementation of 16651 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 16652 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 16653 * Both are passed a {@link android.view.DragEvent} object that has a 16654 * {@link android.view.DragEvent#getAction()} value of 16655 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 16656 * </p> 16657 * <p> 16658 * Your application can invoke startDrag() on any attached View object. The View object does not 16659 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 16660 * be related to the View the user selected for dragging. 16661 * </p> 16662 * @param data A {@link android.content.ClipData} object pointing to the data to be 16663 * transferred by the drag and drop operation. 16664 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 16665 * drag shadow. 16666 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 16667 * drop operation. This Object is put into every DragEvent object sent by the system during the 16668 * current drag. 16669 * <p> 16670 * myLocalState is a lightweight mechanism for the sending information from the dragged View 16671 * to the target Views. For example, it can contain flags that differentiate between a 16672 * a copy operation and a move operation. 16673 * </p> 16674 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 16675 * so the parameter should be set to 0. 16676 * @return {@code true} if the method completes successfully, or 16677 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 16678 * do a drag, and so no drag operation is in progress. 16679 */ 16680 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 16681 Object myLocalState, int flags) { 16682 if (ViewDebug.DEBUG_DRAG) { 16683 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 16684 } 16685 boolean okay = false; 16686 16687 Point shadowSize = new Point(); 16688 Point shadowTouchPoint = new Point(); 16689 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 16690 16691 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 16692 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 16693 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 16694 } 16695 16696 if (ViewDebug.DEBUG_DRAG) { 16697 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 16698 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 16699 } 16700 Surface surface = new Surface(); 16701 try { 16702 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 16703 flags, shadowSize.x, shadowSize.y, surface); 16704 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 16705 + " surface=" + surface); 16706 if (token != null) { 16707 Canvas canvas = surface.lockCanvas(null); 16708 try { 16709 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 16710 shadowBuilder.onDrawShadow(canvas); 16711 } finally { 16712 surface.unlockCanvasAndPost(canvas); 16713 } 16714 16715 final ViewRootImpl root = getViewRootImpl(); 16716 16717 // Cache the local state object for delivery with DragEvents 16718 root.setLocalDragState(myLocalState); 16719 16720 // repurpose 'shadowSize' for the last touch point 16721 root.getLastTouchPoint(shadowSize); 16722 16723 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 16724 shadowSize.x, shadowSize.y, 16725 shadowTouchPoint.x, shadowTouchPoint.y, data); 16726 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 16727 16728 // Off and running! Release our local surface instance; the drag 16729 // shadow surface is now managed by the system process. 16730 surface.release(); 16731 } 16732 } catch (Exception e) { 16733 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 16734 surface.destroy(); 16735 } 16736 16737 return okay; 16738 } 16739 16740 /** 16741 * Handles drag events sent by the system following a call to 16742 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 16743 *<p> 16744 * When the system calls this method, it passes a 16745 * {@link android.view.DragEvent} object. A call to 16746 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 16747 * in DragEvent. The method uses these to determine what is happening in the drag and drop 16748 * operation. 16749 * @param event The {@link android.view.DragEvent} sent by the system. 16750 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 16751 * in DragEvent, indicating the type of drag event represented by this object. 16752 * @return {@code true} if the method was successful, otherwise {@code false}. 16753 * <p> 16754 * The method should return {@code true} in response to an action type of 16755 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 16756 * operation. 16757 * </p> 16758 * <p> 16759 * The method should also return {@code true} in response to an action type of 16760 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 16761 * {@code false} if it didn't. 16762 * </p> 16763 */ 16764 public boolean onDragEvent(DragEvent event) { 16765 return false; 16766 } 16767 16768 /** 16769 * Detects if this View is enabled and has a drag event listener. 16770 * If both are true, then it calls the drag event listener with the 16771 * {@link android.view.DragEvent} it received. If the drag event listener returns 16772 * {@code true}, then dispatchDragEvent() returns {@code true}. 16773 * <p> 16774 * For all other cases, the method calls the 16775 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 16776 * method and returns its result. 16777 * </p> 16778 * <p> 16779 * This ensures that a drag event is always consumed, even if the View does not have a drag 16780 * event listener. However, if the View has a listener and the listener returns true, then 16781 * onDragEvent() is not called. 16782 * </p> 16783 */ 16784 public boolean dispatchDragEvent(DragEvent event) { 16785 //noinspection SimplifiableIfStatement 16786 ListenerInfo li = mListenerInfo; 16787 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 16788 && li.mOnDragListener.onDrag(this, event)) { 16789 return true; 16790 } 16791 return onDragEvent(event); 16792 } 16793 16794 boolean canAcceptDrag() { 16795 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 16796 } 16797 16798 /** 16799 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 16800 * it is ever exposed at all. 16801 * @hide 16802 */ 16803 public void onCloseSystemDialogs(String reason) { 16804 } 16805 16806 /** 16807 * Given a Drawable whose bounds have been set to draw into this view, 16808 * update a Region being computed for 16809 * {@link #gatherTransparentRegion(android.graphics.Region)} so 16810 * that any non-transparent parts of the Drawable are removed from the 16811 * given transparent region. 16812 * 16813 * @param dr The Drawable whose transparency is to be applied to the region. 16814 * @param region A Region holding the current transparency information, 16815 * where any parts of the region that are set are considered to be 16816 * transparent. On return, this region will be modified to have the 16817 * transparency information reduced by the corresponding parts of the 16818 * Drawable that are not transparent. 16819 * {@hide} 16820 */ 16821 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 16822 if (DBG) { 16823 Log.i("View", "Getting transparent region for: " + this); 16824 } 16825 final Region r = dr.getTransparentRegion(); 16826 final Rect db = dr.getBounds(); 16827 final AttachInfo attachInfo = mAttachInfo; 16828 if (r != null && attachInfo != null) { 16829 final int w = getRight()-getLeft(); 16830 final int h = getBottom()-getTop(); 16831 if (db.left > 0) { 16832 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 16833 r.op(0, 0, db.left, h, Region.Op.UNION); 16834 } 16835 if (db.right < w) { 16836 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 16837 r.op(db.right, 0, w, h, Region.Op.UNION); 16838 } 16839 if (db.top > 0) { 16840 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 16841 r.op(0, 0, w, db.top, Region.Op.UNION); 16842 } 16843 if (db.bottom < h) { 16844 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 16845 r.op(0, db.bottom, w, h, Region.Op.UNION); 16846 } 16847 final int[] location = attachInfo.mTransparentLocation; 16848 getLocationInWindow(location); 16849 r.translate(location[0], location[1]); 16850 region.op(r, Region.Op.INTERSECT); 16851 } else { 16852 region.op(db, Region.Op.DIFFERENCE); 16853 } 16854 } 16855 16856 private void checkForLongClick(int delayOffset) { 16857 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 16858 mHasPerformedLongPress = false; 16859 16860 if (mPendingCheckForLongPress == null) { 16861 mPendingCheckForLongPress = new CheckForLongPress(); 16862 } 16863 mPendingCheckForLongPress.rememberWindowAttachCount(); 16864 postDelayed(mPendingCheckForLongPress, 16865 ViewConfiguration.getLongPressTimeout() - delayOffset); 16866 } 16867 } 16868 16869 /** 16870 * Inflate a view from an XML resource. This convenience method wraps the {@link 16871 * LayoutInflater} class, which provides a full range of options for view inflation. 16872 * 16873 * @param context The Context object for your activity or application. 16874 * @param resource The resource ID to inflate 16875 * @param root A view group that will be the parent. Used to properly inflate the 16876 * layout_* parameters. 16877 * @see LayoutInflater 16878 */ 16879 public static View inflate(Context context, int resource, ViewGroup root) { 16880 LayoutInflater factory = LayoutInflater.from(context); 16881 return factory.inflate(resource, root); 16882 } 16883 16884 /** 16885 * Scroll the view with standard behavior for scrolling beyond the normal 16886 * content boundaries. Views that call this method should override 16887 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 16888 * results of an over-scroll operation. 16889 * 16890 * Views can use this method to handle any touch or fling-based scrolling. 16891 * 16892 * @param deltaX Change in X in pixels 16893 * @param deltaY Change in Y in pixels 16894 * @param scrollX Current X scroll value in pixels before applying deltaX 16895 * @param scrollY Current Y scroll value in pixels before applying deltaY 16896 * @param scrollRangeX Maximum content scroll range along the X axis 16897 * @param scrollRangeY Maximum content scroll range along the Y axis 16898 * @param maxOverScrollX Number of pixels to overscroll by in either direction 16899 * along the X axis. 16900 * @param maxOverScrollY Number of pixels to overscroll by in either direction 16901 * along the Y axis. 16902 * @param isTouchEvent true if this scroll operation is the result of a touch event. 16903 * @return true if scrolling was clamped to an over-scroll boundary along either 16904 * axis, false otherwise. 16905 */ 16906 @SuppressWarnings({"UnusedParameters"}) 16907 protected boolean overScrollBy(int deltaX, int deltaY, 16908 int scrollX, int scrollY, 16909 int scrollRangeX, int scrollRangeY, 16910 int maxOverScrollX, int maxOverScrollY, 16911 boolean isTouchEvent) { 16912 final int overScrollMode = mOverScrollMode; 16913 final boolean canScrollHorizontal = 16914 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 16915 final boolean canScrollVertical = 16916 computeVerticalScrollRange() > computeVerticalScrollExtent(); 16917 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 16918 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 16919 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 16920 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 16921 16922 int newScrollX = scrollX + deltaX; 16923 if (!overScrollHorizontal) { 16924 maxOverScrollX = 0; 16925 } 16926 16927 int newScrollY = scrollY + deltaY; 16928 if (!overScrollVertical) { 16929 maxOverScrollY = 0; 16930 } 16931 16932 // Clamp values if at the limits and record 16933 final int left = -maxOverScrollX; 16934 final int right = maxOverScrollX + scrollRangeX; 16935 final int top = -maxOverScrollY; 16936 final int bottom = maxOverScrollY + scrollRangeY; 16937 16938 boolean clampedX = false; 16939 if (newScrollX > right) { 16940 newScrollX = right; 16941 clampedX = true; 16942 } else if (newScrollX < left) { 16943 newScrollX = left; 16944 clampedX = true; 16945 } 16946 16947 boolean clampedY = false; 16948 if (newScrollY > bottom) { 16949 newScrollY = bottom; 16950 clampedY = true; 16951 } else if (newScrollY < top) { 16952 newScrollY = top; 16953 clampedY = true; 16954 } 16955 16956 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 16957 16958 return clampedX || clampedY; 16959 } 16960 16961 /** 16962 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 16963 * respond to the results of an over-scroll operation. 16964 * 16965 * @param scrollX New X scroll value in pixels 16966 * @param scrollY New Y scroll value in pixels 16967 * @param clampedX True if scrollX was clamped to an over-scroll boundary 16968 * @param clampedY True if scrollY was clamped to an over-scroll boundary 16969 */ 16970 protected void onOverScrolled(int scrollX, int scrollY, 16971 boolean clampedX, boolean clampedY) { 16972 // Intentionally empty. 16973 } 16974 16975 /** 16976 * Returns the over-scroll mode for this view. The result will be 16977 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 16978 * (allow over-scrolling only if the view content is larger than the container), 16979 * or {@link #OVER_SCROLL_NEVER}. 16980 * 16981 * @return This view's over-scroll mode. 16982 */ 16983 public int getOverScrollMode() { 16984 return mOverScrollMode; 16985 } 16986 16987 /** 16988 * Set the over-scroll mode for this view. Valid over-scroll modes are 16989 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 16990 * (allow over-scrolling only if the view content is larger than the container), 16991 * or {@link #OVER_SCROLL_NEVER}. 16992 * 16993 * Setting the over-scroll mode of a view will have an effect only if the 16994 * view is capable of scrolling. 16995 * 16996 * @param overScrollMode The new over-scroll mode for this view. 16997 */ 16998 public void setOverScrollMode(int overScrollMode) { 16999 if (overScrollMode != OVER_SCROLL_ALWAYS && 17000 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 17001 overScrollMode != OVER_SCROLL_NEVER) { 17002 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 17003 } 17004 mOverScrollMode = overScrollMode; 17005 } 17006 17007 /** 17008 * Gets a scale factor that determines the distance the view should scroll 17009 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 17010 * @return The vertical scroll scale factor. 17011 * @hide 17012 */ 17013 protected float getVerticalScrollFactor() { 17014 if (mVerticalScrollFactor == 0) { 17015 TypedValue outValue = new TypedValue(); 17016 if (!mContext.getTheme().resolveAttribute( 17017 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 17018 throw new IllegalStateException( 17019 "Expected theme to define listPreferredItemHeight."); 17020 } 17021 mVerticalScrollFactor = outValue.getDimension( 17022 mContext.getResources().getDisplayMetrics()); 17023 } 17024 return mVerticalScrollFactor; 17025 } 17026 17027 /** 17028 * Gets a scale factor that determines the distance the view should scroll 17029 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 17030 * @return The horizontal scroll scale factor. 17031 * @hide 17032 */ 17033 protected float getHorizontalScrollFactor() { 17034 // TODO: Should use something else. 17035 return getVerticalScrollFactor(); 17036 } 17037 17038 /** 17039 * Return the value specifying the text direction or policy that was set with 17040 * {@link #setTextDirection(int)}. 17041 * 17042 * @return the defined text direction. It can be one of: 17043 * 17044 * {@link #TEXT_DIRECTION_INHERIT}, 17045 * {@link #TEXT_DIRECTION_FIRST_STRONG} 17046 * {@link #TEXT_DIRECTION_ANY_RTL}, 17047 * {@link #TEXT_DIRECTION_LTR}, 17048 * {@link #TEXT_DIRECTION_RTL}, 17049 * {@link #TEXT_DIRECTION_LOCALE} 17050 * 17051 * @attr ref android.R.styleable#View_textDirection 17052 * 17053 * @hide 17054 */ 17055 @ViewDebug.ExportedProperty(category = "text", mapping = { 17056 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 17057 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 17058 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 17059 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 17060 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 17061 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 17062 }) 17063 public int getRawTextDirection() { 17064 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 17065 } 17066 17067 /** 17068 * Set the text direction. 17069 * 17070 * @param textDirection the direction to set. Should be one of: 17071 * 17072 * {@link #TEXT_DIRECTION_INHERIT}, 17073 * {@link #TEXT_DIRECTION_FIRST_STRONG} 17074 * {@link #TEXT_DIRECTION_ANY_RTL}, 17075 * {@link #TEXT_DIRECTION_LTR}, 17076 * {@link #TEXT_DIRECTION_RTL}, 17077 * {@link #TEXT_DIRECTION_LOCALE} 17078 * 17079 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution 17080 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will 17081 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 17082 * 17083 * @attr ref android.R.styleable#View_textDirection 17084 */ 17085 public void setTextDirection(int textDirection) { 17086 if (getRawTextDirection() != textDirection) { 17087 // Reset the current text direction and the resolved one 17088 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 17089 resetResolvedTextDirection(); 17090 // Set the new text direction 17091 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 17092 // Do resolution 17093 resolveTextDirection(); 17094 // Notify change 17095 onRtlPropertiesChanged(getLayoutDirection()); 17096 // Refresh 17097 requestLayout(); 17098 invalidate(true); 17099 } 17100 } 17101 17102 /** 17103 * Return the resolved text direction. 17104 * 17105 * @return the resolved text direction. Returns one of: 17106 * 17107 * {@link #TEXT_DIRECTION_FIRST_STRONG} 17108 * {@link #TEXT_DIRECTION_ANY_RTL}, 17109 * {@link #TEXT_DIRECTION_LTR}, 17110 * {@link #TEXT_DIRECTION_RTL}, 17111 * {@link #TEXT_DIRECTION_LOCALE} 17112 * 17113 * @attr ref android.R.styleable#View_textDirection 17114 */ 17115 @ViewDebug.ExportedProperty(category = "text", mapping = { 17116 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 17117 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 17118 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 17119 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 17120 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 17121 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 17122 }) 17123 public int getTextDirection() { 17124 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 17125 } 17126 17127 /** 17128 * Resolve the text direction. 17129 * 17130 * @return true if resolution has been done, false otherwise. 17131 * 17132 * @hide 17133 */ 17134 public boolean resolveTextDirection() { 17135 // Reset any previous text direction resolution 17136 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 17137 17138 if (hasRtlSupport()) { 17139 // Set resolved text direction flag depending on text direction flag 17140 final int textDirection = getRawTextDirection(); 17141 switch(textDirection) { 17142 case TEXT_DIRECTION_INHERIT: 17143 if (!canResolveTextDirection()) { 17144 // We cannot do the resolution if there is no parent, so use the default one 17145 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 17146 // Resolution will need to happen again later 17147 return false; 17148 } 17149 17150 // Parent has not yet resolved, so we still return the default 17151 if (!mParent.isTextDirectionResolved()) { 17152 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 17153 // Resolution will need to happen again later 17154 return false; 17155 } 17156 17157 // Set current resolved direction to the same value as the parent's one 17158 final int parentResolvedDirection = mParent.getTextDirection(); 17159 switch (parentResolvedDirection) { 17160 case TEXT_DIRECTION_FIRST_STRONG: 17161 case TEXT_DIRECTION_ANY_RTL: 17162 case TEXT_DIRECTION_LTR: 17163 case TEXT_DIRECTION_RTL: 17164 case TEXT_DIRECTION_LOCALE: 17165 mPrivateFlags2 |= 17166 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 17167 break; 17168 default: 17169 // Default resolved direction is "first strong" heuristic 17170 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 17171 } 17172 break; 17173 case TEXT_DIRECTION_FIRST_STRONG: 17174 case TEXT_DIRECTION_ANY_RTL: 17175 case TEXT_DIRECTION_LTR: 17176 case TEXT_DIRECTION_RTL: 17177 case TEXT_DIRECTION_LOCALE: 17178 // Resolved direction is the same as text direction 17179 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 17180 break; 17181 default: 17182 // Default resolved direction is "first strong" heuristic 17183 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 17184 } 17185 } else { 17186 // Default resolved direction is "first strong" heuristic 17187 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 17188 } 17189 17190 // Set to resolved 17191 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 17192 return true; 17193 } 17194 17195 /** 17196 * Check if text direction resolution can be done. 17197 * 17198 * @return true if text direction resolution can be done otherwise return false. 17199 * 17200 * @hide 17201 */ 17202 public boolean canResolveTextDirection() { 17203 switch (getRawTextDirection()) { 17204 case TEXT_DIRECTION_INHERIT: 17205 return (mParent != null) && mParent.canResolveTextDirection(); 17206 default: 17207 return true; 17208 } 17209 } 17210 17211 /** 17212 * Reset resolved text direction. Text direction will be resolved during a call to 17213 * {@link #onMeasure(int, int)}. 17214 * 17215 * @hide 17216 */ 17217 public void resetResolvedTextDirection() { 17218 // Reset any previous text direction resolution 17219 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 17220 // Set to default value 17221 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 17222 } 17223 17224 /** 17225 * @return true if text direction is inherited. 17226 * 17227 * @hide 17228 */ 17229 public boolean isTextDirectionInherited() { 17230 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 17231 } 17232 17233 /** 17234 * @return true if text direction is resolved. 17235 * 17236 * @hide 17237 */ 17238 public boolean isTextDirectionResolved() { 17239 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED; 17240 } 17241 17242 /** 17243 * Return the value specifying the text alignment or policy that was set with 17244 * {@link #setTextAlignment(int)}. 17245 * 17246 * @return the defined text alignment. It can be one of: 17247 * 17248 * {@link #TEXT_ALIGNMENT_INHERIT}, 17249 * {@link #TEXT_ALIGNMENT_GRAVITY}, 17250 * {@link #TEXT_ALIGNMENT_CENTER}, 17251 * {@link #TEXT_ALIGNMENT_TEXT_START}, 17252 * {@link #TEXT_ALIGNMENT_TEXT_END}, 17253 * {@link #TEXT_ALIGNMENT_VIEW_START}, 17254 * {@link #TEXT_ALIGNMENT_VIEW_END} 17255 * 17256 * @attr ref android.R.styleable#View_textAlignment 17257 * 17258 * @hide 17259 */ 17260 @ViewDebug.ExportedProperty(category = "text", mapping = { 17261 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 17262 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 17263 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 17264 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 17265 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 17266 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 17267 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 17268 }) 17269 public int getRawTextAlignment() { 17270 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 17271 } 17272 17273 /** 17274 * Set the text alignment. 17275 * 17276 * @param textAlignment The text alignment to set. Should be one of 17277 * 17278 * {@link #TEXT_ALIGNMENT_INHERIT}, 17279 * {@link #TEXT_ALIGNMENT_GRAVITY}, 17280 * {@link #TEXT_ALIGNMENT_CENTER}, 17281 * {@link #TEXT_ALIGNMENT_TEXT_START}, 17282 * {@link #TEXT_ALIGNMENT_TEXT_END}, 17283 * {@link #TEXT_ALIGNMENT_VIEW_START}, 17284 * {@link #TEXT_ALIGNMENT_VIEW_END} 17285 * 17286 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution 17287 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 17288 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}. 17289 * 17290 * @attr ref android.R.styleable#View_textAlignment 17291 */ 17292 public void setTextAlignment(int textAlignment) { 17293 if (textAlignment != getRawTextAlignment()) { 17294 // Reset the current and resolved text alignment 17295 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 17296 resetResolvedTextAlignment(); 17297 // Set the new text alignment 17298 mPrivateFlags2 |= 17299 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 17300 // Do resolution 17301 resolveTextAlignment(); 17302 // Notify change 17303 onRtlPropertiesChanged(getLayoutDirection()); 17304 // Refresh 17305 requestLayout(); 17306 invalidate(true); 17307 } 17308 } 17309 17310 /** 17311 * Return the resolved text alignment. 17312 * 17313 * @return the resolved text alignment. Returns one of: 17314 * 17315 * {@link #TEXT_ALIGNMENT_GRAVITY}, 17316 * {@link #TEXT_ALIGNMENT_CENTER}, 17317 * {@link #TEXT_ALIGNMENT_TEXT_START}, 17318 * {@link #TEXT_ALIGNMENT_TEXT_END}, 17319 * {@link #TEXT_ALIGNMENT_VIEW_START}, 17320 * {@link #TEXT_ALIGNMENT_VIEW_END} 17321 * 17322 * @attr ref android.R.styleable#View_textAlignment 17323 */ 17324 @ViewDebug.ExportedProperty(category = "text", mapping = { 17325 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 17326 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 17327 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 17328 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 17329 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 17330 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 17331 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 17332 }) 17333 public int getTextAlignment() { 17334 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> 17335 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 17336 } 17337 17338 /** 17339 * Resolve the text alignment. 17340 * 17341 * @return true if resolution has been done, false otherwise. 17342 * 17343 * @hide 17344 */ 17345 public boolean resolveTextAlignment() { 17346 // Reset any previous text alignment resolution 17347 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 17348 17349 if (hasRtlSupport()) { 17350 // Set resolved text alignment flag depending on text alignment flag 17351 final int textAlignment = getRawTextAlignment(); 17352 switch (textAlignment) { 17353 case TEXT_ALIGNMENT_INHERIT: 17354 // Check if we can resolve the text alignment 17355 if (!canResolveTextAlignment()) { 17356 // We cannot do the resolution if there is no parent so use the default 17357 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 17358 // Resolution will need to happen again later 17359 return false; 17360 } 17361 17362 // Parent has not yet resolved, so we still return the default 17363 if (!mParent.isTextAlignmentResolved()) { 17364 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 17365 // Resolution will need to happen again later 17366 return false; 17367 } 17368 17369 final int parentResolvedTextAlignment = mParent.getTextAlignment(); 17370 switch (parentResolvedTextAlignment) { 17371 case TEXT_ALIGNMENT_GRAVITY: 17372 case TEXT_ALIGNMENT_TEXT_START: 17373 case TEXT_ALIGNMENT_TEXT_END: 17374 case TEXT_ALIGNMENT_CENTER: 17375 case TEXT_ALIGNMENT_VIEW_START: 17376 case TEXT_ALIGNMENT_VIEW_END: 17377 // Resolved text alignment is the same as the parent resolved 17378 // text alignment 17379 mPrivateFlags2 |= 17380 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 17381 break; 17382 default: 17383 // Use default resolved text alignment 17384 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 17385 } 17386 break; 17387 case TEXT_ALIGNMENT_GRAVITY: 17388 case TEXT_ALIGNMENT_TEXT_START: 17389 case TEXT_ALIGNMENT_TEXT_END: 17390 case TEXT_ALIGNMENT_CENTER: 17391 case TEXT_ALIGNMENT_VIEW_START: 17392 case TEXT_ALIGNMENT_VIEW_END: 17393 // Resolved text alignment is the same as text alignment 17394 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 17395 break; 17396 default: 17397 // Use default resolved text alignment 17398 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 17399 } 17400 } else { 17401 // Use default resolved text alignment 17402 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 17403 } 17404 17405 // Set the resolved 17406 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 17407 return true; 17408 } 17409 17410 /** 17411 * Check if text alignment resolution can be done. 17412 * 17413 * @return true if text alignment resolution can be done otherwise return false. 17414 * 17415 * @hide 17416 */ 17417 public boolean canResolveTextAlignment() { 17418 switch (getRawTextAlignment()) { 17419 case TEXT_DIRECTION_INHERIT: 17420 return (mParent != null) && mParent.canResolveTextAlignment(); 17421 default: 17422 return true; 17423 } 17424 } 17425 17426 /** 17427 * Reset resolved text alignment. Text alignment will be resolved during a call to 17428 * {@link #onMeasure(int, int)}. 17429 * 17430 * @hide 17431 */ 17432 public void resetResolvedTextAlignment() { 17433 // Reset any previous text alignment resolution 17434 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 17435 // Set to default 17436 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 17437 } 17438 17439 /** 17440 * @return true if text alignment is inherited. 17441 * 17442 * @hide 17443 */ 17444 public boolean isTextAlignmentInherited() { 17445 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 17446 } 17447 17448 /** 17449 * @return true if text alignment is resolved. 17450 * 17451 * @hide 17452 */ 17453 public boolean isTextAlignmentResolved() { 17454 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED; 17455 } 17456 17457 /** 17458 * Generate a value suitable for use in {@link #setId(int)}. 17459 * This value will not collide with ID values generated at build time by aapt for R.id. 17460 * 17461 * @return a generated ID value 17462 */ 17463 public static int generateViewId() { 17464 for (;;) { 17465 final int result = sNextGeneratedId.get(); 17466 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 17467 int newValue = result + 1; 17468 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 17469 if (sNextGeneratedId.compareAndSet(result, newValue)) { 17470 return result; 17471 } 17472 } 17473 } 17474 17475 // 17476 // Properties 17477 // 17478 /** 17479 * A Property wrapper around the <code>alpha</code> functionality handled by the 17480 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 17481 */ 17482 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 17483 @Override 17484 public void setValue(View object, float value) { 17485 object.setAlpha(value); 17486 } 17487 17488 @Override 17489 public Float get(View object) { 17490 return object.getAlpha(); 17491 } 17492 }; 17493 17494 /** 17495 * A Property wrapper around the <code>translationX</code> functionality handled by the 17496 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 17497 */ 17498 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 17499 @Override 17500 public void setValue(View object, float value) { 17501 object.setTranslationX(value); 17502 } 17503 17504 @Override 17505 public Float get(View object) { 17506 return object.getTranslationX(); 17507 } 17508 }; 17509 17510 /** 17511 * A Property wrapper around the <code>translationY</code> functionality handled by the 17512 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 17513 */ 17514 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 17515 @Override 17516 public void setValue(View object, float value) { 17517 object.setTranslationY(value); 17518 } 17519 17520 @Override 17521 public Float get(View object) { 17522 return object.getTranslationY(); 17523 } 17524 }; 17525 17526 /** 17527 * A Property wrapper around the <code>x</code> functionality handled by the 17528 * {@link View#setX(float)} and {@link View#getX()} methods. 17529 */ 17530 public static final Property<View, Float> X = new FloatProperty<View>("x") { 17531 @Override 17532 public void setValue(View object, float value) { 17533 object.setX(value); 17534 } 17535 17536 @Override 17537 public Float get(View object) { 17538 return object.getX(); 17539 } 17540 }; 17541 17542 /** 17543 * A Property wrapper around the <code>y</code> functionality handled by the 17544 * {@link View#setY(float)} and {@link View#getY()} methods. 17545 */ 17546 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 17547 @Override 17548 public void setValue(View object, float value) { 17549 object.setY(value); 17550 } 17551 17552 @Override 17553 public Float get(View object) { 17554 return object.getY(); 17555 } 17556 }; 17557 17558 /** 17559 * A Property wrapper around the <code>rotation</code> functionality handled by the 17560 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 17561 */ 17562 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 17563 @Override 17564 public void setValue(View object, float value) { 17565 object.setRotation(value); 17566 } 17567 17568 @Override 17569 public Float get(View object) { 17570 return object.getRotation(); 17571 } 17572 }; 17573 17574 /** 17575 * A Property wrapper around the <code>rotationX</code> functionality handled by the 17576 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 17577 */ 17578 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 17579 @Override 17580 public void setValue(View object, float value) { 17581 object.setRotationX(value); 17582 } 17583 17584 @Override 17585 public Float get(View object) { 17586 return object.getRotationX(); 17587 } 17588 }; 17589 17590 /** 17591 * A Property wrapper around the <code>rotationY</code> functionality handled by the 17592 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 17593 */ 17594 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 17595 @Override 17596 public void setValue(View object, float value) { 17597 object.setRotationY(value); 17598 } 17599 17600 @Override 17601 public Float get(View object) { 17602 return object.getRotationY(); 17603 } 17604 }; 17605 17606 /** 17607 * A Property wrapper around the <code>scaleX</code> functionality handled by the 17608 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 17609 */ 17610 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 17611 @Override 17612 public void setValue(View object, float value) { 17613 object.setScaleX(value); 17614 } 17615 17616 @Override 17617 public Float get(View object) { 17618 return object.getScaleX(); 17619 } 17620 }; 17621 17622 /** 17623 * A Property wrapper around the <code>scaleY</code> functionality handled by the 17624 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 17625 */ 17626 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 17627 @Override 17628 public void setValue(View object, float value) { 17629 object.setScaleY(value); 17630 } 17631 17632 @Override 17633 public Float get(View object) { 17634 return object.getScaleY(); 17635 } 17636 }; 17637 17638 /** 17639 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 17640 * Each MeasureSpec represents a requirement for either the width or the height. 17641 * A MeasureSpec is comprised of a size and a mode. There are three possible 17642 * modes: 17643 * <dl> 17644 * <dt>UNSPECIFIED</dt> 17645 * <dd> 17646 * The parent has not imposed any constraint on the child. It can be whatever size 17647 * it wants. 17648 * </dd> 17649 * 17650 * <dt>EXACTLY</dt> 17651 * <dd> 17652 * The parent has determined an exact size for the child. The child is going to be 17653 * given those bounds regardless of how big it wants to be. 17654 * </dd> 17655 * 17656 * <dt>AT_MOST</dt> 17657 * <dd> 17658 * The child can be as large as it wants up to the specified size. 17659 * </dd> 17660 * </dl> 17661 * 17662 * MeasureSpecs are implemented as ints to reduce object allocation. This class 17663 * is provided to pack and unpack the <size, mode> tuple into the int. 17664 */ 17665 public static class MeasureSpec { 17666 private static final int MODE_SHIFT = 30; 17667 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 17668 17669 /** 17670 * Measure specification mode: The parent has not imposed any constraint 17671 * on the child. It can be whatever size it wants. 17672 */ 17673 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 17674 17675 /** 17676 * Measure specification mode: The parent has determined an exact size 17677 * for the child. The child is going to be given those bounds regardless 17678 * of how big it wants to be. 17679 */ 17680 public static final int EXACTLY = 1 << MODE_SHIFT; 17681 17682 /** 17683 * Measure specification mode: The child can be as large as it wants up 17684 * to the specified size. 17685 */ 17686 public static final int AT_MOST = 2 << MODE_SHIFT; 17687 17688 /** 17689 * Creates a measure specification based on the supplied size and mode. 17690 * 17691 * The mode must always be one of the following: 17692 * <ul> 17693 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 17694 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 17695 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 17696 * </ul> 17697 * 17698 * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's 17699 * implementation was such that the order of arguments did not matter 17700 * and overflow in either value could impact the resulting MeasureSpec. 17701 * {@link android.widget.RelativeLayout} was affected by this bug. 17702 * Apps targeting API levels greater than 17 will get the fixed, more strict 17703 * behavior.</p> 17704 * 17705 * @param size the size of the measure specification 17706 * @param mode the mode of the measure specification 17707 * @return the measure specification based on size and mode 17708 */ 17709 public static int makeMeasureSpec(int size, int mode) { 17710 if (sUseBrokenMakeMeasureSpec) { 17711 return size + mode; 17712 } else { 17713 return (size & ~MODE_MASK) | (mode & MODE_MASK); 17714 } 17715 } 17716 17717 /** 17718 * Extracts the mode from the supplied measure specification. 17719 * 17720 * @param measureSpec the measure specification to extract the mode from 17721 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 17722 * {@link android.view.View.MeasureSpec#AT_MOST} or 17723 * {@link android.view.View.MeasureSpec#EXACTLY} 17724 */ 17725 public static int getMode(int measureSpec) { 17726 return (measureSpec & MODE_MASK); 17727 } 17728 17729 /** 17730 * Extracts the size from the supplied measure specification. 17731 * 17732 * @param measureSpec the measure specification to extract the size from 17733 * @return the size in pixels defined in the supplied measure specification 17734 */ 17735 public static int getSize(int measureSpec) { 17736 return (measureSpec & ~MODE_MASK); 17737 } 17738 17739 static int adjust(int measureSpec, int delta) { 17740 return makeMeasureSpec(getSize(measureSpec + delta), getMode(measureSpec)); 17741 } 17742 17743 /** 17744 * Returns a String representation of the specified measure 17745 * specification. 17746 * 17747 * @param measureSpec the measure specification to convert to a String 17748 * @return a String with the following format: "MeasureSpec: MODE SIZE" 17749 */ 17750 public static String toString(int measureSpec) { 17751 int mode = getMode(measureSpec); 17752 int size = getSize(measureSpec); 17753 17754 StringBuilder sb = new StringBuilder("MeasureSpec: "); 17755 17756 if (mode == UNSPECIFIED) 17757 sb.append("UNSPECIFIED "); 17758 else if (mode == EXACTLY) 17759 sb.append("EXACTLY "); 17760 else if (mode == AT_MOST) 17761 sb.append("AT_MOST "); 17762 else 17763 sb.append(mode).append(" "); 17764 17765 sb.append(size); 17766 return sb.toString(); 17767 } 17768 } 17769 17770 class CheckForLongPress implements Runnable { 17771 17772 private int mOriginalWindowAttachCount; 17773 17774 public void run() { 17775 if (isPressed() && (mParent != null) 17776 && mOriginalWindowAttachCount == mWindowAttachCount) { 17777 if (performLongClick()) { 17778 mHasPerformedLongPress = true; 17779 } 17780 } 17781 } 17782 17783 public void rememberWindowAttachCount() { 17784 mOriginalWindowAttachCount = mWindowAttachCount; 17785 } 17786 } 17787 17788 private final class CheckForTap implements Runnable { 17789 public void run() { 17790 mPrivateFlags &= ~PFLAG_PREPRESSED; 17791 setPressed(true); 17792 checkForLongClick(ViewConfiguration.getTapTimeout()); 17793 } 17794 } 17795 17796 private final class PerformClick implements Runnable { 17797 public void run() { 17798 performClick(); 17799 } 17800 } 17801 17802 /** @hide */ 17803 public void hackTurnOffWindowResizeAnim(boolean off) { 17804 mAttachInfo.mTurnOffWindowResizeAnim = off; 17805 } 17806 17807 /** 17808 * This method returns a ViewPropertyAnimator object, which can be used to animate 17809 * specific properties on this View. 17810 * 17811 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 17812 */ 17813 public ViewPropertyAnimator animate() { 17814 if (mAnimator == null) { 17815 mAnimator = new ViewPropertyAnimator(this); 17816 } 17817 return mAnimator; 17818 } 17819 17820 /** 17821 * Set the current Scene that this view is in. The current scene is set only 17822 * on the root view of a scene, not for every view in that hierarchy. This 17823 * information is used by Scene to determine whether there is a previous 17824 * scene which should be exited before the new scene is entered. 17825 * 17826 * @param scene The new scene being set on the view 17827 * 17828 * @hide 17829 */ 17830 public void setCurrentScene(Scene scene) { 17831 mCurrentScene = scene; 17832 } 17833 17834 /** 17835 * Gets the current {@link Scene} set on this view. A scene is set on a view 17836 * only if that view is the scene root. 17837 * 17838 * @return The current Scene set on this view. A value of null indicates that 17839 * no Scene is current set. 17840 */ 17841 public Scene getCurrentScene() { 17842 return mCurrentScene; 17843 } 17844 17845 /** 17846 * Interface definition for a callback to be invoked when a hardware key event is 17847 * dispatched to this view. The callback will be invoked before the key event is 17848 * given to the view. This is only useful for hardware keyboards; a software input 17849 * method has no obligation to trigger this listener. 17850 */ 17851 public interface OnKeyListener { 17852 /** 17853 * Called when a hardware key is dispatched to a view. This allows listeners to 17854 * get a chance to respond before the target view. 17855 * <p>Key presses in software keyboards will generally NOT trigger this method, 17856 * although some may elect to do so in some situations. Do not assume a 17857 * software input method has to be key-based; even if it is, it may use key presses 17858 * in a different way than you expect, so there is no way to reliably catch soft 17859 * input key presses. 17860 * 17861 * @param v The view the key has been dispatched to. 17862 * @param keyCode The code for the physical key that was pressed 17863 * @param event The KeyEvent object containing full information about 17864 * the event. 17865 * @return True if the listener has consumed the event, false otherwise. 17866 */ 17867 boolean onKey(View v, int keyCode, KeyEvent event); 17868 } 17869 17870 /** 17871 * Interface definition for a callback to be invoked when a touch event is 17872 * dispatched to this view. The callback will be invoked before the touch 17873 * event is given to the view. 17874 */ 17875 public interface OnTouchListener { 17876 /** 17877 * Called when a touch event is dispatched to a view. This allows listeners to 17878 * get a chance to respond before the target view. 17879 * 17880 * @param v The view the touch event has been dispatched to. 17881 * @param event The MotionEvent object containing full information about 17882 * the event. 17883 * @return True if the listener has consumed the event, false otherwise. 17884 */ 17885 boolean onTouch(View v, MotionEvent event); 17886 } 17887 17888 /** 17889 * Interface definition for a callback to be invoked when a hover event is 17890 * dispatched to this view. The callback will be invoked before the hover 17891 * event is given to the view. 17892 */ 17893 public interface OnHoverListener { 17894 /** 17895 * Called when a hover event is dispatched to a view. This allows listeners to 17896 * get a chance to respond before the target view. 17897 * 17898 * @param v The view the hover event has been dispatched to. 17899 * @param event The MotionEvent object containing full information about 17900 * the event. 17901 * @return True if the listener has consumed the event, false otherwise. 17902 */ 17903 boolean onHover(View v, MotionEvent event); 17904 } 17905 17906 /** 17907 * Interface definition for a callback to be invoked when a generic motion event is 17908 * dispatched to this view. The callback will be invoked before the generic motion 17909 * event is given to the view. 17910 */ 17911 public interface OnGenericMotionListener { 17912 /** 17913 * Called when a generic motion event is dispatched to a view. This allows listeners to 17914 * get a chance to respond before the target view. 17915 * 17916 * @param v The view the generic motion event has been dispatched to. 17917 * @param event The MotionEvent object containing full information about 17918 * the event. 17919 * @return True if the listener has consumed the event, false otherwise. 17920 */ 17921 boolean onGenericMotion(View v, MotionEvent event); 17922 } 17923 17924 /** 17925 * Interface definition for a callback to be invoked when a view has been clicked and held. 17926 */ 17927 public interface OnLongClickListener { 17928 /** 17929 * Called when a view has been clicked and held. 17930 * 17931 * @param v The view that was clicked and held. 17932 * 17933 * @return true if the callback consumed the long click, false otherwise. 17934 */ 17935 boolean onLongClick(View v); 17936 } 17937 17938 /** 17939 * Interface definition for a callback to be invoked when a drag is being dispatched 17940 * to this view. The callback will be invoked before the hosting view's own 17941 * onDrag(event) method. If the listener wants to fall back to the hosting view's 17942 * onDrag(event) behavior, it should return 'false' from this callback. 17943 * 17944 * <div class="special reference"> 17945 * <h3>Developer Guides</h3> 17946 * <p>For a guide to implementing drag and drop features, read the 17947 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 17948 * </div> 17949 */ 17950 public interface OnDragListener { 17951 /** 17952 * Called when a drag event is dispatched to a view. This allows listeners 17953 * to get a chance to override base View behavior. 17954 * 17955 * @param v The View that received the drag event. 17956 * @param event The {@link android.view.DragEvent} object for the drag event. 17957 * @return {@code true} if the drag event was handled successfully, or {@code false} 17958 * if the drag event was not handled. Note that {@code false} will trigger the View 17959 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 17960 */ 17961 boolean onDrag(View v, DragEvent event); 17962 } 17963 17964 /** 17965 * Interface definition for a callback to be invoked when the focus state of 17966 * a view changed. 17967 */ 17968 public interface OnFocusChangeListener { 17969 /** 17970 * Called when the focus state of a view has changed. 17971 * 17972 * @param v The view whose state has changed. 17973 * @param hasFocus The new focus state of v. 17974 */ 17975 void onFocusChange(View v, boolean hasFocus); 17976 } 17977 17978 /** 17979 * Interface definition for a callback to be invoked when a view is clicked. 17980 */ 17981 public interface OnClickListener { 17982 /** 17983 * Called when a view has been clicked. 17984 * 17985 * @param v The view that was clicked. 17986 */ 17987 void onClick(View v); 17988 } 17989 17990 /** 17991 * Interface definition for a callback to be invoked when the context menu 17992 * for this view is being built. 17993 */ 17994 public interface OnCreateContextMenuListener { 17995 /** 17996 * Called when the context menu for this view is being built. It is not 17997 * safe to hold onto the menu after this method returns. 17998 * 17999 * @param menu The context menu that is being built 18000 * @param v The view for which the context menu is being built 18001 * @param menuInfo Extra information about the item for which the 18002 * context menu should be shown. This information will vary 18003 * depending on the class of v. 18004 */ 18005 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 18006 } 18007 18008 /** 18009 * Interface definition for a callback to be invoked when the status bar changes 18010 * visibility. This reports <strong>global</strong> changes to the system UI 18011 * state, not what the application is requesting. 18012 * 18013 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 18014 */ 18015 public interface OnSystemUiVisibilityChangeListener { 18016 /** 18017 * Called when the status bar changes visibility because of a call to 18018 * {@link View#setSystemUiVisibility(int)}. 18019 * 18020 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 18021 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 18022 * This tells you the <strong>global</strong> state of these UI visibility 18023 * flags, not what your app is currently applying. 18024 */ 18025 public void onSystemUiVisibilityChange(int visibility); 18026 } 18027 18028 /** 18029 * Interface definition for a callback to be invoked when this view is attached 18030 * or detached from its window. 18031 */ 18032 public interface OnAttachStateChangeListener { 18033 /** 18034 * Called when the view is attached to a window. 18035 * @param v The view that was attached 18036 */ 18037 public void onViewAttachedToWindow(View v); 18038 /** 18039 * Called when the view is detached from a window. 18040 * @param v The view that was detached 18041 */ 18042 public void onViewDetachedFromWindow(View v); 18043 } 18044 18045 private final class UnsetPressedState implements Runnable { 18046 public void run() { 18047 setPressed(false); 18048 } 18049 } 18050 18051 /** 18052 * Base class for derived classes that want to save and restore their own 18053 * state in {@link android.view.View#onSaveInstanceState()}. 18054 */ 18055 public static class BaseSavedState extends AbsSavedState { 18056 /** 18057 * Constructor used when reading from a parcel. Reads the state of the superclass. 18058 * 18059 * @param source 18060 */ 18061 public BaseSavedState(Parcel source) { 18062 super(source); 18063 } 18064 18065 /** 18066 * Constructor called by derived classes when creating their SavedState objects 18067 * 18068 * @param superState The state of the superclass of this view 18069 */ 18070 public BaseSavedState(Parcelable superState) { 18071 super(superState); 18072 } 18073 18074 public static final Parcelable.Creator<BaseSavedState> CREATOR = 18075 new Parcelable.Creator<BaseSavedState>() { 18076 public BaseSavedState createFromParcel(Parcel in) { 18077 return new BaseSavedState(in); 18078 } 18079 18080 public BaseSavedState[] newArray(int size) { 18081 return new BaseSavedState[size]; 18082 } 18083 }; 18084 } 18085 18086 /** 18087 * A set of information given to a view when it is attached to its parent 18088 * window. 18089 */ 18090 static class AttachInfo { 18091 interface Callbacks { 18092 void playSoundEffect(int effectId); 18093 boolean performHapticFeedback(int effectId, boolean always); 18094 } 18095 18096 /** 18097 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 18098 * to a Handler. This class contains the target (View) to invalidate and 18099 * the coordinates of the dirty rectangle. 18100 * 18101 * For performance purposes, this class also implements a pool of up to 18102 * POOL_LIMIT objects that get reused. This reduces memory allocations 18103 * whenever possible. 18104 */ 18105 static class InvalidateInfo { 18106 private static final int POOL_LIMIT = 10; 18107 18108 private static final SynchronizedPool<InvalidateInfo> sPool = 18109 new SynchronizedPool<InvalidateInfo>(POOL_LIMIT); 18110 18111 View target; 18112 18113 int left; 18114 int top; 18115 int right; 18116 int bottom; 18117 18118 public static InvalidateInfo obtain() { 18119 InvalidateInfo instance = sPool.acquire(); 18120 return (instance != null) ? instance : new InvalidateInfo(); 18121 } 18122 18123 public void recycle() { 18124 target = null; 18125 sPool.release(this); 18126 } 18127 } 18128 18129 final IWindowSession mSession; 18130 18131 final IWindow mWindow; 18132 18133 final IBinder mWindowToken; 18134 18135 final Display mDisplay; 18136 18137 final Callbacks mRootCallbacks; 18138 18139 HardwareCanvas mHardwareCanvas; 18140 18141 IWindowId mIWindowId; 18142 WindowId mWindowId; 18143 18144 /** 18145 * The top view of the hierarchy. 18146 */ 18147 View mRootView; 18148 18149 IBinder mPanelParentWindowToken; 18150 Surface mSurface; 18151 18152 boolean mHardwareAccelerated; 18153 boolean mHardwareAccelerationRequested; 18154 HardwareRenderer mHardwareRenderer; 18155 18156 boolean mScreenOn; 18157 18158 /** 18159 * Scale factor used by the compatibility mode 18160 */ 18161 float mApplicationScale; 18162 18163 /** 18164 * Indicates whether the application is in compatibility mode 18165 */ 18166 boolean mScalingRequired; 18167 18168 /** 18169 * If set, ViewRootImpl doesn't use its lame animation for when the window resizes. 18170 */ 18171 boolean mTurnOffWindowResizeAnim; 18172 18173 /** 18174 * Left position of this view's window 18175 */ 18176 int mWindowLeft; 18177 18178 /** 18179 * Top position of this view's window 18180 */ 18181 int mWindowTop; 18182 18183 /** 18184 * Indicates whether views need to use 32-bit drawing caches 18185 */ 18186 boolean mUse32BitDrawingCache; 18187 18188 /** 18189 * For windows that are full-screen but using insets to layout inside 18190 * of the screen areas, these are the current insets to appear inside 18191 * the overscan area of the display. 18192 */ 18193 final Rect mOverscanInsets = new Rect(); 18194 18195 /** 18196 * For windows that are full-screen but using insets to layout inside 18197 * of the screen decorations, these are the current insets for the 18198 * content of the window. 18199 */ 18200 final Rect mContentInsets = new Rect(); 18201 18202 /** 18203 * For windows that are full-screen but using insets to layout inside 18204 * of the screen decorations, these are the current insets for the 18205 * actual visible parts of the window. 18206 */ 18207 final Rect mVisibleInsets = new Rect(); 18208 18209 /** 18210 * The internal insets given by this window. This value is 18211 * supplied by the client (through 18212 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 18213 * be given to the window manager when changed to be used in laying 18214 * out windows behind it. 18215 */ 18216 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 18217 = new ViewTreeObserver.InternalInsetsInfo(); 18218 18219 /** 18220 * All views in the window's hierarchy that serve as scroll containers, 18221 * used to determine if the window can be resized or must be panned 18222 * to adjust for a soft input area. 18223 */ 18224 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 18225 18226 final KeyEvent.DispatcherState mKeyDispatchState 18227 = new KeyEvent.DispatcherState(); 18228 18229 /** 18230 * Indicates whether the view's window currently has the focus. 18231 */ 18232 boolean mHasWindowFocus; 18233 18234 /** 18235 * The current visibility of the window. 18236 */ 18237 int mWindowVisibility; 18238 18239 /** 18240 * Indicates the time at which drawing started to occur. 18241 */ 18242 long mDrawingTime; 18243 18244 /** 18245 * Indicates whether or not ignoring the DIRTY_MASK flags. 18246 */ 18247 boolean mIgnoreDirtyState; 18248 18249 /** 18250 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 18251 * to avoid clearing that flag prematurely. 18252 */ 18253 boolean mSetIgnoreDirtyState = false; 18254 18255 /** 18256 * Indicates whether the view's window is currently in touch mode. 18257 */ 18258 boolean mInTouchMode; 18259 18260 /** 18261 * Indicates that ViewAncestor should trigger a global layout change 18262 * the next time it performs a traversal 18263 */ 18264 boolean mRecomputeGlobalAttributes; 18265 18266 /** 18267 * Always report new attributes at next traversal. 18268 */ 18269 boolean mForceReportNewAttributes; 18270 18271 /** 18272 * Set during a traveral if any views want to keep the screen on. 18273 */ 18274 boolean mKeepScreenOn; 18275 18276 /** 18277 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 18278 */ 18279 int mSystemUiVisibility; 18280 18281 /** 18282 * Hack to force certain system UI visibility flags to be cleared. 18283 */ 18284 int mDisabledSystemUiVisibility; 18285 18286 /** 18287 * Last global system UI visibility reported by the window manager. 18288 */ 18289 int mGlobalSystemUiVisibility; 18290 18291 /** 18292 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 18293 * attached. 18294 */ 18295 boolean mHasSystemUiListeners; 18296 18297 /** 18298 * Set if the window has requested to extend into the overscan region 18299 * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN. 18300 */ 18301 boolean mOverscanRequested; 18302 18303 /** 18304 * Set if the visibility of any views has changed. 18305 */ 18306 boolean mViewVisibilityChanged; 18307 18308 /** 18309 * Set to true if a view has been scrolled. 18310 */ 18311 boolean mViewScrollChanged; 18312 18313 /** 18314 * Global to the view hierarchy used as a temporary for dealing with 18315 * x/y points in the transparent region computations. 18316 */ 18317 final int[] mTransparentLocation = new int[2]; 18318 18319 /** 18320 * Global to the view hierarchy used as a temporary for dealing with 18321 * x/y points in the ViewGroup.invalidateChild implementation. 18322 */ 18323 final int[] mInvalidateChildLocation = new int[2]; 18324 18325 18326 /** 18327 * Global to the view hierarchy used as a temporary for dealing with 18328 * x/y location when view is transformed. 18329 */ 18330 final float[] mTmpTransformLocation = new float[2]; 18331 18332 /** 18333 * The view tree observer used to dispatch global events like 18334 * layout, pre-draw, touch mode change, etc. 18335 */ 18336 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 18337 18338 /** 18339 * A Canvas used by the view hierarchy to perform bitmap caching. 18340 */ 18341 Canvas mCanvas; 18342 18343 /** 18344 * The view root impl. 18345 */ 18346 final ViewRootImpl mViewRootImpl; 18347 18348 /** 18349 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 18350 * handler can be used to pump events in the UI events queue. 18351 */ 18352 final Handler mHandler; 18353 18354 /** 18355 * Temporary for use in computing invalidate rectangles while 18356 * calling up the hierarchy. 18357 */ 18358 final Rect mTmpInvalRect = new Rect(); 18359 18360 /** 18361 * Temporary for use in computing hit areas with transformed views 18362 */ 18363 final RectF mTmpTransformRect = new RectF(); 18364 18365 /** 18366 * Temporary for use in transforming invalidation rect 18367 */ 18368 final Matrix mTmpMatrix = new Matrix(); 18369 18370 /** 18371 * Temporary for use in transforming invalidation rect 18372 */ 18373 final Transformation mTmpTransformation = new Transformation(); 18374 18375 /** 18376 * Temporary list for use in collecting focusable descendents of a view. 18377 */ 18378 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 18379 18380 /** 18381 * The id of the window for accessibility purposes. 18382 */ 18383 int mAccessibilityWindowId = View.NO_ID; 18384 18385 /** 18386 * Flags related to accessibility processing. 18387 * 18388 * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 18389 * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS 18390 */ 18391 int mAccessibilityFetchFlags; 18392 18393 /** 18394 * The drawable for highlighting accessibility focus. 18395 */ 18396 Drawable mAccessibilityFocusDrawable; 18397 18398 /** 18399 * Show where the margins, bounds and layout bounds are for each view. 18400 */ 18401 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 18402 18403 /** 18404 * Point used to compute visible regions. 18405 */ 18406 final Point mPoint = new Point(); 18407 18408 /** 18409 * Used to track which View originated a requestLayout() call, used when 18410 * requestLayout() is called during layout. 18411 */ 18412 View mViewRequestingLayout; 18413 18414 /** 18415 * Creates a new set of attachment information with the specified 18416 * events handler and thread. 18417 * 18418 * @param handler the events handler the view must use 18419 */ 18420 AttachInfo(IWindowSession session, IWindow window, Display display, 18421 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) { 18422 mSession = session; 18423 mWindow = window; 18424 mWindowToken = window.asBinder(); 18425 mDisplay = display; 18426 mViewRootImpl = viewRootImpl; 18427 mHandler = handler; 18428 mRootCallbacks = effectPlayer; 18429 } 18430 } 18431 18432 /** 18433 * <p>ScrollabilityCache holds various fields used by a View when scrolling 18434 * is supported. This avoids keeping too many unused fields in most 18435 * instances of View.</p> 18436 */ 18437 private static class ScrollabilityCache implements Runnable { 18438 18439 /** 18440 * Scrollbars are not visible 18441 */ 18442 public static final int OFF = 0; 18443 18444 /** 18445 * Scrollbars are visible 18446 */ 18447 public static final int ON = 1; 18448 18449 /** 18450 * Scrollbars are fading away 18451 */ 18452 public static final int FADING = 2; 18453 18454 public boolean fadeScrollBars; 18455 18456 public int fadingEdgeLength; 18457 public int scrollBarDefaultDelayBeforeFade; 18458 public int scrollBarFadeDuration; 18459 18460 public int scrollBarSize; 18461 public ScrollBarDrawable scrollBar; 18462 public float[] interpolatorValues; 18463 public View host; 18464 18465 public final Paint paint; 18466 public final Matrix matrix; 18467 public Shader shader; 18468 18469 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 18470 18471 private static final float[] OPAQUE = { 255 }; 18472 private static final float[] TRANSPARENT = { 0.0f }; 18473 18474 /** 18475 * When fading should start. This time moves into the future every time 18476 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 18477 */ 18478 public long fadeStartTime; 18479 18480 18481 /** 18482 * The current state of the scrollbars: ON, OFF, or FADING 18483 */ 18484 public int state = OFF; 18485 18486 private int mLastColor; 18487 18488 public ScrollabilityCache(ViewConfiguration configuration, View host) { 18489 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 18490 scrollBarSize = configuration.getScaledScrollBarSize(); 18491 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 18492 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 18493 18494 paint = new Paint(); 18495 matrix = new Matrix(); 18496 // use use a height of 1, and then wack the matrix each time we 18497 // actually use it. 18498 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 18499 paint.setShader(shader); 18500 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 18501 18502 this.host = host; 18503 } 18504 18505 public void setFadeColor(int color) { 18506 if (color != mLastColor) { 18507 mLastColor = color; 18508 18509 if (color != 0) { 18510 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 18511 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 18512 paint.setShader(shader); 18513 // Restore the default transfer mode (src_over) 18514 paint.setXfermode(null); 18515 } else { 18516 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 18517 paint.setShader(shader); 18518 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 18519 } 18520 } 18521 } 18522 18523 public void run() { 18524 long now = AnimationUtils.currentAnimationTimeMillis(); 18525 if (now >= fadeStartTime) { 18526 18527 // the animation fades the scrollbars out by changing 18528 // the opacity (alpha) from fully opaque to fully 18529 // transparent 18530 int nextFrame = (int) now; 18531 int framesCount = 0; 18532 18533 Interpolator interpolator = scrollBarInterpolator; 18534 18535 // Start opaque 18536 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 18537 18538 // End transparent 18539 nextFrame += scrollBarFadeDuration; 18540 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 18541 18542 state = FADING; 18543 18544 // Kick off the fade animation 18545 host.invalidate(true); 18546 } 18547 } 18548 } 18549 18550 /** 18551 * Resuable callback for sending 18552 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 18553 */ 18554 private class SendViewScrolledAccessibilityEvent implements Runnable { 18555 public volatile boolean mIsPending; 18556 18557 public void run() { 18558 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 18559 mIsPending = false; 18560 } 18561 } 18562 18563 /** 18564 * <p> 18565 * This class represents a delegate that can be registered in a {@link View} 18566 * to enhance accessibility support via composition rather via inheritance. 18567 * It is specifically targeted to widget developers that extend basic View 18568 * classes i.e. classes in package android.view, that would like their 18569 * applications to be backwards compatible. 18570 * </p> 18571 * <div class="special reference"> 18572 * <h3>Developer Guides</h3> 18573 * <p>For more information about making applications accessible, read the 18574 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 18575 * developer guide.</p> 18576 * </div> 18577 * <p> 18578 * A scenario in which a developer would like to use an accessibility delegate 18579 * is overriding a method introduced in a later API version then the minimal API 18580 * version supported by the application. For example, the method 18581 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 18582 * in API version 4 when the accessibility APIs were first introduced. If a 18583 * developer would like his application to run on API version 4 devices (assuming 18584 * all other APIs used by the application are version 4 or lower) and take advantage 18585 * of this method, instead of overriding the method which would break the application's 18586 * backwards compatibility, he can override the corresponding method in this 18587 * delegate and register the delegate in the target View if the API version of 18588 * the system is high enough i.e. the API version is same or higher to the API 18589 * version that introduced 18590 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 18591 * </p> 18592 * <p> 18593 * Here is an example implementation: 18594 * </p> 18595 * <code><pre><p> 18596 * if (Build.VERSION.SDK_INT >= 14) { 18597 * // If the API version is equal of higher than the version in 18598 * // which onInitializeAccessibilityNodeInfo was introduced we 18599 * // register a delegate with a customized implementation. 18600 * View view = findViewById(R.id.view_id); 18601 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 18602 * public void onInitializeAccessibilityNodeInfo(View host, 18603 * AccessibilityNodeInfo info) { 18604 * // Let the default implementation populate the info. 18605 * super.onInitializeAccessibilityNodeInfo(host, info); 18606 * // Set some other information. 18607 * info.setEnabled(host.isEnabled()); 18608 * } 18609 * }); 18610 * } 18611 * </code></pre></p> 18612 * <p> 18613 * This delegate contains methods that correspond to the accessibility methods 18614 * in View. If a delegate has been specified the implementation in View hands 18615 * off handling to the corresponding method in this delegate. The default 18616 * implementation the delegate methods behaves exactly as the corresponding 18617 * method in View for the case of no accessibility delegate been set. Hence, 18618 * to customize the behavior of a View method, clients can override only the 18619 * corresponding delegate method without altering the behavior of the rest 18620 * accessibility related methods of the host view. 18621 * </p> 18622 */ 18623 public static class AccessibilityDelegate { 18624 18625 /** 18626 * Sends an accessibility event of the given type. If accessibility is not 18627 * enabled this method has no effect. 18628 * <p> 18629 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 18630 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 18631 * been set. 18632 * </p> 18633 * 18634 * @param host The View hosting the delegate. 18635 * @param eventType The type of the event to send. 18636 * 18637 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 18638 */ 18639 public void sendAccessibilityEvent(View host, int eventType) { 18640 host.sendAccessibilityEventInternal(eventType); 18641 } 18642 18643 /** 18644 * Performs the specified accessibility action on the view. For 18645 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 18646 * <p> 18647 * The default implementation behaves as 18648 * {@link View#performAccessibilityAction(int, Bundle) 18649 * View#performAccessibilityAction(int, Bundle)} for the case of 18650 * no accessibility delegate been set. 18651 * </p> 18652 * 18653 * @param action The action to perform. 18654 * @return Whether the action was performed. 18655 * 18656 * @see View#performAccessibilityAction(int, Bundle) 18657 * View#performAccessibilityAction(int, Bundle) 18658 */ 18659 public boolean performAccessibilityAction(View host, int action, Bundle args) { 18660 return host.performAccessibilityActionInternal(action, args); 18661 } 18662 18663 /** 18664 * Sends an accessibility event. This method behaves exactly as 18665 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 18666 * empty {@link AccessibilityEvent} and does not perform a check whether 18667 * accessibility is enabled. 18668 * <p> 18669 * The default implementation behaves as 18670 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 18671 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 18672 * the case of no accessibility delegate been set. 18673 * </p> 18674 * 18675 * @param host The View hosting the delegate. 18676 * @param event The event to send. 18677 * 18678 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 18679 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 18680 */ 18681 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 18682 host.sendAccessibilityEventUncheckedInternal(event); 18683 } 18684 18685 /** 18686 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 18687 * to its children for adding their text content to the event. 18688 * <p> 18689 * The default implementation behaves as 18690 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 18691 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 18692 * the case of no accessibility delegate been set. 18693 * </p> 18694 * 18695 * @param host The View hosting the delegate. 18696 * @param event The event. 18697 * @return True if the event population was completed. 18698 * 18699 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 18700 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 18701 */ 18702 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 18703 return host.dispatchPopulateAccessibilityEventInternal(event); 18704 } 18705 18706 /** 18707 * Gives a chance to the host View to populate the accessibility event with its 18708 * text content. 18709 * <p> 18710 * The default implementation behaves as 18711 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 18712 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 18713 * the case of no accessibility delegate been set. 18714 * </p> 18715 * 18716 * @param host The View hosting the delegate. 18717 * @param event The accessibility event which to populate. 18718 * 18719 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 18720 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 18721 */ 18722 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 18723 host.onPopulateAccessibilityEventInternal(event); 18724 } 18725 18726 /** 18727 * Initializes an {@link AccessibilityEvent} with information about the 18728 * the host View which is the event source. 18729 * <p> 18730 * The default implementation behaves as 18731 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 18732 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 18733 * the case of no accessibility delegate been set. 18734 * </p> 18735 * 18736 * @param host The View hosting the delegate. 18737 * @param event The event to initialize. 18738 * 18739 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 18740 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 18741 */ 18742 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 18743 host.onInitializeAccessibilityEventInternal(event); 18744 } 18745 18746 /** 18747 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 18748 * <p> 18749 * The default implementation behaves as 18750 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 18751 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 18752 * the case of no accessibility delegate been set. 18753 * </p> 18754 * 18755 * @param host The View hosting the delegate. 18756 * @param info The instance to initialize. 18757 * 18758 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 18759 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 18760 */ 18761 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 18762 host.onInitializeAccessibilityNodeInfoInternal(info); 18763 } 18764 18765 /** 18766 * Called when a child of the host View has requested sending an 18767 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 18768 * to augment the event. 18769 * <p> 18770 * The default implementation behaves as 18771 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 18772 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 18773 * the case of no accessibility delegate been set. 18774 * </p> 18775 * 18776 * @param host The View hosting the delegate. 18777 * @param child The child which requests sending the event. 18778 * @param event The event to be sent. 18779 * @return True if the event should be sent 18780 * 18781 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 18782 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 18783 */ 18784 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 18785 AccessibilityEvent event) { 18786 return host.onRequestSendAccessibilityEventInternal(child, event); 18787 } 18788 18789 /** 18790 * Gets the provider for managing a virtual view hierarchy rooted at this View 18791 * and reported to {@link android.accessibilityservice.AccessibilityService}s 18792 * that explore the window content. 18793 * <p> 18794 * The default implementation behaves as 18795 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 18796 * the case of no accessibility delegate been set. 18797 * </p> 18798 * 18799 * @return The provider. 18800 * 18801 * @see AccessibilityNodeProvider 18802 */ 18803 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 18804 return null; 18805 } 18806 18807 /** 18808 * Returns an {@link AccessibilityNodeInfo} representing the host view from the 18809 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 18810 * This method is responsible for obtaining an accessibility node info from a 18811 * pool of reusable instances and calling 18812 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host 18813 * view to initialize the former. 18814 * <p> 18815 * <strong>Note:</strong> The client is responsible for recycling the obtained 18816 * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object 18817 * creation. 18818 * </p> 18819 * <p> 18820 * The default implementation behaves as 18821 * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for 18822 * the case of no accessibility delegate been set. 18823 * </p> 18824 * @return A populated {@link AccessibilityNodeInfo}. 18825 * 18826 * @see AccessibilityNodeInfo 18827 * 18828 * @hide 18829 */ 18830 public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) { 18831 return host.createAccessibilityNodeInfoInternal(); 18832 } 18833 } 18834 18835 private class MatchIdPredicate implements Predicate<View> { 18836 public int mId; 18837 18838 @Override 18839 public boolean apply(View view) { 18840 return (view.mID == mId); 18841 } 18842 } 18843 18844 private class MatchLabelForPredicate implements Predicate<View> { 18845 private int mLabeledId; 18846 18847 @Override 18848 public boolean apply(View view) { 18849 return (view.mLabelForId == mLabeledId); 18850 } 18851 } 18852 18853 private class SendViewStateChangedAccessibilityEvent implements Runnable { 18854 private boolean mPosted; 18855 private long mLastEventTimeMillis; 18856 18857 public void run() { 18858 mPosted = false; 18859 mLastEventTimeMillis = SystemClock.uptimeMillis(); 18860 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 18861 AccessibilityEvent event = AccessibilityEvent.obtain(); 18862 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 18863 event.setContentChangeType(AccessibilityEvent.CONTENT_CHANGE_TYPE_NODE); 18864 sendAccessibilityEventUnchecked(event); 18865 } 18866 } 18867 18868 public void runOrPost() { 18869 if (mPosted) { 18870 return; 18871 } 18872 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 18873 final long minEventIntevalMillis = 18874 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 18875 if (timeSinceLastMillis >= minEventIntevalMillis) { 18876 run(); 18877 } else { 18878 postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 18879 mPosted = true; 18880 } 18881 } 18882 } 18883 18884 /** 18885 * Dump all private flags in readable format, useful for documentation and 18886 * sanity checking. 18887 */ 18888 private static void dumpFlags() { 18889 final HashMap<String, String> found = Maps.newHashMap(); 18890 try { 18891 for (Field field : View.class.getDeclaredFields()) { 18892 final int modifiers = field.getModifiers(); 18893 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 18894 if (field.getType().equals(int.class)) { 18895 final int value = field.getInt(null); 18896 dumpFlag(found, field.getName(), value); 18897 } else if (field.getType().equals(int[].class)) { 18898 final int[] values = (int[]) field.get(null); 18899 for (int i = 0; i < values.length; i++) { 18900 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 18901 } 18902 } 18903 } 18904 } 18905 } catch (IllegalAccessException e) { 18906 throw new RuntimeException(e); 18907 } 18908 18909 final ArrayList<String> keys = Lists.newArrayList(); 18910 keys.addAll(found.keySet()); 18911 Collections.sort(keys); 18912 for (String key : keys) { 18913 Log.d(VIEW_LOG_TAG, found.get(key)); 18914 } 18915 } 18916 18917 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 18918 // Sort flags by prefix, then by bits, always keeping unique keys 18919 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 18920 final int prefix = name.indexOf('_'); 18921 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 18922 final String output = bits + " " + name; 18923 found.put(key, output); 18924 } 18925} 18926