View.java revision 617feb99a06e7ffb3894e86a286bf30e085f321a
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.Bundle; 44import android.os.Handler; 45import android.os.IBinder; 46import android.os.Parcel; 47import android.os.Parcelable; 48import android.os.RemoteException; 49import android.os.SystemClock; 50import android.os.SystemProperties; 51import android.text.TextUtils; 52import android.util.AttributeSet; 53import android.util.FloatProperty; 54import android.util.LayoutDirection; 55import android.util.Log; 56import android.util.LongSparseLongArray; 57import android.util.Pools.SynchronizedPool; 58import android.util.Property; 59import android.util.SparseArray; 60import android.util.SuperNotCalledException; 61import android.util.TypedValue; 62import android.view.ContextMenu.ContextMenuInfo; 63import android.view.AccessibilityIterators.TextSegmentIterator; 64import android.view.AccessibilityIterators.CharacterTextSegmentIterator; 65import android.view.AccessibilityIterators.WordTextSegmentIterator; 66import android.view.AccessibilityIterators.ParagraphTextSegmentIterator; 67import android.view.accessibility.AccessibilityEvent; 68import android.view.accessibility.AccessibilityEventSource; 69import android.view.accessibility.AccessibilityManager; 70import android.view.accessibility.AccessibilityNodeInfo; 71import android.view.accessibility.AccessibilityNodeProvider; 72import android.view.animation.Animation; 73import android.view.animation.AnimationUtils; 74import android.view.animation.Transformation; 75import android.view.inputmethod.EditorInfo; 76import android.view.inputmethod.InputConnection; 77import android.view.inputmethod.InputMethodManager; 78import android.widget.ScrollBarDrawable; 79 80import static android.os.Build.VERSION_CODES.*; 81import static java.lang.Math.max; 82 83import com.android.internal.R; 84import com.android.internal.util.Predicate; 85import com.android.internal.view.menu.MenuBuilder; 86import com.google.android.collect.Lists; 87import com.google.android.collect.Maps; 88 89import java.lang.ref.WeakReference; 90import java.lang.reflect.Field; 91import java.lang.reflect.InvocationTargetException; 92import java.lang.reflect.Method; 93import java.lang.reflect.Modifier; 94import java.util.ArrayList; 95import java.util.Arrays; 96import java.util.Collections; 97import java.util.HashMap; 98import java.util.Locale; 99import java.util.concurrent.CopyOnWriteArrayList; 100import java.util.concurrent.atomic.AtomicInteger; 101 102/** 103 * <p> 104 * This class represents the basic building block for user interface components. A View 105 * occupies a rectangular area on the screen and is responsible for drawing and 106 * event handling. View is the base class for <em>widgets</em>, which are 107 * used to create interactive UI components (buttons, text fields, etc.). The 108 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 109 * are invisible containers that hold other Views (or other ViewGroups) and define 110 * their layout properties. 111 * </p> 112 * 113 * <div class="special reference"> 114 * <h3>Developer Guides</h3> 115 * <p>For information about using this class to develop your application's user interface, 116 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide. 117 * </div> 118 * 119 * <a name="Using"></a> 120 * <h3>Using Views</h3> 121 * <p> 122 * All of the views in a window are arranged in a single tree. You can add views 123 * either from code or by specifying a tree of views in one or more XML layout 124 * files. There are many specialized subclasses of views that act as controls or 125 * are capable of displaying text, images, or other content. 126 * </p> 127 * <p> 128 * Once you have created a tree of views, there are typically a few types of 129 * common operations you may wish to perform: 130 * <ul> 131 * <li><strong>Set properties:</strong> for example setting the text of a 132 * {@link android.widget.TextView}. The available properties and the methods 133 * that set them will vary among the different subclasses of views. Note that 134 * properties that are known at build time can be set in the XML layout 135 * files.</li> 136 * <li><strong>Set focus:</strong> The framework will handled moving focus in 137 * response to user input. To force focus to a specific view, call 138 * {@link #requestFocus}.</li> 139 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 140 * that will be notified when something interesting happens to the view. For 141 * example, all views will let you set a listener to be notified when the view 142 * gains or loses focus. You can register such a listener using 143 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 144 * Other view subclasses offer more specialized listeners. For example, a Button 145 * exposes a listener to notify clients when the button is clicked.</li> 146 * <li><strong>Set visibility:</strong> You can hide or show views using 147 * {@link #setVisibility(int)}.</li> 148 * </ul> 149 * </p> 150 * <p><em> 151 * Note: The Android framework is responsible for measuring, laying out and 152 * drawing views. You should not call methods that perform these actions on 153 * views yourself unless you are actually implementing a 154 * {@link android.view.ViewGroup}. 155 * </em></p> 156 * 157 * <a name="Lifecycle"></a> 158 * <h3>Implementing a Custom View</h3> 159 * 160 * <p> 161 * To implement a custom view, you will usually begin by providing overrides for 162 * some of the standard methods that the framework calls on all views. You do 163 * not need to override all of these methods. In fact, you can start by just 164 * overriding {@link #onDraw(android.graphics.Canvas)}. 165 * <table border="2" width="85%" align="center" cellpadding="5"> 166 * <thead> 167 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 168 * </thead> 169 * 170 * <tbody> 171 * <tr> 172 * <td rowspan="2">Creation</td> 173 * <td>Constructors</td> 174 * <td>There is a form of the constructor that are called when the view 175 * is created from code and a form that is called when the view is 176 * inflated from a layout file. The second form should parse and apply 177 * any attributes defined in the layout file. 178 * </td> 179 * </tr> 180 * <tr> 181 * <td><code>{@link #onFinishInflate()}</code></td> 182 * <td>Called after a view and all of its children has been inflated 183 * from XML.</td> 184 * </tr> 185 * 186 * <tr> 187 * <td rowspan="3">Layout</td> 188 * <td><code>{@link #onMeasure(int, int)}</code></td> 189 * <td>Called to determine the size requirements for this view and all 190 * of its children. 191 * </td> 192 * </tr> 193 * <tr> 194 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 195 * <td>Called when this view should assign a size and position to all 196 * of its children. 197 * </td> 198 * </tr> 199 * <tr> 200 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 201 * <td>Called when the size of this view has changed. 202 * </td> 203 * </tr> 204 * 205 * <tr> 206 * <td>Drawing</td> 207 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 208 * <td>Called when the view should render its content. 209 * </td> 210 * </tr> 211 * 212 * <tr> 213 * <td rowspan="4">Event processing</td> 214 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 215 * <td>Called when a new hardware key event occurs. 216 * </td> 217 * </tr> 218 * <tr> 219 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 220 * <td>Called when a hardware key up event occurs. 221 * </td> 222 * </tr> 223 * <tr> 224 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 225 * <td>Called when a trackball motion event occurs. 226 * </td> 227 * </tr> 228 * <tr> 229 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 230 * <td>Called when a touch screen motion event occurs. 231 * </td> 232 * </tr> 233 * 234 * <tr> 235 * <td rowspan="2">Focus</td> 236 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 237 * <td>Called when the view gains or loses focus. 238 * </td> 239 * </tr> 240 * 241 * <tr> 242 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 243 * <td>Called when the window containing the view gains or loses focus. 244 * </td> 245 * </tr> 246 * 247 * <tr> 248 * <td rowspan="3">Attaching</td> 249 * <td><code>{@link #onAttachedToWindow()}</code></td> 250 * <td>Called when the view is attached to a window. 251 * </td> 252 * </tr> 253 * 254 * <tr> 255 * <td><code>{@link #onDetachedFromWindow}</code></td> 256 * <td>Called when the view is detached from its window. 257 * </td> 258 * </tr> 259 * 260 * <tr> 261 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 262 * <td>Called when the visibility of the window containing the view 263 * has changed. 264 * </td> 265 * </tr> 266 * </tbody> 267 * 268 * </table> 269 * </p> 270 * 271 * <a name="IDs"></a> 272 * <h3>IDs</h3> 273 * Views may have an integer id associated with them. These ids are typically 274 * assigned in the layout XML files, and are used to find specific views within 275 * the view tree. A common pattern is to: 276 * <ul> 277 * <li>Define a Button in the layout file and assign it a unique ID. 278 * <pre> 279 * <Button 280 * android:id="@+id/my_button" 281 * android:layout_width="wrap_content" 282 * android:layout_height="wrap_content" 283 * android:text="@string/my_button_text"/> 284 * </pre></li> 285 * <li>From the onCreate method of an Activity, find the Button 286 * <pre class="prettyprint"> 287 * Button myButton = (Button) findViewById(R.id.my_button); 288 * </pre></li> 289 * </ul> 290 * <p> 291 * View IDs need not be unique throughout the tree, but it is good practice to 292 * ensure that they are at least unique within the part of the tree you are 293 * searching. 294 * </p> 295 * 296 * <a name="Position"></a> 297 * <h3>Position</h3> 298 * <p> 299 * The geometry of a view is that of a rectangle. A view has a location, 300 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 301 * two dimensions, expressed as a width and a height. The unit for location 302 * and dimensions is the pixel. 303 * </p> 304 * 305 * <p> 306 * It is possible to retrieve the location of a view by invoking the methods 307 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 308 * coordinate of the rectangle representing the view. The latter returns the 309 * top, or Y, coordinate of the rectangle representing the view. These methods 310 * both return the location of the view relative to its parent. For instance, 311 * when getLeft() returns 20, that means the view is located 20 pixels to the 312 * right of the left edge of its direct parent. 313 * </p> 314 * 315 * <p> 316 * In addition, several convenience methods are offered to avoid unnecessary 317 * computations, namely {@link #getRight()} and {@link #getBottom()}. 318 * These methods return the coordinates of the right and bottom edges of the 319 * rectangle representing the view. For instance, calling {@link #getRight()} 320 * is similar to the following computation: <code>getLeft() + getWidth()</code> 321 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 322 * </p> 323 * 324 * <a name="SizePaddingMargins"></a> 325 * <h3>Size, padding and margins</h3> 326 * <p> 327 * The size of a view is expressed with a width and a height. A view actually 328 * possess two pairs of width and height values. 329 * </p> 330 * 331 * <p> 332 * The first pair is known as <em>measured width</em> and 333 * <em>measured height</em>. These dimensions define how big a view wants to be 334 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 335 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 336 * and {@link #getMeasuredHeight()}. 337 * </p> 338 * 339 * <p> 340 * The second pair is simply known as <em>width</em> and <em>height</em>, or 341 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 342 * dimensions define the actual size of the view on screen, at drawing time and 343 * after layout. These values may, but do not have to, be different from the 344 * measured width and height. The width and height can be obtained by calling 345 * {@link #getWidth()} and {@link #getHeight()}. 346 * </p> 347 * 348 * <p> 349 * To measure its dimensions, a view takes into account its padding. The padding 350 * is expressed in pixels for the left, top, right and bottom parts of the view. 351 * Padding can be used to offset the content of the view by a specific amount of 352 * pixels. For instance, a left padding of 2 will push the view's content by 353 * 2 pixels to the right of the left edge. Padding can be set using the 354 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)} 355 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 356 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()}, 357 * {@link #getPaddingEnd()}. 358 * </p> 359 * 360 * <p> 361 * Even though a view can define a padding, it does not provide any support for 362 * margins. However, view groups provide such a support. Refer to 363 * {@link android.view.ViewGroup} and 364 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 365 * </p> 366 * 367 * <a name="Layout"></a> 368 * <h3>Layout</h3> 369 * <p> 370 * Layout is a two pass process: a measure pass and a layout pass. The measuring 371 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 372 * of the view tree. Each view pushes dimension specifications down the tree 373 * during the recursion. At the end of the measure pass, every view has stored 374 * its measurements. The second pass happens in 375 * {@link #layout(int,int,int,int)} and is also top-down. During 376 * this pass each parent is responsible for positioning all of its children 377 * using the sizes computed in the measure pass. 378 * </p> 379 * 380 * <p> 381 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 382 * {@link #getMeasuredHeight()} values must be set, along with those for all of 383 * that view's descendants. A view's measured width and measured height values 384 * must respect the constraints imposed by the view's parents. This guarantees 385 * that at the end of the measure pass, all parents accept all of their 386 * children's measurements. A parent view may call measure() more than once on 387 * its children. For example, the parent may measure each child once with 388 * unspecified dimensions to find out how big they want to be, then call 389 * measure() on them again with actual numbers if the sum of all the children's 390 * unconstrained sizes is too big or too small. 391 * </p> 392 * 393 * <p> 394 * The measure pass uses two classes to communicate dimensions. The 395 * {@link MeasureSpec} class is used by views to tell their parents how they 396 * want to be measured and positioned. The base LayoutParams class just 397 * describes how big the view wants to be for both width and height. For each 398 * dimension, it can specify one of: 399 * <ul> 400 * <li> an exact number 401 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 402 * (minus padding) 403 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 404 * enclose its content (plus padding). 405 * </ul> 406 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 407 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 408 * an X and Y value. 409 * </p> 410 * 411 * <p> 412 * MeasureSpecs are used to push requirements down the tree from parent to 413 * child. A MeasureSpec can be in one of three modes: 414 * <ul> 415 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 416 * of a child view. For example, a LinearLayout may call measure() on its child 417 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 418 * tall the child view wants to be given a width of 240 pixels. 419 * <li>EXACTLY: This is used by the parent to impose an exact size on the 420 * child. The child must use this size, and guarantee that all of its 421 * descendants will fit within this size. 422 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 423 * child. The child must gurantee that it and all of its descendants will fit 424 * within this size. 425 * </ul> 426 * </p> 427 * 428 * <p> 429 * To intiate a layout, call {@link #requestLayout}. This method is typically 430 * called by a view on itself when it believes that is can no longer fit within 431 * its current bounds. 432 * </p> 433 * 434 * <a name="Drawing"></a> 435 * <h3>Drawing</h3> 436 * <p> 437 * Drawing is handled by walking the tree and rendering each view that 438 * intersects the invalid region. Because the tree is traversed in-order, 439 * this means that parents will draw before (i.e., behind) their children, with 440 * siblings drawn in the order they appear in the tree. 441 * If you set a background drawable for a View, then the View will draw it for you 442 * before calling back to its <code>onDraw()</code> method. 443 * </p> 444 * 445 * <p> 446 * Note that the framework will not draw views that are not in the invalid region. 447 * </p> 448 * 449 * <p> 450 * To force a view to draw, call {@link #invalidate()}. 451 * </p> 452 * 453 * <a name="EventHandlingThreading"></a> 454 * <h3>Event Handling and Threading</h3> 455 * <p> 456 * The basic cycle of a view is as follows: 457 * <ol> 458 * <li>An event comes in and is dispatched to the appropriate view. The view 459 * handles the event and notifies any listeners.</li> 460 * <li>If in the course of processing the event, the view's bounds may need 461 * to be changed, the view will call {@link #requestLayout()}.</li> 462 * <li>Similarly, if in the course of processing the event the view's appearance 463 * may need to be changed, the view will call {@link #invalidate()}.</li> 464 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 465 * the framework will take care of measuring, laying out, and drawing the tree 466 * as appropriate.</li> 467 * </ol> 468 * </p> 469 * 470 * <p><em>Note: The entire view tree is single threaded. You must always be on 471 * the UI thread when calling any method on any view.</em> 472 * If you are doing work on other threads and want to update the state of a view 473 * from that thread, you should use a {@link Handler}. 474 * </p> 475 * 476 * <a name="FocusHandling"></a> 477 * <h3>Focus Handling</h3> 478 * <p> 479 * The framework will handle routine focus movement in response to user input. 480 * This includes changing the focus as views are removed or hidden, or as new 481 * views become available. Views indicate their willingness to take focus 482 * through the {@link #isFocusable} method. To change whether a view can take 483 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 484 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 485 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 486 * </p> 487 * <p> 488 * Focus movement is based on an algorithm which finds the nearest neighbor in a 489 * given direction. In rare cases, the default algorithm may not match the 490 * intended behavior of the developer. In these situations, you can provide 491 * explicit overrides by using these XML attributes in the layout file: 492 * <pre> 493 * nextFocusDown 494 * nextFocusLeft 495 * nextFocusRight 496 * nextFocusUp 497 * </pre> 498 * </p> 499 * 500 * 501 * <p> 502 * To get a particular view to take focus, call {@link #requestFocus()}. 503 * </p> 504 * 505 * <a name="TouchMode"></a> 506 * <h3>Touch Mode</h3> 507 * <p> 508 * When a user is navigating a user interface via directional keys such as a D-pad, it is 509 * necessary to give focus to actionable items such as buttons so the user can see 510 * what will take input. If the device has touch capabilities, however, and the user 511 * begins interacting with the interface by touching it, it is no longer necessary to 512 * always highlight, or give focus to, a particular view. This motivates a mode 513 * for interaction named 'touch mode'. 514 * </p> 515 * <p> 516 * For a touch capable device, once the user touches the screen, the device 517 * will enter touch mode. From this point onward, only views for which 518 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 519 * Other views that are touchable, like buttons, will not take focus when touched; they will 520 * only fire the on click listeners. 521 * </p> 522 * <p> 523 * Any time a user hits a directional key, such as a D-pad direction, the view device will 524 * exit touch mode, and find a view to take focus, so that the user may resume interacting 525 * with the user interface without touching the screen again. 526 * </p> 527 * <p> 528 * The touch mode state is maintained across {@link android.app.Activity}s. Call 529 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 530 * </p> 531 * 532 * <a name="Scrolling"></a> 533 * <h3>Scrolling</h3> 534 * <p> 535 * The framework provides basic support for views that wish to internally 536 * scroll their content. This includes keeping track of the X and Y scroll 537 * offset as well as mechanisms for drawing scrollbars. See 538 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 539 * {@link #awakenScrollBars()} for more details. 540 * </p> 541 * 542 * <a name="Tags"></a> 543 * <h3>Tags</h3> 544 * <p> 545 * Unlike IDs, tags are not used to identify views. Tags are essentially an 546 * extra piece of information that can be associated with a view. They are most 547 * often used as a convenience to store data related to views in the views 548 * themselves rather than by putting them in a separate structure. 549 * </p> 550 * 551 * <a name="Properties"></a> 552 * <h3>Properties</h3> 553 * <p> 554 * The View class exposes an {@link #ALPHA} property, as well as several transform-related 555 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are 556 * available both in the {@link Property} form as well as in similarly-named setter/getter 557 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can 558 * be used to set persistent state associated with these rendering-related properties on the view. 559 * The properties and methods can also be used in conjunction with 560 * {@link android.animation.Animator Animator}-based animations, described more in the 561 * <a href="#Animation">Animation</a> section. 562 * </p> 563 * 564 * <a name="Animation"></a> 565 * <h3>Animation</h3> 566 * <p> 567 * Starting with Android 3.0, the preferred way of animating views is to use the 568 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based 569 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and 570 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0 571 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only 572 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class 573 * makes animating these View properties particularly easy and efficient. 574 * </p> 575 * <p> 576 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered. 577 * You can attach an {@link Animation} object to a view using 578 * {@link #setAnimation(Animation)} or 579 * {@link #startAnimation(Animation)}. The animation can alter the scale, 580 * rotation, translation and alpha of a view over time. If the animation is 581 * attached to a view that has children, the animation will affect the entire 582 * subtree rooted by that node. When an animation is started, the framework will 583 * take care of redrawing the appropriate views until the animation completes. 584 * </p> 585 * 586 * <a name="Security"></a> 587 * <h3>Security</h3> 588 * <p> 589 * Sometimes it is essential that an application be able to verify that an action 590 * is being performed with the full knowledge and consent of the user, such as 591 * granting a permission request, making a purchase or clicking on an advertisement. 592 * Unfortunately, a malicious application could try to spoof the user into 593 * performing these actions, unaware, by concealing the intended purpose of the view. 594 * As a remedy, the framework offers a touch filtering mechanism that can be used to 595 * improve the security of views that provide access to sensitive functionality. 596 * </p><p> 597 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 598 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 599 * will discard touches that are received whenever the view's window is obscured by 600 * another visible window. As a result, the view will not receive touches whenever a 601 * toast, dialog or other window appears above the view's window. 602 * </p><p> 603 * For more fine-grained control over security, consider overriding the 604 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 605 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 606 * </p> 607 * 608 * @attr ref android.R.styleable#View_alpha 609 * @attr ref android.R.styleable#View_background 610 * @attr ref android.R.styleable#View_clickable 611 * @attr ref android.R.styleable#View_contentDescription 612 * @attr ref android.R.styleable#View_drawingCacheQuality 613 * @attr ref android.R.styleable#View_duplicateParentState 614 * @attr ref android.R.styleable#View_id 615 * @attr ref android.R.styleable#View_requiresFadingEdge 616 * @attr ref android.R.styleable#View_fadeScrollbars 617 * @attr ref android.R.styleable#View_fadingEdgeLength 618 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 619 * @attr ref android.R.styleable#View_fitsSystemWindows 620 * @attr ref android.R.styleable#View_isScrollContainer 621 * @attr ref android.R.styleable#View_focusable 622 * @attr ref android.R.styleable#View_focusableInTouchMode 623 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 624 * @attr ref android.R.styleable#View_keepScreenOn 625 * @attr ref android.R.styleable#View_layerType 626 * @attr ref android.R.styleable#View_layoutDirection 627 * @attr ref android.R.styleable#View_longClickable 628 * @attr ref android.R.styleable#View_minHeight 629 * @attr ref android.R.styleable#View_minWidth 630 * @attr ref android.R.styleable#View_nextFocusDown 631 * @attr ref android.R.styleable#View_nextFocusLeft 632 * @attr ref android.R.styleable#View_nextFocusRight 633 * @attr ref android.R.styleable#View_nextFocusUp 634 * @attr ref android.R.styleable#View_onClick 635 * @attr ref android.R.styleable#View_padding 636 * @attr ref android.R.styleable#View_paddingBottom 637 * @attr ref android.R.styleable#View_paddingLeft 638 * @attr ref android.R.styleable#View_paddingRight 639 * @attr ref android.R.styleable#View_paddingTop 640 * @attr ref android.R.styleable#View_paddingStart 641 * @attr ref android.R.styleable#View_paddingEnd 642 * @attr ref android.R.styleable#View_saveEnabled 643 * @attr ref android.R.styleable#View_rotation 644 * @attr ref android.R.styleable#View_rotationX 645 * @attr ref android.R.styleable#View_rotationY 646 * @attr ref android.R.styleable#View_scaleX 647 * @attr ref android.R.styleable#View_scaleY 648 * @attr ref android.R.styleable#View_scrollX 649 * @attr ref android.R.styleable#View_scrollY 650 * @attr ref android.R.styleable#View_scrollbarSize 651 * @attr ref android.R.styleable#View_scrollbarStyle 652 * @attr ref android.R.styleable#View_scrollbars 653 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 654 * @attr ref android.R.styleable#View_scrollbarFadeDuration 655 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 656 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 657 * @attr ref android.R.styleable#View_scrollbarThumbVertical 658 * @attr ref android.R.styleable#View_scrollbarTrackVertical 659 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 660 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 661 * @attr ref android.R.styleable#View_soundEffectsEnabled 662 * @attr ref android.R.styleable#View_tag 663 * @attr ref android.R.styleable#View_textAlignment 664 * @attr ref android.R.styleable#View_textDirection 665 * @attr ref android.R.styleable#View_transformPivotX 666 * @attr ref android.R.styleable#View_transformPivotY 667 * @attr ref android.R.styleable#View_translationX 668 * @attr ref android.R.styleable#View_translationY 669 * @attr ref android.R.styleable#View_visibility 670 * 671 * @see android.view.ViewGroup 672 */ 673public class View implements Drawable.Callback, KeyEvent.Callback, 674 AccessibilityEventSource { 675 private static final boolean DBG = false; 676 677 /** 678 * The logging tag used by this class with android.util.Log. 679 */ 680 protected static final String VIEW_LOG_TAG = "View"; 681 682 /** 683 * When set to true, apps will draw debugging information about their layouts. 684 * 685 * @hide 686 */ 687 public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout"; 688 689 /** 690 * Used to mark a View that has no ID. 691 */ 692 public static final int NO_ID = -1; 693 694 private static boolean sUseBrokenMakeMeasureSpec = false; 695 696 /** 697 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 698 * calling setFlags. 699 */ 700 private static final int NOT_FOCUSABLE = 0x00000000; 701 702 /** 703 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 704 * setFlags. 705 */ 706 private static final int FOCUSABLE = 0x00000001; 707 708 /** 709 * Mask for use with setFlags indicating bits used for focus. 710 */ 711 private static final int FOCUSABLE_MASK = 0x00000001; 712 713 /** 714 * This view will adjust its padding to fit sytem windows (e.g. status bar) 715 */ 716 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 717 718 /** 719 * This view is visible. 720 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 721 * android:visibility}. 722 */ 723 public static final int VISIBLE = 0x00000000; 724 725 /** 726 * This view is invisible, but it still takes up space for layout purposes. 727 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 728 * android:visibility}. 729 */ 730 public static final int INVISIBLE = 0x00000004; 731 732 /** 733 * This view is invisible, and it doesn't take any space for layout 734 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 735 * android:visibility}. 736 */ 737 public static final int GONE = 0x00000008; 738 739 /** 740 * Mask for use with setFlags indicating bits used for visibility. 741 * {@hide} 742 */ 743 static final int VISIBILITY_MASK = 0x0000000C; 744 745 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 746 747 /** 748 * This view is enabled. Interpretation varies by subclass. 749 * Use with ENABLED_MASK when calling setFlags. 750 * {@hide} 751 */ 752 static final int ENABLED = 0x00000000; 753 754 /** 755 * This view is disabled. Interpretation varies by subclass. 756 * Use with ENABLED_MASK when calling setFlags. 757 * {@hide} 758 */ 759 static final int DISABLED = 0x00000020; 760 761 /** 762 * Mask for use with setFlags indicating bits used for indicating whether 763 * this view is enabled 764 * {@hide} 765 */ 766 static final int ENABLED_MASK = 0x00000020; 767 768 /** 769 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 770 * called and further optimizations will be performed. It is okay to have 771 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 772 * {@hide} 773 */ 774 static final int WILL_NOT_DRAW = 0x00000080; 775 776 /** 777 * Mask for use with setFlags indicating bits used for indicating whether 778 * this view is will draw 779 * {@hide} 780 */ 781 static final int DRAW_MASK = 0x00000080; 782 783 /** 784 * <p>This view doesn't show scrollbars.</p> 785 * {@hide} 786 */ 787 static final int SCROLLBARS_NONE = 0x00000000; 788 789 /** 790 * <p>This view shows horizontal scrollbars.</p> 791 * {@hide} 792 */ 793 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 794 795 /** 796 * <p>This view shows vertical scrollbars.</p> 797 * {@hide} 798 */ 799 static final int SCROLLBARS_VERTICAL = 0x00000200; 800 801 /** 802 * <p>Mask for use with setFlags indicating bits used for indicating which 803 * scrollbars are enabled.</p> 804 * {@hide} 805 */ 806 static final int SCROLLBARS_MASK = 0x00000300; 807 808 /** 809 * Indicates that the view should filter touches when its window is obscured. 810 * Refer to the class comments for more information about this security feature. 811 * {@hide} 812 */ 813 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 814 815 /** 816 * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate 817 * that they are optional and should be skipped if the window has 818 * requested system UI flags that ignore those insets for layout. 819 */ 820 static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800; 821 822 /** 823 * <p>This view doesn't show fading edges.</p> 824 * {@hide} 825 */ 826 static final int FADING_EDGE_NONE = 0x00000000; 827 828 /** 829 * <p>This view shows horizontal fading edges.</p> 830 * {@hide} 831 */ 832 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 833 834 /** 835 * <p>This view shows vertical fading edges.</p> 836 * {@hide} 837 */ 838 static final int FADING_EDGE_VERTICAL = 0x00002000; 839 840 /** 841 * <p>Mask for use with setFlags indicating bits used for indicating which 842 * fading edges are enabled.</p> 843 * {@hide} 844 */ 845 static final int FADING_EDGE_MASK = 0x00003000; 846 847 /** 848 * <p>Indicates this view can be clicked. When clickable, a View reacts 849 * to clicks by notifying the OnClickListener.<p> 850 * {@hide} 851 */ 852 static final int CLICKABLE = 0x00004000; 853 854 /** 855 * <p>Indicates this view is caching its drawing into a bitmap.</p> 856 * {@hide} 857 */ 858 static final int DRAWING_CACHE_ENABLED = 0x00008000; 859 860 /** 861 * <p>Indicates that no icicle should be saved for this view.<p> 862 * {@hide} 863 */ 864 static final int SAVE_DISABLED = 0x000010000; 865 866 /** 867 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 868 * property.</p> 869 * {@hide} 870 */ 871 static final int SAVE_DISABLED_MASK = 0x000010000; 872 873 /** 874 * <p>Indicates that no drawing cache should ever be created for this view.<p> 875 * {@hide} 876 */ 877 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 878 879 /** 880 * <p>Indicates this view can take / keep focus when int touch mode.</p> 881 * {@hide} 882 */ 883 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 884 885 /** 886 * <p>Enables low quality mode for the drawing cache.</p> 887 */ 888 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 889 890 /** 891 * <p>Enables high quality mode for the drawing cache.</p> 892 */ 893 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 894 895 /** 896 * <p>Enables automatic quality mode for the drawing cache.</p> 897 */ 898 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 899 900 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 901 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 902 }; 903 904 /** 905 * <p>Mask for use with setFlags indicating bits used for the cache 906 * quality property.</p> 907 * {@hide} 908 */ 909 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 910 911 /** 912 * <p> 913 * Indicates this view can be long clicked. When long clickable, a View 914 * reacts to long clicks by notifying the OnLongClickListener or showing a 915 * context menu. 916 * </p> 917 * {@hide} 918 */ 919 static final int LONG_CLICKABLE = 0x00200000; 920 921 /** 922 * <p>Indicates that this view gets its drawable states from its direct parent 923 * and ignores its original internal states.</p> 924 * 925 * @hide 926 */ 927 static final int DUPLICATE_PARENT_STATE = 0x00400000; 928 929 /** 930 * The scrollbar style to display the scrollbars inside the content area, 931 * without increasing the padding. The scrollbars will be overlaid with 932 * translucency on the view's content. 933 */ 934 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 935 936 /** 937 * The scrollbar style to display the scrollbars inside the padded area, 938 * increasing the padding of the view. The scrollbars will not overlap the 939 * content area of the view. 940 */ 941 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 942 943 /** 944 * The scrollbar style to display the scrollbars at the edge of the view, 945 * without increasing the padding. The scrollbars will be overlaid with 946 * translucency. 947 */ 948 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 949 950 /** 951 * The scrollbar style to display the scrollbars at the edge of the view, 952 * increasing the padding of the view. The scrollbars will only overlap the 953 * background, if any. 954 */ 955 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 956 957 /** 958 * Mask to check if the scrollbar style is overlay or inset. 959 * {@hide} 960 */ 961 static final int SCROLLBARS_INSET_MASK = 0x01000000; 962 963 /** 964 * Mask to check if the scrollbar style is inside or outside. 965 * {@hide} 966 */ 967 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 968 969 /** 970 * Mask for scrollbar style. 971 * {@hide} 972 */ 973 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 974 975 /** 976 * View flag indicating that the screen should remain on while the 977 * window containing this view is visible to the user. This effectively 978 * takes care of automatically setting the WindowManager's 979 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 980 */ 981 public static final int KEEP_SCREEN_ON = 0x04000000; 982 983 /** 984 * View flag indicating whether this view should have sound effects enabled 985 * for events such as clicking and touching. 986 */ 987 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 988 989 /** 990 * View flag indicating whether this view should have haptic feedback 991 * enabled for events such as long presses. 992 */ 993 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 994 995 /** 996 * <p>Indicates that the view hierarchy should stop saving state when 997 * it reaches this view. If state saving is initiated immediately at 998 * the view, it will be allowed. 999 * {@hide} 1000 */ 1001 static final int PARENT_SAVE_DISABLED = 0x20000000; 1002 1003 /** 1004 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 1005 * {@hide} 1006 */ 1007 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 1008 1009 /** 1010 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1011 * should add all focusable Views regardless if they are focusable in touch mode. 1012 */ 1013 public static final int FOCUSABLES_ALL = 0x00000000; 1014 1015 /** 1016 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1017 * should add only Views focusable in touch mode. 1018 */ 1019 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1020 1021 /** 1022 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1023 * item. 1024 */ 1025 public static final int FOCUS_BACKWARD = 0x00000001; 1026 1027 /** 1028 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1029 * item. 1030 */ 1031 public static final int FOCUS_FORWARD = 0x00000002; 1032 1033 /** 1034 * Use with {@link #focusSearch(int)}. Move focus to the left. 1035 */ 1036 public static final int FOCUS_LEFT = 0x00000011; 1037 1038 /** 1039 * Use with {@link #focusSearch(int)}. Move focus up. 1040 */ 1041 public static final int FOCUS_UP = 0x00000021; 1042 1043 /** 1044 * Use with {@link #focusSearch(int)}. Move focus to the right. 1045 */ 1046 public static final int FOCUS_RIGHT = 0x00000042; 1047 1048 /** 1049 * Use with {@link #focusSearch(int)}. Move focus down. 1050 */ 1051 public static final int FOCUS_DOWN = 0x00000082; 1052 1053 /** 1054 * Bits of {@link #getMeasuredWidthAndState()} and 1055 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1056 */ 1057 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1058 1059 /** 1060 * Bits of {@link #getMeasuredWidthAndState()} and 1061 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1062 */ 1063 public static final int MEASURED_STATE_MASK = 0xff000000; 1064 1065 /** 1066 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1067 * for functions that combine both width and height into a single int, 1068 * such as {@link #getMeasuredState()} and the childState argument of 1069 * {@link #resolveSizeAndState(int, int, int)}. 1070 */ 1071 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1072 1073 /** 1074 * Bit of {@link #getMeasuredWidthAndState()} and 1075 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1076 * is smaller that the space the view would like to have. 1077 */ 1078 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1079 1080 /** 1081 * Base View state sets 1082 */ 1083 // Singles 1084 /** 1085 * Indicates the view has no states set. States are used with 1086 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1087 * view depending on its state. 1088 * 1089 * @see android.graphics.drawable.Drawable 1090 * @see #getDrawableState() 1091 */ 1092 protected static final int[] EMPTY_STATE_SET; 1093 /** 1094 * Indicates the view is enabled. States are used with 1095 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1096 * view depending on its state. 1097 * 1098 * @see android.graphics.drawable.Drawable 1099 * @see #getDrawableState() 1100 */ 1101 protected static final int[] ENABLED_STATE_SET; 1102 /** 1103 * Indicates the view is focused. States are used with 1104 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1105 * view depending on its state. 1106 * 1107 * @see android.graphics.drawable.Drawable 1108 * @see #getDrawableState() 1109 */ 1110 protected static final int[] FOCUSED_STATE_SET; 1111 /** 1112 * Indicates the view is selected. States are used with 1113 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1114 * view depending on its state. 1115 * 1116 * @see android.graphics.drawable.Drawable 1117 * @see #getDrawableState() 1118 */ 1119 protected static final int[] SELECTED_STATE_SET; 1120 /** 1121 * Indicates the view is pressed. States are used with 1122 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1123 * view depending on its state. 1124 * 1125 * @see android.graphics.drawable.Drawable 1126 * @see #getDrawableState() 1127 */ 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 // for mPrivateFlags: 1579 /** {@hide} */ 1580 static final int PFLAG_WANTS_FOCUS = 0x00000001; 1581 /** {@hide} */ 1582 static final int PFLAG_FOCUSED = 0x00000002; 1583 /** {@hide} */ 1584 static final int PFLAG_SELECTED = 0x00000004; 1585 /** {@hide} */ 1586 static final int PFLAG_IS_ROOT_NAMESPACE = 0x00000008; 1587 /** {@hide} */ 1588 static final int PFLAG_HAS_BOUNDS = 0x00000010; 1589 /** {@hide} */ 1590 static final int PFLAG_DRAWN = 0x00000020; 1591 /** 1592 * When this flag is set, this view is running an animation on behalf of its 1593 * children and should therefore not cancel invalidate requests, even if they 1594 * lie outside of this view's bounds. 1595 * 1596 * {@hide} 1597 */ 1598 static final int PFLAG_DRAW_ANIMATION = 0x00000040; 1599 /** {@hide} */ 1600 static final int PFLAG_SKIP_DRAW = 0x00000080; 1601 /** {@hide} */ 1602 static final int PFLAG_ONLY_DRAWS_BACKGROUND = 0x00000100; 1603 /** {@hide} */ 1604 static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1605 /** {@hide} */ 1606 static final int PFLAG_DRAWABLE_STATE_DIRTY = 0x00000400; 1607 /** {@hide} */ 1608 static final int PFLAG_MEASURED_DIMENSION_SET = 0x00000800; 1609 /** {@hide} */ 1610 static final int PFLAG_FORCE_LAYOUT = 0x00001000; 1611 /** {@hide} */ 1612 static final int PFLAG_LAYOUT_REQUIRED = 0x00002000; 1613 1614 private static final int PFLAG_PRESSED = 0x00004000; 1615 1616 /** {@hide} */ 1617 static final int PFLAG_DRAWING_CACHE_VALID = 0x00008000; 1618 /** 1619 * Flag used to indicate that this view should be drawn once more (and only once 1620 * more) after its animation has completed. 1621 * {@hide} 1622 */ 1623 static final int PFLAG_ANIMATION_STARTED = 0x00010000; 1624 1625 private static final int PFLAG_SAVE_STATE_CALLED = 0x00020000; 1626 1627 /** 1628 * Indicates that the View returned true when onSetAlpha() was called and that 1629 * the alpha must be restored. 1630 * {@hide} 1631 */ 1632 static final int PFLAG_ALPHA_SET = 0x00040000; 1633 1634 /** 1635 * Set by {@link #setScrollContainer(boolean)}. 1636 */ 1637 static final int PFLAG_SCROLL_CONTAINER = 0x00080000; 1638 1639 /** 1640 * Set by {@link #setScrollContainer(boolean)}. 1641 */ 1642 static final int PFLAG_SCROLL_CONTAINER_ADDED = 0x00100000; 1643 1644 /** 1645 * View flag indicating whether this view was invalidated (fully or partially.) 1646 * 1647 * @hide 1648 */ 1649 static final int PFLAG_DIRTY = 0x00200000; 1650 1651 /** 1652 * View flag indicating whether this view was invalidated by an opaque 1653 * invalidate request. 1654 * 1655 * @hide 1656 */ 1657 static final int PFLAG_DIRTY_OPAQUE = 0x00400000; 1658 1659 /** 1660 * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}. 1661 * 1662 * @hide 1663 */ 1664 static final int PFLAG_DIRTY_MASK = 0x00600000; 1665 1666 /** 1667 * Indicates whether the background is opaque. 1668 * 1669 * @hide 1670 */ 1671 static final int PFLAG_OPAQUE_BACKGROUND = 0x00800000; 1672 1673 /** 1674 * Indicates whether the scrollbars are opaque. 1675 * 1676 * @hide 1677 */ 1678 static final int PFLAG_OPAQUE_SCROLLBARS = 0x01000000; 1679 1680 /** 1681 * Indicates whether the view is opaque. 1682 * 1683 * @hide 1684 */ 1685 static final int PFLAG_OPAQUE_MASK = 0x01800000; 1686 1687 /** 1688 * Indicates a prepressed state; 1689 * the short time between ACTION_DOWN and recognizing 1690 * a 'real' press. Prepressed is used to recognize quick taps 1691 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1692 * 1693 * @hide 1694 */ 1695 private static final int PFLAG_PREPRESSED = 0x02000000; 1696 1697 /** 1698 * Indicates whether the view is temporarily detached. 1699 * 1700 * @hide 1701 */ 1702 static final int PFLAG_CANCEL_NEXT_UP_EVENT = 0x04000000; 1703 1704 /** 1705 * Indicates that we should awaken scroll bars once attached 1706 * 1707 * @hide 1708 */ 1709 private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1710 1711 /** 1712 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1713 * @hide 1714 */ 1715 private static final int PFLAG_HOVERED = 0x10000000; 1716 1717 /** 1718 * Indicates that pivotX or pivotY were explicitly set and we should not assume the center 1719 * for transform operations 1720 * 1721 * @hide 1722 */ 1723 private static final int PFLAG_PIVOT_EXPLICITLY_SET = 0x20000000; 1724 1725 /** {@hide} */ 1726 static final int PFLAG_ACTIVATED = 0x40000000; 1727 1728 /** 1729 * Indicates that this view was specifically invalidated, not just dirtied because some 1730 * child view was invalidated. The flag is used to determine when we need to recreate 1731 * a view's display list (as opposed to just returning a reference to its existing 1732 * display list). 1733 * 1734 * @hide 1735 */ 1736 static final int PFLAG_INVALIDATED = 0x80000000; 1737 1738 /** 1739 * Masks for mPrivateFlags2, as generated by dumpFlags(): 1740 * 1741 * -------|-------|-------|-------| 1742 * PFLAG2_TEXT_ALIGNMENT_FLAGS[0] 1743 * PFLAG2_TEXT_DIRECTION_FLAGS[0] 1744 * 1 PFLAG2_DRAG_CAN_ACCEPT 1745 * 1 PFLAG2_DRAG_HOVERED 1746 * 1 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT 1747 * 11 PFLAG2_TEXT_DIRECTION_MASK_SHIFT 1748 * 1 1 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT 1749 * 11 PFLAG2_LAYOUT_DIRECTION_MASK 1750 * 11 1 PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 1751 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL 1752 * 1 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT 1753 * 1 1 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT 1754 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED 1755 * 11 PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK 1756 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[1] 1757 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[2] 1758 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[3] 1759 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[4] 1760 * 1 1 PFLAG2_TEXT_DIRECTION_FLAGS[5] 1761 * 111 PFLAG2_TEXT_DIRECTION_MASK 1762 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED 1763 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT 1764 * 111 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK 1765 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[1] 1766 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[2] 1767 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[3] 1768 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[4] 1769 * 1 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[5] 1770 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[6] 1771 * 111 PFLAG2_TEXT_ALIGNMENT_MASK 1772 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED 1773 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT 1774 * 111 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK 1775 * 11 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK 1776 * 1 PFLAG2_HAS_TRANSIENT_STATE 1777 * 1 PFLAG2_ACCESSIBILITY_FOCUSED 1778 * 1 PFLAG2_ACCESSIBILITY_STATE_CHANGED 1779 * 1 PFLAG2_VIEW_QUICK_REJECTED 1780 * 1 PFLAG2_PADDING_RESOLVED 1781 * -------|-------|-------|-------| 1782 */ 1783 1784 /** 1785 * Indicates that this view has reported that it can accept the current drag's content. 1786 * Cleared when the drag operation concludes. 1787 * @hide 1788 */ 1789 static final int PFLAG2_DRAG_CAN_ACCEPT = 0x00000001; 1790 1791 /** 1792 * Indicates that this view is currently directly under the drag location in a 1793 * drag-and-drop operation involving content that it can accept. Cleared when 1794 * the drag exits the view, or when the drag operation concludes. 1795 * @hide 1796 */ 1797 static final int PFLAG2_DRAG_HOVERED = 0x00000002; 1798 1799 /** 1800 * Horizontal layout direction of this view is from Left to Right. 1801 * Use with {@link #setLayoutDirection}. 1802 */ 1803 public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR; 1804 1805 /** 1806 * Horizontal layout direction of this view is from Right to Left. 1807 * Use with {@link #setLayoutDirection}. 1808 */ 1809 public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL; 1810 1811 /** 1812 * Horizontal layout direction of this view is inherited from its parent. 1813 * Use with {@link #setLayoutDirection}. 1814 */ 1815 public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT; 1816 1817 /** 1818 * Horizontal layout direction of this view is from deduced from the default language 1819 * script for the locale. Use with {@link #setLayoutDirection}. 1820 */ 1821 public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE; 1822 1823 /** 1824 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1825 * @hide 1826 */ 1827 static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2; 1828 1829 /** 1830 * Mask for use with private flags indicating bits used for horizontal layout direction. 1831 * @hide 1832 */ 1833 static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1834 1835 /** 1836 * Indicates whether the view horizontal layout direction has been resolved and drawn to the 1837 * right-to-left direction. 1838 * @hide 1839 */ 1840 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1841 1842 /** 1843 * Indicates whether the view horizontal layout direction has been resolved. 1844 * @hide 1845 */ 1846 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1847 1848 /** 1849 * Mask for use with private flags indicating bits used for resolved horizontal layout direction. 1850 * @hide 1851 */ 1852 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C 1853 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1854 1855 /* 1856 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct 1857 * flag value. 1858 * @hide 1859 */ 1860 private static final int[] LAYOUT_DIRECTION_FLAGS = { 1861 LAYOUT_DIRECTION_LTR, 1862 LAYOUT_DIRECTION_RTL, 1863 LAYOUT_DIRECTION_INHERIT, 1864 LAYOUT_DIRECTION_LOCALE 1865 }; 1866 1867 /** 1868 * Default horizontal layout direction. 1869 */ 1870 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 1871 1872 /** 1873 * Default horizontal layout direction. 1874 * @hide 1875 */ 1876 static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR; 1877 1878 /** 1879 * Indicates that the view is tracking some sort of transient state 1880 * that the app should not need to be aware of, but that the framework 1881 * should take special care to preserve. 1882 * 1883 * @hide 1884 */ 1885 static final int PFLAG2_HAS_TRANSIENT_STATE = 0x1 << 22; 1886 1887 /** 1888 * Text direction is inherited thru {@link ViewGroup} 1889 */ 1890 public static final int TEXT_DIRECTION_INHERIT = 0; 1891 1892 /** 1893 * Text direction is using "first strong algorithm". The first strong directional character 1894 * determines the paragraph direction. If there is no strong directional character, the 1895 * paragraph direction is the view's resolved layout direction. 1896 */ 1897 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 1898 1899 /** 1900 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 1901 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 1902 * If there are neither, the paragraph direction is the view's resolved layout direction. 1903 */ 1904 public static final int TEXT_DIRECTION_ANY_RTL = 2; 1905 1906 /** 1907 * Text direction is forced to LTR. 1908 */ 1909 public static final int TEXT_DIRECTION_LTR = 3; 1910 1911 /** 1912 * Text direction is forced to RTL. 1913 */ 1914 public static final int TEXT_DIRECTION_RTL = 4; 1915 1916 /** 1917 * Text direction is coming from the system Locale. 1918 */ 1919 public static final int TEXT_DIRECTION_LOCALE = 5; 1920 1921 /** 1922 * Default text direction is inherited 1923 */ 1924 private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT; 1925 1926 /** 1927 * Default resolved text direction 1928 * @hide 1929 */ 1930 static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG; 1931 1932 /** 1933 * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED) 1934 * @hide 1935 */ 1936 static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6; 1937 1938 /** 1939 * Mask for use with private flags indicating bits used for text direction. 1940 * @hide 1941 */ 1942 static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007 1943 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 1944 1945 /** 1946 * Array of text direction flags for mapping attribute "textDirection" to correct 1947 * flag value. 1948 * @hide 1949 */ 1950 private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = { 1951 TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1952 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1953 TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1954 TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1955 TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1956 TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT 1957 }; 1958 1959 /** 1960 * Indicates whether the view text direction has been resolved. 1961 * @hide 1962 */ 1963 static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008 1964 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 1965 1966 /** 1967 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1968 * @hide 1969 */ 1970 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10; 1971 1972 /** 1973 * Mask for use with private flags indicating bits used for resolved text direction. 1974 * @hide 1975 */ 1976 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 1977 << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 1978 1979 /** 1980 * Indicates whether the view text direction has been resolved to the "first strong" heuristic. 1981 * @hide 1982 */ 1983 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT = 1984 TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 1985 1986 /* 1987 * Default text alignment. The text alignment of this View is inherited from its parent. 1988 * Use with {@link #setTextAlignment(int)} 1989 */ 1990 public static final int TEXT_ALIGNMENT_INHERIT = 0; 1991 1992 /** 1993 * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL, 1994 * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction. 1995 * 1996 * Use with {@link #setTextAlignment(int)} 1997 */ 1998 public static final int TEXT_ALIGNMENT_GRAVITY = 1; 1999 2000 /** 2001 * Align to the start of the paragraph, e.g. ALIGN_NORMAL. 2002 * 2003 * Use with {@link #setTextAlignment(int)} 2004 */ 2005 public static final int TEXT_ALIGNMENT_TEXT_START = 2; 2006 2007 /** 2008 * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE. 2009 * 2010 * Use with {@link #setTextAlignment(int)} 2011 */ 2012 public static final int TEXT_ALIGNMENT_TEXT_END = 3; 2013 2014 /** 2015 * Center the paragraph, e.g. ALIGN_CENTER. 2016 * 2017 * Use with {@link #setTextAlignment(int)} 2018 */ 2019 public static final int TEXT_ALIGNMENT_CENTER = 4; 2020 2021 /** 2022 * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved 2023 * layoutDirection is LTR, and ALIGN_RIGHT otherwise. 2024 * 2025 * Use with {@link #setTextAlignment(int)} 2026 */ 2027 public static final int TEXT_ALIGNMENT_VIEW_START = 5; 2028 2029 /** 2030 * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved 2031 * layoutDirection is LTR, and ALIGN_LEFT otherwise. 2032 * 2033 * Use with {@link #setTextAlignment(int)} 2034 */ 2035 public static final int TEXT_ALIGNMENT_VIEW_END = 6; 2036 2037 /** 2038 * Default text alignment is inherited 2039 */ 2040 private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2041 2042 /** 2043 * Default resolved text alignment 2044 * @hide 2045 */ 2046 static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2047 2048 /** 2049 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2050 * @hide 2051 */ 2052 static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13; 2053 2054 /** 2055 * Mask for use with private flags indicating bits used for text alignment. 2056 * @hide 2057 */ 2058 static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2059 2060 /** 2061 * Array of text direction flags for mapping attribute "textAlignment" to correct 2062 * flag value. 2063 * @hide 2064 */ 2065 private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = { 2066 TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2067 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2068 TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2069 TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2070 TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2071 TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2072 TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 2073 }; 2074 2075 /** 2076 * Indicates whether the view text alignment has been resolved. 2077 * @hide 2078 */ 2079 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2080 2081 /** 2082 * Bit shift to get the resolved text alignment. 2083 * @hide 2084 */ 2085 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17; 2086 2087 /** 2088 * Mask for use with private flags indicating bits used for text alignment. 2089 * @hide 2090 */ 2091 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 2092 << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2093 2094 /** 2095 * Indicates whether if the view text alignment has been resolved to gravity 2096 */ 2097 private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT = 2098 TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2099 2100 // Accessiblity constants for mPrivateFlags2 2101 2102 /** 2103 * Shift for the bits in {@link #mPrivateFlags2} related to the 2104 * "importantForAccessibility" attribute. 2105 */ 2106 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20; 2107 2108 /** 2109 * Automatically determine whether a view is important for accessibility. 2110 */ 2111 public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000; 2112 2113 /** 2114 * The view is important for accessibility. 2115 */ 2116 public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001; 2117 2118 /** 2119 * The view is not important for accessibility. 2120 */ 2121 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002; 2122 2123 /** 2124 * The default whether the view is important for accessibility. 2125 */ 2126 static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO; 2127 2128 /** 2129 * Mask for obtainig the bits which specify how to determine 2130 * whether a view is important for accessibility. 2131 */ 2132 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO 2133 | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO) 2134 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2135 2136 /** 2137 * Flag indicating whether a view has accessibility focus. 2138 */ 2139 static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000; 2140 2141 /** 2142 * Flag whether the accessibility state of the subtree rooted at this view changed. 2143 */ 2144 static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000; 2145 2146 /** 2147 * Flag indicating whether a view failed the quickReject() check in draw(). This condition 2148 * is used to check whether later changes to the view's transform should invalidate the 2149 * view to force the quickReject test to run again. 2150 */ 2151 static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000; 2152 2153 /** 2154 * Flag indicating that start/end padding has been resolved into left/right padding 2155 * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()} 2156 * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved 2157 * during measurement. In some special cases this is required such as when an adapter-based 2158 * view measures prospective children without attaching them to a window. 2159 */ 2160 static final int PFLAG2_PADDING_RESOLVED = 0x20000000; 2161 2162 /** 2163 * Flag indicating that the start/end drawables has been resolved into left/right ones. 2164 */ 2165 static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000; 2166 2167 /** 2168 * Group of bits indicating that RTL properties resolution is done. 2169 */ 2170 static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED | 2171 PFLAG2_TEXT_DIRECTION_RESOLVED | 2172 PFLAG2_TEXT_ALIGNMENT_RESOLVED | 2173 PFLAG2_PADDING_RESOLVED | 2174 PFLAG2_DRAWABLE_RESOLVED; 2175 2176 // There are a couple of flags left in mPrivateFlags2 2177 2178 /* End of masks for mPrivateFlags2 */ 2179 2180 /* Masks for mPrivateFlags3 */ 2181 2182 /** 2183 * Flag indicating that view has a transform animation set on it. This is used to track whether 2184 * an animation is cleared between successive frames, in order to tell the associated 2185 * DisplayList to clear its animation matrix. 2186 */ 2187 static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1; 2188 2189 /** 2190 * Flag indicating that view has an alpha animation set on it. This is used to track whether an 2191 * animation is cleared between successive frames, in order to tell the associated 2192 * DisplayList to restore its alpha value. 2193 */ 2194 static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2; 2195 2196 /** 2197 * Flag indicating that the view has been through at least one layout since it 2198 * was last attached to a window. 2199 */ 2200 static final int PFLAG3_IS_LAID_OUT = 0x4; 2201 2202 /** 2203 * Flag indicating that a call to measure() was skipped and should be done 2204 * instead when layout() is invoked. 2205 */ 2206 static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8; 2207 2208 /** 2209 * Flag indicating that an overridden method correctly called down to 2210 * the superclass implementation as required by the API spec. 2211 */ 2212 static final int PFLAG3_CALLED_SUPER = 0x10; 2213 2214 2215 /* End of masks for mPrivateFlags3 */ 2216 2217 static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED; 2218 2219 /** 2220 * Always allow a user to over-scroll this view, provided it is a 2221 * view that can scroll. 2222 * 2223 * @see #getOverScrollMode() 2224 * @see #setOverScrollMode(int) 2225 */ 2226 public static final int OVER_SCROLL_ALWAYS = 0; 2227 2228 /** 2229 * Allow a user to over-scroll this view only if the content is large 2230 * enough to meaningfully scroll, provided it is a view that can scroll. 2231 * 2232 * @see #getOverScrollMode() 2233 * @see #setOverScrollMode(int) 2234 */ 2235 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 2236 2237 /** 2238 * Never allow a user to over-scroll this view. 2239 * 2240 * @see #getOverScrollMode() 2241 * @see #setOverScrollMode(int) 2242 */ 2243 public static final int OVER_SCROLL_NEVER = 2; 2244 2245 /** 2246 * Special constant for {@link #setSystemUiVisibility(int)}: View has 2247 * requested the system UI (status bar) to be visible (the default). 2248 * 2249 * @see #setSystemUiVisibility(int) 2250 */ 2251 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 2252 2253 /** 2254 * Flag for {@link #setSystemUiVisibility(int)}: View has requested the 2255 * system UI to enter an unobtrusive "low profile" mode. 2256 * 2257 * <p>This is for use in games, book readers, video players, or any other 2258 * "immersive" application where the usual system chrome is deemed too distracting. 2259 * 2260 * <p>In low profile mode, the status bar and/or navigation icons may dim. 2261 * 2262 * @see #setSystemUiVisibility(int) 2263 */ 2264 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 2265 2266 /** 2267 * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the 2268 * system navigation be temporarily hidden. 2269 * 2270 * <p>This is an even less obtrusive state than that called for by 2271 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 2272 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 2273 * those to disappear. This is useful (in conjunction with the 2274 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 2275 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 2276 * window flags) for displaying content using every last pixel on the display. 2277 * 2278 * <p>There is a limitation: because navigation controls are so important, the least user 2279 * interaction will cause them to reappear immediately. When this happens, both 2280 * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically, 2281 * so that both elements reappear at the same time. 2282 * 2283 * @see #setSystemUiVisibility(int) 2284 */ 2285 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 2286 2287 /** 2288 * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go 2289 * into the normal fullscreen mode so that its content can take over the screen 2290 * while still allowing the user to interact with the application. 2291 * 2292 * <p>This has the same visual effect as 2293 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN 2294 * WindowManager.LayoutParams.FLAG_FULLSCREEN}, 2295 * meaning that non-critical screen decorations (such as the status bar) will be 2296 * hidden while the user is in the View's window, focusing the experience on 2297 * that content. Unlike the window flag, if you are using ActionBar in 2298 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2299 * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also 2300 * hide the action bar. 2301 * 2302 * <p>This approach to going fullscreen is best used over the window flag when 2303 * it is a transient state -- that is, the application does this at certain 2304 * points in its user interaction where it wants to allow the user to focus 2305 * on content, but not as a continuous state. For situations where the application 2306 * would like to simply stay full screen the entire time (such as a game that 2307 * wants to take over the screen), the 2308 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag} 2309 * is usually a better approach. The state set here will be removed by the system 2310 * in various situations (such as the user moving to another application) like 2311 * the other system UI states. 2312 * 2313 * <p>When using this flag, the application should provide some easy facility 2314 * for the user to go out of it. A common example would be in an e-book 2315 * reader, where tapping on the screen brings back whatever screen and UI 2316 * decorations that had been hidden while the user was immersed in reading 2317 * the book. 2318 * 2319 * @see #setSystemUiVisibility(int) 2320 */ 2321 public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004; 2322 2323 /** 2324 * Flag for {@link #setSystemUiVisibility(int)}: When using other layout 2325 * flags, we would like a stable view of the content insets given to 2326 * {@link #fitSystemWindows(Rect)}. This means that the insets seen there 2327 * will always represent the worst case that the application can expect 2328 * as a continuous state. In the stock Android UI this is the space for 2329 * the system bar, nav bar, and status bar, but not more transient elements 2330 * such as an input method. 2331 * 2332 * The stable layout your UI sees is based on the system UI modes you can 2333 * switch to. That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 2334 * then you will get a stable layout for changes of the 2335 * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify 2336 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and 2337 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition 2338 * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} 2339 * with a stable layout. (Note that you should avoid using 2340 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.) 2341 * 2342 * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN} 2343 * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}), 2344 * then a hidden status bar will be considered a "stable" state for purposes 2345 * here. This allows your UI to continually hide the status bar, while still 2346 * using the system UI flags to hide the action bar while still retaining 2347 * a stable layout. Note that changing the window fullscreen flag will never 2348 * provide a stable layout for a clean transition. 2349 * 2350 * <p>If you are using ActionBar in 2351 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2352 * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the 2353 * insets it adds to those given to the application. 2354 */ 2355 public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100; 2356 2357 /** 2358 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2359 * to be layed out as if it has requested 2360 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't. This 2361 * allows it to avoid artifacts when switching in and out of that mode, at 2362 * the expense that some of its user interface may be covered by screen 2363 * decorations when they are shown. You can perform layout of your inner 2364 * UI elements to account for the navigation system UI through the 2365 * {@link #fitSystemWindows(Rect)} method. 2366 */ 2367 public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200; 2368 2369 /** 2370 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2371 * to be layed out as if it has requested 2372 * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't. This 2373 * allows it to avoid artifacts when switching in and out of that mode, at 2374 * the expense that some of its user interface may be covered by screen 2375 * decorations when they are shown. You can perform layout of your inner 2376 * UI elements to account for non-fullscreen system UI through the 2377 * {@link #fitSystemWindows(Rect)} method. 2378 */ 2379 public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400; 2380 2381 /** 2382 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2383 * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation 2384 * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. Use this flag to create an immersive 2385 * experience while also hiding the system bars. If this flag is not set, 2386 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user 2387 * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system 2388 * if the user swipes from the top of the screen. 2389 * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with 2390 * system gestures, such as swiping from the top of the screen. These transient system bars 2391 * will overlay app’s content, may have some degree of transparency, and will automatically 2392 * hide after a short timeout. 2393 * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and 2394 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination 2395 * with one or both of those flags.</p> 2396 */ 2397 public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800; 2398 2399 /** 2400 * Flag for {@link #setSystemUiVisibility(int)}: View would like the status bar to have 2401 * transparency. 2402 * 2403 * <p>The transparency request may be denied if the bar is in another mode with a specific 2404 * style, like {@link #SYSTEM_UI_FLAG_IMMERSIVE immersive mode}. 2405 */ 2406 public static final int SYSTEM_UI_FLAG_TRANSPARENT_STATUS = 0x00001000; 2407 2408 /** 2409 * Flag for {@link #setSystemUiVisibility(int)}: View would like the navigation bar to have 2410 * transparency. 2411 * 2412 * <p>The transparency request may be denied if the bar is in another mode with a specific 2413 * style, like {@link #SYSTEM_UI_FLAG_IMMERSIVE immersive mode}. 2414 */ 2415 public static final int SYSTEM_UI_FLAG_TRANSPARENT_NAVIGATION = 0x00002000; 2416 2417 /** 2418 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 2419 */ 2420 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 2421 2422 /** 2423 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 2424 */ 2425 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 2426 2427 /** 2428 * @hide 2429 * 2430 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2431 * out of the public fields to keep the undefined bits out of the developer's way. 2432 * 2433 * Flag to make the status bar not expandable. Unless you also 2434 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 2435 */ 2436 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 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 notification icons and scrolling ticker text. 2445 */ 2446 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 2447 2448 /** 2449 * @hide 2450 * 2451 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2452 * out of the public fields to keep the undefined bits out of the developer's way. 2453 * 2454 * Flag to disable incoming notification alerts. This will not block 2455 * icons, but it will block sound, vibrating and other visual or aural notifications. 2456 */ 2457 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 2458 2459 /** 2460 * @hide 2461 * 2462 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2463 * out of the public fields to keep the undefined bits out of the developer's way. 2464 * 2465 * Flag to hide only the scrolling ticker. Note that 2466 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 2467 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 2468 */ 2469 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 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 the center system info area. 2478 */ 2479 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 2480 2481 /** 2482 * @hide 2483 * 2484 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2485 * out of the public fields to keep the undefined bits out of the developer's way. 2486 * 2487 * Flag to hide only the home button. Don't use this 2488 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2489 */ 2490 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 2491 2492 /** 2493 * @hide 2494 * 2495 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2496 * out of the public fields to keep the undefined bits out of the developer's way. 2497 * 2498 * Flag to hide only the back button. Don't use this 2499 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2500 */ 2501 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 2502 2503 /** 2504 * @hide 2505 * 2506 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2507 * out of the public fields to keep the undefined bits out of the developer's way. 2508 * 2509 * Flag to hide only the clock. You might use this if your activity has 2510 * its own clock making the status bar's clock redundant. 2511 */ 2512 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 2513 2514 /** 2515 * @hide 2516 * 2517 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2518 * out of the public fields to keep the undefined bits out of the developer's way. 2519 * 2520 * Flag to hide only the recent apps button. Don't use this 2521 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2522 */ 2523 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 2524 2525 /** 2526 * @hide 2527 * 2528 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2529 * out of the public fields to keep the undefined bits out of the developer's way. 2530 * 2531 * Flag to disable the global search gesture. Don't use this 2532 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2533 */ 2534 public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000; 2535 2536 /** 2537 * @hide 2538 * 2539 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2540 * out of the public fields to keep the undefined bits out of the developer's way. 2541 * 2542 * Flag to specify that the status bar is displayed in transient mode. 2543 */ 2544 public static final int STATUS_BAR_TRANSIENT = 0x04000000; 2545 2546 /** 2547 * @hide 2548 * 2549 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2550 * out of the public fields to keep the undefined bits out of the developer's way. 2551 * 2552 * Flag to specify that the navigation bar is displayed in transient mode. 2553 */ 2554 public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000; 2555 2556 /** 2557 * @hide 2558 * 2559 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2560 * out of the public fields to keep the undefined bits out of the developer's way. 2561 * 2562 * Flag to specify that the hidden status bar would like to be shown. 2563 */ 2564 public static final int STATUS_BAR_UNHIDE = 0x10000000; 2565 2566 /** 2567 * @hide 2568 * 2569 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2570 * out of the public fields to keep the undefined bits out of the developer's way. 2571 * 2572 * Flag to specify that the hidden navigation bar would like to be shown. 2573 */ 2574 public static final int NAVIGATION_BAR_UNHIDE = 0x20000000; 2575 2576 /** 2577 * @hide 2578 */ 2579 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF; 2580 2581 /** 2582 * These are the system UI flags that can be cleared by events outside 2583 * of an application. Currently this is just the ability to tap on the 2584 * screen while hiding the navigation bar to have it return. 2585 * @hide 2586 */ 2587 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 2588 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 2589 | SYSTEM_UI_FLAG_FULLSCREEN; 2590 2591 /** 2592 * Flags that can impact the layout in relation to system UI. 2593 */ 2594 public static final int SYSTEM_UI_LAYOUT_FLAGS = 2595 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 2596 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 2597 2598 /** 2599 * Find views that render the specified text. 2600 * 2601 * @see #findViewsWithText(ArrayList, CharSequence, int) 2602 */ 2603 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 2604 2605 /** 2606 * Find find views that contain the specified content description. 2607 * 2608 * @see #findViewsWithText(ArrayList, CharSequence, int) 2609 */ 2610 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 2611 2612 /** 2613 * Find views that contain {@link AccessibilityNodeProvider}. Such 2614 * a View is a root of virtual view hierarchy and may contain the searched 2615 * text. If this flag is set Views with providers are automatically 2616 * added and it is a responsibility of the client to call the APIs of 2617 * the provider to determine whether the virtual tree rooted at this View 2618 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 2619 * represeting the virtual views with this text. 2620 * 2621 * @see #findViewsWithText(ArrayList, CharSequence, int) 2622 * 2623 * @hide 2624 */ 2625 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 2626 2627 /** 2628 * The undefined cursor position. 2629 * 2630 * @hide 2631 */ 2632 public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1; 2633 2634 /** 2635 * Indicates that the screen has changed state and is now off. 2636 * 2637 * @see #onScreenStateChanged(int) 2638 */ 2639 public static final int SCREEN_STATE_OFF = 0x0; 2640 2641 /** 2642 * Indicates that the screen has changed state and is now on. 2643 * 2644 * @see #onScreenStateChanged(int) 2645 */ 2646 public static final int SCREEN_STATE_ON = 0x1; 2647 2648 /** 2649 * Controls the over-scroll mode for this view. 2650 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 2651 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 2652 * and {@link #OVER_SCROLL_NEVER}. 2653 */ 2654 private int mOverScrollMode; 2655 2656 /** 2657 * The parent this view is attached to. 2658 * {@hide} 2659 * 2660 * @see #getParent() 2661 */ 2662 protected ViewParent mParent; 2663 2664 /** 2665 * {@hide} 2666 */ 2667 AttachInfo mAttachInfo; 2668 2669 /** 2670 * {@hide} 2671 */ 2672 @ViewDebug.ExportedProperty(flagMapping = { 2673 @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT, 2674 name = "FORCE_LAYOUT"), 2675 @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED, 2676 name = "LAYOUT_REQUIRED"), 2677 @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID, 2678 name = "DRAWING_CACHE_INVALID", outputIf = false), 2679 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true), 2680 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false), 2681 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 2682 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY") 2683 }) 2684 int mPrivateFlags; 2685 int mPrivateFlags2; 2686 int mPrivateFlags3; 2687 2688 /** 2689 * This view's request for the visibility of the status bar. 2690 * @hide 2691 */ 2692 @ViewDebug.ExportedProperty(flagMapping = { 2693 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 2694 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 2695 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 2696 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2697 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2698 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 2699 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 2700 equals = SYSTEM_UI_FLAG_VISIBLE, 2701 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 2702 }) 2703 int mSystemUiVisibility; 2704 2705 /** 2706 * Reference count for transient state. 2707 * @see #setHasTransientState(boolean) 2708 */ 2709 int mTransientStateCount = 0; 2710 2711 /** 2712 * Count of how many windows this view has been attached to. 2713 */ 2714 int mWindowAttachCount; 2715 2716 /** 2717 * The layout parameters associated with this view and used by the parent 2718 * {@link android.view.ViewGroup} to determine how this view should be 2719 * laid out. 2720 * {@hide} 2721 */ 2722 protected ViewGroup.LayoutParams mLayoutParams; 2723 2724 /** 2725 * The view flags hold various views states. 2726 * {@hide} 2727 */ 2728 @ViewDebug.ExportedProperty 2729 int mViewFlags; 2730 2731 static class TransformationInfo { 2732 /** 2733 * The transform matrix for the View. This transform is calculated internally 2734 * based on the rotation, scaleX, and scaleY properties. The identity matrix 2735 * is used by default. Do *not* use this variable directly; instead call 2736 * getMatrix(), which will automatically recalculate the matrix if necessary 2737 * to get the correct matrix based on the latest rotation and scale properties. 2738 */ 2739 private final Matrix mMatrix = new Matrix(); 2740 2741 /** 2742 * The transform matrix for the View. This transform is calculated internally 2743 * based on the rotation, scaleX, and scaleY properties. The identity matrix 2744 * is used by default. Do *not* use this variable directly; instead call 2745 * getInverseMatrix(), which will automatically recalculate the matrix if necessary 2746 * to get the correct matrix based on the latest rotation and scale properties. 2747 */ 2748 private Matrix mInverseMatrix; 2749 2750 /** 2751 * An internal variable that tracks whether we need to recalculate the 2752 * transform matrix, based on whether the rotation or scaleX/Y properties 2753 * have changed since the matrix was last calculated. 2754 */ 2755 boolean mMatrixDirty = false; 2756 2757 /** 2758 * An internal variable that tracks whether we need to recalculate the 2759 * transform matrix, based on whether the rotation or scaleX/Y properties 2760 * have changed since the matrix was last calculated. 2761 */ 2762 private boolean mInverseMatrixDirty = true; 2763 2764 /** 2765 * A variable that tracks whether we need to recalculate the 2766 * transform matrix, based on whether the rotation or scaleX/Y properties 2767 * have changed since the matrix was last calculated. This variable 2768 * is only valid after a call to updateMatrix() or to a function that 2769 * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix(). 2770 */ 2771 private boolean mMatrixIsIdentity = true; 2772 2773 /** 2774 * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set. 2775 */ 2776 private Camera mCamera = null; 2777 2778 /** 2779 * This matrix is used when computing the matrix for 3D rotations. 2780 */ 2781 private Matrix matrix3D = null; 2782 2783 /** 2784 * These prev values are used to recalculate a centered pivot point when necessary. The 2785 * pivot point is only used in matrix operations (when rotation, scale, or translation are 2786 * set), so thes values are only used then as well. 2787 */ 2788 private int mPrevWidth = -1; 2789 private int mPrevHeight = -1; 2790 2791 /** 2792 * The degrees rotation around the vertical axis through the pivot point. 2793 */ 2794 @ViewDebug.ExportedProperty 2795 float mRotationY = 0f; 2796 2797 /** 2798 * The degrees rotation around the horizontal axis through the pivot point. 2799 */ 2800 @ViewDebug.ExportedProperty 2801 float mRotationX = 0f; 2802 2803 /** 2804 * The degrees rotation around the pivot point. 2805 */ 2806 @ViewDebug.ExportedProperty 2807 float mRotation = 0f; 2808 2809 /** 2810 * The amount of translation of the object away from its left property (post-layout). 2811 */ 2812 @ViewDebug.ExportedProperty 2813 float mTranslationX = 0f; 2814 2815 /** 2816 * The amount of translation of the object away from its top property (post-layout). 2817 */ 2818 @ViewDebug.ExportedProperty 2819 float mTranslationY = 0f; 2820 2821 /** 2822 * The amount of scale in the x direction around the pivot point. A 2823 * value of 1 means no scaling is applied. 2824 */ 2825 @ViewDebug.ExportedProperty 2826 float mScaleX = 1f; 2827 2828 /** 2829 * The amount of scale in the y direction around the pivot point. A 2830 * value of 1 means no scaling is applied. 2831 */ 2832 @ViewDebug.ExportedProperty 2833 float mScaleY = 1f; 2834 2835 /** 2836 * The x location of the point around which the view is rotated and scaled. 2837 */ 2838 @ViewDebug.ExportedProperty 2839 float mPivotX = 0f; 2840 2841 /** 2842 * The y location of the point around which the view is rotated and scaled. 2843 */ 2844 @ViewDebug.ExportedProperty 2845 float mPivotY = 0f; 2846 2847 /** 2848 * The opacity of the View. This is a value from 0 to 1, where 0 means 2849 * completely transparent and 1 means completely opaque. 2850 */ 2851 @ViewDebug.ExportedProperty 2852 float mAlpha = 1f; 2853 } 2854 2855 TransformationInfo mTransformationInfo; 2856 2857 /** 2858 * Current clip bounds. to which all drawing of this view are constrained. 2859 */ 2860 private Rect mClipBounds = null; 2861 2862 private boolean mLastIsOpaque; 2863 2864 /** 2865 * Convenience value to check for float values that are close enough to zero to be considered 2866 * zero. 2867 */ 2868 private static final float NONZERO_EPSILON = .001f; 2869 2870 /** 2871 * The distance in pixels from the left edge of this view's parent 2872 * to the left edge of this view. 2873 * {@hide} 2874 */ 2875 @ViewDebug.ExportedProperty(category = "layout") 2876 protected int mLeft; 2877 /** 2878 * The distance in pixels from the left edge of this view's parent 2879 * to the right edge of this view. 2880 * {@hide} 2881 */ 2882 @ViewDebug.ExportedProperty(category = "layout") 2883 protected int mRight; 2884 /** 2885 * The distance in pixels from the top edge of this view's parent 2886 * to the top edge of this view. 2887 * {@hide} 2888 */ 2889 @ViewDebug.ExportedProperty(category = "layout") 2890 protected int mTop; 2891 /** 2892 * The distance in pixels from the top edge of this view's parent 2893 * to the bottom edge of this view. 2894 * {@hide} 2895 */ 2896 @ViewDebug.ExportedProperty(category = "layout") 2897 protected int mBottom; 2898 2899 /** 2900 * The offset, in pixels, by which the content of this view is scrolled 2901 * horizontally. 2902 * {@hide} 2903 */ 2904 @ViewDebug.ExportedProperty(category = "scrolling") 2905 protected int mScrollX; 2906 /** 2907 * The offset, in pixels, by which the content of this view is scrolled 2908 * vertically. 2909 * {@hide} 2910 */ 2911 @ViewDebug.ExportedProperty(category = "scrolling") 2912 protected int mScrollY; 2913 2914 /** 2915 * The left padding in pixels, that is the distance in pixels between the 2916 * left edge of this view and the left edge of its content. 2917 * {@hide} 2918 */ 2919 @ViewDebug.ExportedProperty(category = "padding") 2920 protected int mPaddingLeft = 0; 2921 /** 2922 * The right padding in pixels, that is the distance in pixels between the 2923 * right edge of this view and the right edge of its content. 2924 * {@hide} 2925 */ 2926 @ViewDebug.ExportedProperty(category = "padding") 2927 protected int mPaddingRight = 0; 2928 /** 2929 * The top padding in pixels, that is the distance in pixels between the 2930 * top edge of this view and the top edge of its content. 2931 * {@hide} 2932 */ 2933 @ViewDebug.ExportedProperty(category = "padding") 2934 protected int mPaddingTop; 2935 /** 2936 * The bottom padding in pixels, that is the distance in pixels between the 2937 * bottom edge of this view and the bottom edge of its content. 2938 * {@hide} 2939 */ 2940 @ViewDebug.ExportedProperty(category = "padding") 2941 protected int mPaddingBottom; 2942 2943 /** 2944 * The layout insets in pixels, that is the distance in pixels between the 2945 * visible edges of this view its bounds. 2946 */ 2947 private Insets mLayoutInsets; 2948 2949 /** 2950 * Briefly describes the view and is primarily used for accessibility support. 2951 */ 2952 private CharSequence mContentDescription; 2953 2954 /** 2955 * Specifies the id of a view for which this view serves as a label for 2956 * accessibility purposes. 2957 */ 2958 private int mLabelForId = View.NO_ID; 2959 2960 /** 2961 * Predicate for matching labeled view id with its label for 2962 * accessibility purposes. 2963 */ 2964 private MatchLabelForPredicate mMatchLabelForPredicate; 2965 2966 /** 2967 * Predicate for matching a view by its id. 2968 */ 2969 private MatchIdPredicate mMatchIdPredicate; 2970 2971 /** 2972 * Cache the paddingRight set by the user to append to the scrollbar's size. 2973 * 2974 * @hide 2975 */ 2976 @ViewDebug.ExportedProperty(category = "padding") 2977 protected int mUserPaddingRight; 2978 2979 /** 2980 * Cache the paddingBottom set by the user to append to the scrollbar's size. 2981 * 2982 * @hide 2983 */ 2984 @ViewDebug.ExportedProperty(category = "padding") 2985 protected int mUserPaddingBottom; 2986 2987 /** 2988 * Cache the paddingLeft set by the user to append to the scrollbar's size. 2989 * 2990 * @hide 2991 */ 2992 @ViewDebug.ExportedProperty(category = "padding") 2993 protected int mUserPaddingLeft; 2994 2995 /** 2996 * Cache the paddingStart set by the user to append to the scrollbar's size. 2997 * 2998 */ 2999 @ViewDebug.ExportedProperty(category = "padding") 3000 int mUserPaddingStart; 3001 3002 /** 3003 * Cache the paddingEnd set by the user to append to the scrollbar's size. 3004 * 3005 */ 3006 @ViewDebug.ExportedProperty(category = "padding") 3007 int mUserPaddingEnd; 3008 3009 /** 3010 * Cache initial left padding. 3011 * 3012 * @hide 3013 */ 3014 int mUserPaddingLeftInitial; 3015 3016 /** 3017 * Cache initial right padding. 3018 * 3019 * @hide 3020 */ 3021 int mUserPaddingRightInitial; 3022 3023 /** 3024 * Default undefined padding 3025 */ 3026 private static final int UNDEFINED_PADDING = Integer.MIN_VALUE; 3027 3028 /** 3029 * @hide 3030 */ 3031 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 3032 /** 3033 * @hide 3034 */ 3035 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 3036 3037 private LongSparseLongArray mMeasureCache; 3038 3039 @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_") 3040 private Drawable mBackground; 3041 3042 private int mBackgroundResource; 3043 private boolean mBackgroundSizeChanged; 3044 3045 static class ListenerInfo { 3046 /** 3047 * Listener used to dispatch focus change events. 3048 * This field should be made private, so it is hidden from the SDK. 3049 * {@hide} 3050 */ 3051 protected OnFocusChangeListener mOnFocusChangeListener; 3052 3053 /** 3054 * Listeners for layout change events. 3055 */ 3056 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 3057 3058 /** 3059 * Listeners for attach events. 3060 */ 3061 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 3062 3063 /** 3064 * Listener used to dispatch click events. 3065 * This field should be made private, so it is hidden from the SDK. 3066 * {@hide} 3067 */ 3068 public OnClickListener mOnClickListener; 3069 3070 /** 3071 * Listener used to dispatch long click events. 3072 * This field should be made private, so it is hidden from the SDK. 3073 * {@hide} 3074 */ 3075 protected OnLongClickListener mOnLongClickListener; 3076 3077 /** 3078 * Listener used to build the context menu. 3079 * This field should be made private, so it is hidden from the SDK. 3080 * {@hide} 3081 */ 3082 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 3083 3084 private OnKeyListener mOnKeyListener; 3085 3086 private OnTouchListener mOnTouchListener; 3087 3088 private OnHoverListener mOnHoverListener; 3089 3090 private OnGenericMotionListener mOnGenericMotionListener; 3091 3092 private OnDragListener mOnDragListener; 3093 3094 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 3095 } 3096 3097 ListenerInfo mListenerInfo; 3098 3099 /** 3100 * The application environment this view lives in. 3101 * This field should be made private, so it is hidden from the SDK. 3102 * {@hide} 3103 */ 3104 protected Context mContext; 3105 3106 private final Resources mResources; 3107 3108 private ScrollabilityCache mScrollCache; 3109 3110 private int[] mDrawableState = null; 3111 3112 /** 3113 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 3114 * the user may specify which view to go to next. 3115 */ 3116 private int mNextFocusLeftId = View.NO_ID; 3117 3118 /** 3119 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 3120 * the user may specify which view to go to next. 3121 */ 3122 private int mNextFocusRightId = View.NO_ID; 3123 3124 /** 3125 * When this view has focus and the next focus is {@link #FOCUS_UP}, 3126 * the user may specify which view to go to next. 3127 */ 3128 private int mNextFocusUpId = View.NO_ID; 3129 3130 /** 3131 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 3132 * the user may specify which view to go to next. 3133 */ 3134 private int mNextFocusDownId = View.NO_ID; 3135 3136 /** 3137 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 3138 * the user may specify which view to go to next. 3139 */ 3140 int mNextFocusForwardId = View.NO_ID; 3141 3142 private CheckForLongPress mPendingCheckForLongPress; 3143 private CheckForTap mPendingCheckForTap = null; 3144 private PerformClick mPerformClick; 3145 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 3146 3147 private UnsetPressedState mUnsetPressedState; 3148 3149 /** 3150 * Whether the long press's action has been invoked. The tap's action is invoked on the 3151 * up event while a long press is invoked as soon as the long press duration is reached, so 3152 * a long press could be performed before the tap is checked, in which case the tap's action 3153 * should not be invoked. 3154 */ 3155 private boolean mHasPerformedLongPress; 3156 3157 /** 3158 * The minimum height of the view. We'll try our best to have the height 3159 * of this view to at least this amount. 3160 */ 3161 @ViewDebug.ExportedProperty(category = "measurement") 3162 private int mMinHeight; 3163 3164 /** 3165 * The minimum width of the view. We'll try our best to have the width 3166 * of this view to at least this amount. 3167 */ 3168 @ViewDebug.ExportedProperty(category = "measurement") 3169 private int mMinWidth; 3170 3171 /** 3172 * The delegate to handle touch events that are physically in this view 3173 * but should be handled by another view. 3174 */ 3175 private TouchDelegate mTouchDelegate = null; 3176 3177 /** 3178 * Solid color to use as a background when creating the drawing cache. Enables 3179 * the cache to use 16 bit bitmaps instead of 32 bit. 3180 */ 3181 private int mDrawingCacheBackgroundColor = 0; 3182 3183 /** 3184 * Special tree observer used when mAttachInfo is null. 3185 */ 3186 private ViewTreeObserver mFloatingTreeObserver; 3187 3188 /** 3189 * Cache the touch slop from the context that created the view. 3190 */ 3191 private int mTouchSlop; 3192 3193 /** 3194 * Object that handles automatic animation of view properties. 3195 */ 3196 private ViewPropertyAnimator mAnimator = null; 3197 3198 /** 3199 * Flag indicating that a drag can cross window boundaries. When 3200 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 3201 * with this flag set, all visible applications will be able to participate 3202 * in the drag operation and receive the dragged content. 3203 * 3204 * @hide 3205 */ 3206 public static final int DRAG_FLAG_GLOBAL = 1; 3207 3208 /** 3209 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 3210 */ 3211 private float mVerticalScrollFactor; 3212 3213 /** 3214 * Position of the vertical scroll bar. 3215 */ 3216 private int mVerticalScrollbarPosition; 3217 3218 /** 3219 * Position the scroll bar at the default position as determined by the system. 3220 */ 3221 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 3222 3223 /** 3224 * Position the scroll bar along the left edge. 3225 */ 3226 public static final int SCROLLBAR_POSITION_LEFT = 1; 3227 3228 /** 3229 * Position the scroll bar along the right edge. 3230 */ 3231 public static final int SCROLLBAR_POSITION_RIGHT = 2; 3232 3233 /** 3234 * Indicates that the view does not have a layer. 3235 * 3236 * @see #getLayerType() 3237 * @see #setLayerType(int, android.graphics.Paint) 3238 * @see #LAYER_TYPE_SOFTWARE 3239 * @see #LAYER_TYPE_HARDWARE 3240 */ 3241 public static final int LAYER_TYPE_NONE = 0; 3242 3243 /** 3244 * <p>Indicates that the view has a software layer. A software layer is backed 3245 * by a bitmap and causes the view to be rendered using Android's software 3246 * rendering pipeline, even if hardware acceleration is enabled.</p> 3247 * 3248 * <p>Software layers have various usages:</p> 3249 * <p>When the application is not using hardware acceleration, a software layer 3250 * is useful to apply a specific color filter and/or blending mode and/or 3251 * translucency to a view and all its children.</p> 3252 * <p>When the application is using hardware acceleration, a software layer 3253 * is useful to render drawing primitives not supported by the hardware 3254 * accelerated pipeline. It can also be used to cache a complex view tree 3255 * into a texture and reduce the complexity of drawing operations. For instance, 3256 * when animating a complex view tree with a translation, a software layer can 3257 * be used to render the view tree only once.</p> 3258 * <p>Software layers should be avoided when the affected view tree updates 3259 * often. Every update will require to re-render the software layer, which can 3260 * potentially be slow (particularly when hardware acceleration is turned on 3261 * since the layer will have to be uploaded into a hardware texture after every 3262 * update.)</p> 3263 * 3264 * @see #getLayerType() 3265 * @see #setLayerType(int, android.graphics.Paint) 3266 * @see #LAYER_TYPE_NONE 3267 * @see #LAYER_TYPE_HARDWARE 3268 */ 3269 public static final int LAYER_TYPE_SOFTWARE = 1; 3270 3271 /** 3272 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 3273 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 3274 * OpenGL hardware) and causes the view to be rendered using Android's hardware 3275 * rendering pipeline, but only if hardware acceleration is turned on for the 3276 * view hierarchy. When hardware acceleration is turned off, hardware layers 3277 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 3278 * 3279 * <p>A hardware layer is useful to apply a specific color filter and/or 3280 * blending mode and/or translucency to a view and all its children.</p> 3281 * <p>A hardware layer can be used to cache a complex view tree into a 3282 * texture and reduce the complexity of drawing operations. For instance, 3283 * when animating a complex view tree with a translation, a hardware layer can 3284 * be used to render the view tree only once.</p> 3285 * <p>A hardware layer can also be used to increase the rendering quality when 3286 * rotation transformations are applied on a view. It can also be used to 3287 * prevent potential clipping issues when applying 3D transforms on a view.</p> 3288 * 3289 * @see #getLayerType() 3290 * @see #setLayerType(int, android.graphics.Paint) 3291 * @see #LAYER_TYPE_NONE 3292 * @see #LAYER_TYPE_SOFTWARE 3293 */ 3294 public static final int LAYER_TYPE_HARDWARE = 2; 3295 3296 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 3297 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 3298 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 3299 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 3300 }) 3301 int mLayerType = LAYER_TYPE_NONE; 3302 Paint mLayerPaint; 3303 Rect mLocalDirtyRect; 3304 private HardwareLayer mHardwareLayer; 3305 3306 /** 3307 * Set to true when drawing cache is enabled and cannot be created. 3308 * 3309 * @hide 3310 */ 3311 public boolean mCachingFailed; 3312 private Bitmap mDrawingCache; 3313 private Bitmap mUnscaledDrawingCache; 3314 3315 DisplayList mDisplayList; 3316 3317 /** 3318 * Set to true when the view is sending hover accessibility events because it 3319 * is the innermost hovered view. 3320 */ 3321 private boolean mSendingHoverAccessibilityEvents; 3322 3323 /** 3324 * Delegate for injecting accessibility functionality. 3325 */ 3326 AccessibilityDelegate mAccessibilityDelegate; 3327 3328 /** 3329 * The view's overlay layer. Developers get a reference to the overlay via getOverlay() 3330 * and add/remove objects to/from the overlay directly through the Overlay methods. 3331 */ 3332 ViewOverlay mOverlay; 3333 3334 /** 3335 * Consistency verifier for debugging purposes. 3336 * @hide 3337 */ 3338 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 3339 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 3340 new InputEventConsistencyVerifier(this, 0) : null; 3341 3342 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); 3343 3344 /** 3345 * Simple constructor to use when creating a view from code. 3346 * 3347 * @param context The Context the view is running in, through which it can 3348 * access the current theme, resources, etc. 3349 */ 3350 public View(Context context) { 3351 mContext = context; 3352 mResources = context != null ? context.getResources() : null; 3353 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 3354 // Set some flags defaults 3355 mPrivateFlags2 = 3356 (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) | 3357 (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) | 3358 (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) | 3359 (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) | 3360 (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) | 3361 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT); 3362 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 3363 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 3364 mUserPaddingStart = UNDEFINED_PADDING; 3365 mUserPaddingEnd = UNDEFINED_PADDING; 3366 3367 if (!sUseBrokenMakeMeasureSpec && context != null && 3368 context.getApplicationInfo().targetSdkVersion <= JELLY_BEAN_MR1) { 3369 // Older apps may need this compatibility hack for measurement. 3370 sUseBrokenMakeMeasureSpec = true; 3371 } 3372 } 3373 3374 /** 3375 * Constructor that is called when inflating a view from XML. This is called 3376 * when a view is being constructed from an XML file, supplying attributes 3377 * that were specified in the XML file. This version uses a default style of 3378 * 0, so the only attribute values applied are those in the Context's Theme 3379 * and the given AttributeSet. 3380 * 3381 * <p> 3382 * The method onFinishInflate() will be called after all children have been 3383 * added. 3384 * 3385 * @param context The Context the view is running in, through which it can 3386 * access the current theme, resources, etc. 3387 * @param attrs The attributes of the XML tag that is inflating the view. 3388 * @see #View(Context, AttributeSet, int) 3389 */ 3390 public View(Context context, AttributeSet attrs) { 3391 this(context, attrs, 0); 3392 } 3393 3394 /** 3395 * Perform inflation from XML and apply a class-specific base style from a 3396 * theme attribute. This constructor of View allows subclasses to use their 3397 * own base style when they are inflating. For example, a Button class's 3398 * constructor would call this version of the super class constructor and 3399 * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this 3400 * allows the theme's button style to modify all of the base view attributes 3401 * (in particular its background) as well as the Button class's attributes. 3402 * 3403 * @param context The Context the view is running in, through which it can 3404 * access the current theme, resources, etc. 3405 * @param attrs The attributes of the XML tag that is inflating the view. 3406 * @param defStyleAttr An attribute in the current theme that contains a 3407 * reference to a style resource that supplies default values for 3408 * the view. Can be 0 to not look for defaults. 3409 * @see #View(Context, AttributeSet) 3410 */ 3411 public View(Context context, AttributeSet attrs, int defStyleAttr) { 3412 this(context, attrs, defStyleAttr, 0); 3413 } 3414 3415 /** 3416 * Perform inflation from XML and apply a class-specific base style from a 3417 * theme attribute or style resource. This constructor of View allows 3418 * subclasses to use their own base style when they are inflating. 3419 * <p> 3420 * When determining the final value of a particular attribute, there are 3421 * four inputs that come into play: 3422 * <ol> 3423 * <li>Any attribute values in the given AttributeSet. 3424 * <li>The style resource specified in the AttributeSet (named "style"). 3425 * <li>The default style specified by <var>defStyleAttr</var>. 3426 * <li>The default style specified by <var>defStyleRes</var>. 3427 * <li>The base values in this theme. 3428 * </ol> 3429 * <p> 3430 * Each of these inputs is considered in-order, with the first listed taking 3431 * precedence over the following ones. In other words, if in the 3432 * AttributeSet you have supplied <code><Button * textColor="#ff000000"></code> 3433 * , then the button's text will <em>always</em> be black, regardless of 3434 * what is specified in any of the styles. 3435 * 3436 * @param context The Context the view is running in, through which it can 3437 * access the current theme, resources, etc. 3438 * @param attrs The attributes of the XML tag that is inflating the view. 3439 * @param defStyleAttr An attribute in the current theme that contains a 3440 * reference to a style resource that supplies default values for 3441 * the view. Can be 0 to not look for defaults. 3442 * @param defStyleRes A resource identifier of a style resource that 3443 * supplies default values for the view, used only if 3444 * defStyleAttr is 0 or can not be found in the theme. Can be 0 3445 * to not look for defaults. 3446 * @see #View(Context, AttributeSet, int) 3447 */ 3448 public View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 3449 this(context); 3450 3451 final TypedArray a = context.obtainStyledAttributes( 3452 attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes); 3453 3454 Drawable background = null; 3455 3456 int leftPadding = -1; 3457 int topPadding = -1; 3458 int rightPadding = -1; 3459 int bottomPadding = -1; 3460 int startPadding = UNDEFINED_PADDING; 3461 int endPadding = UNDEFINED_PADDING; 3462 3463 int padding = -1; 3464 3465 int viewFlagValues = 0; 3466 int viewFlagMasks = 0; 3467 3468 boolean setScrollContainer = false; 3469 3470 int x = 0; 3471 int y = 0; 3472 3473 float tx = 0; 3474 float ty = 0; 3475 float rotation = 0; 3476 float rotationX = 0; 3477 float rotationY = 0; 3478 float sx = 1f; 3479 float sy = 1f; 3480 boolean transformSet = false; 3481 3482 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 3483 int overScrollMode = mOverScrollMode; 3484 boolean initializeScrollbars = false; 3485 3486 boolean leftPaddingDefined = false; 3487 boolean rightPaddingDefined = false; 3488 boolean startPaddingDefined = false; 3489 boolean endPaddingDefined = false; 3490 3491 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3492 3493 final int N = a.getIndexCount(); 3494 for (int i = 0; i < N; i++) { 3495 int attr = a.getIndex(i); 3496 switch (attr) { 3497 case com.android.internal.R.styleable.View_background: 3498 background = a.getDrawable(attr); 3499 break; 3500 case com.android.internal.R.styleable.View_padding: 3501 padding = a.getDimensionPixelSize(attr, -1); 3502 mUserPaddingLeftInitial = padding; 3503 mUserPaddingRightInitial = padding; 3504 leftPaddingDefined = true; 3505 rightPaddingDefined = true; 3506 break; 3507 case com.android.internal.R.styleable.View_paddingLeft: 3508 leftPadding = a.getDimensionPixelSize(attr, -1); 3509 mUserPaddingLeftInitial = leftPadding; 3510 leftPaddingDefined = true; 3511 break; 3512 case com.android.internal.R.styleable.View_paddingTop: 3513 topPadding = a.getDimensionPixelSize(attr, -1); 3514 break; 3515 case com.android.internal.R.styleable.View_paddingRight: 3516 rightPadding = a.getDimensionPixelSize(attr, -1); 3517 mUserPaddingRightInitial = rightPadding; 3518 rightPaddingDefined = true; 3519 break; 3520 case com.android.internal.R.styleable.View_paddingBottom: 3521 bottomPadding = a.getDimensionPixelSize(attr, -1); 3522 break; 3523 case com.android.internal.R.styleable.View_paddingStart: 3524 startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3525 startPaddingDefined = (startPadding != UNDEFINED_PADDING); 3526 break; 3527 case com.android.internal.R.styleable.View_paddingEnd: 3528 endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3529 endPaddingDefined = (endPadding != UNDEFINED_PADDING); 3530 break; 3531 case com.android.internal.R.styleable.View_scrollX: 3532 x = a.getDimensionPixelOffset(attr, 0); 3533 break; 3534 case com.android.internal.R.styleable.View_scrollY: 3535 y = a.getDimensionPixelOffset(attr, 0); 3536 break; 3537 case com.android.internal.R.styleable.View_alpha: 3538 setAlpha(a.getFloat(attr, 1f)); 3539 break; 3540 case com.android.internal.R.styleable.View_transformPivotX: 3541 setPivotX(a.getDimensionPixelOffset(attr, 0)); 3542 break; 3543 case com.android.internal.R.styleable.View_transformPivotY: 3544 setPivotY(a.getDimensionPixelOffset(attr, 0)); 3545 break; 3546 case com.android.internal.R.styleable.View_translationX: 3547 tx = a.getDimensionPixelOffset(attr, 0); 3548 transformSet = true; 3549 break; 3550 case com.android.internal.R.styleable.View_translationY: 3551 ty = a.getDimensionPixelOffset(attr, 0); 3552 transformSet = true; 3553 break; 3554 case com.android.internal.R.styleable.View_rotation: 3555 rotation = a.getFloat(attr, 0); 3556 transformSet = true; 3557 break; 3558 case com.android.internal.R.styleable.View_rotationX: 3559 rotationX = a.getFloat(attr, 0); 3560 transformSet = true; 3561 break; 3562 case com.android.internal.R.styleable.View_rotationY: 3563 rotationY = a.getFloat(attr, 0); 3564 transformSet = true; 3565 break; 3566 case com.android.internal.R.styleable.View_scaleX: 3567 sx = a.getFloat(attr, 1f); 3568 transformSet = true; 3569 break; 3570 case com.android.internal.R.styleable.View_scaleY: 3571 sy = a.getFloat(attr, 1f); 3572 transformSet = true; 3573 break; 3574 case com.android.internal.R.styleable.View_id: 3575 mID = a.getResourceId(attr, NO_ID); 3576 break; 3577 case com.android.internal.R.styleable.View_tag: 3578 mTag = a.getText(attr); 3579 break; 3580 case com.android.internal.R.styleable.View_fitsSystemWindows: 3581 if (a.getBoolean(attr, false)) { 3582 viewFlagValues |= FITS_SYSTEM_WINDOWS; 3583 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 3584 } 3585 break; 3586 case com.android.internal.R.styleable.View_focusable: 3587 if (a.getBoolean(attr, false)) { 3588 viewFlagValues |= FOCUSABLE; 3589 viewFlagMasks |= FOCUSABLE_MASK; 3590 } 3591 break; 3592 case com.android.internal.R.styleable.View_focusableInTouchMode: 3593 if (a.getBoolean(attr, false)) { 3594 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 3595 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 3596 } 3597 break; 3598 case com.android.internal.R.styleable.View_clickable: 3599 if (a.getBoolean(attr, false)) { 3600 viewFlagValues |= CLICKABLE; 3601 viewFlagMasks |= CLICKABLE; 3602 } 3603 break; 3604 case com.android.internal.R.styleable.View_longClickable: 3605 if (a.getBoolean(attr, false)) { 3606 viewFlagValues |= LONG_CLICKABLE; 3607 viewFlagMasks |= LONG_CLICKABLE; 3608 } 3609 break; 3610 case com.android.internal.R.styleable.View_saveEnabled: 3611 if (!a.getBoolean(attr, true)) { 3612 viewFlagValues |= SAVE_DISABLED; 3613 viewFlagMasks |= SAVE_DISABLED_MASK; 3614 } 3615 break; 3616 case com.android.internal.R.styleable.View_duplicateParentState: 3617 if (a.getBoolean(attr, false)) { 3618 viewFlagValues |= DUPLICATE_PARENT_STATE; 3619 viewFlagMasks |= DUPLICATE_PARENT_STATE; 3620 } 3621 break; 3622 case com.android.internal.R.styleable.View_visibility: 3623 final int visibility = a.getInt(attr, 0); 3624 if (visibility != 0) { 3625 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 3626 viewFlagMasks |= VISIBILITY_MASK; 3627 } 3628 break; 3629 case com.android.internal.R.styleable.View_layoutDirection: 3630 // Clear any layout direction flags (included resolved bits) already set 3631 mPrivateFlags2 &= 3632 ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK); 3633 // Set the layout direction flags depending on the value of the attribute 3634 final int layoutDirection = a.getInt(attr, -1); 3635 final int value = (layoutDirection != -1) ? 3636 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 3637 mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT); 3638 break; 3639 case com.android.internal.R.styleable.View_drawingCacheQuality: 3640 final int cacheQuality = a.getInt(attr, 0); 3641 if (cacheQuality != 0) { 3642 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 3643 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 3644 } 3645 break; 3646 case com.android.internal.R.styleable.View_contentDescription: 3647 setContentDescription(a.getString(attr)); 3648 break; 3649 case com.android.internal.R.styleable.View_labelFor: 3650 setLabelFor(a.getResourceId(attr, NO_ID)); 3651 break; 3652 case com.android.internal.R.styleable.View_soundEffectsEnabled: 3653 if (!a.getBoolean(attr, true)) { 3654 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 3655 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 3656 } 3657 break; 3658 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 3659 if (!a.getBoolean(attr, true)) { 3660 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 3661 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 3662 } 3663 break; 3664 case R.styleable.View_scrollbars: 3665 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 3666 if (scrollbars != SCROLLBARS_NONE) { 3667 viewFlagValues |= scrollbars; 3668 viewFlagMasks |= SCROLLBARS_MASK; 3669 initializeScrollbars = true; 3670 } 3671 break; 3672 //noinspection deprecation 3673 case R.styleable.View_fadingEdge: 3674 if (targetSdkVersion >= ICE_CREAM_SANDWICH) { 3675 // Ignore the attribute starting with ICS 3676 break; 3677 } 3678 // With builds < ICS, fall through and apply fading edges 3679 case R.styleable.View_requiresFadingEdge: 3680 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 3681 if (fadingEdge != FADING_EDGE_NONE) { 3682 viewFlagValues |= fadingEdge; 3683 viewFlagMasks |= FADING_EDGE_MASK; 3684 initializeFadingEdge(a); 3685 } 3686 break; 3687 case R.styleable.View_scrollbarStyle: 3688 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 3689 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3690 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 3691 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 3692 } 3693 break; 3694 case R.styleable.View_isScrollContainer: 3695 setScrollContainer = true; 3696 if (a.getBoolean(attr, false)) { 3697 setScrollContainer(true); 3698 } 3699 break; 3700 case com.android.internal.R.styleable.View_keepScreenOn: 3701 if (a.getBoolean(attr, false)) { 3702 viewFlagValues |= KEEP_SCREEN_ON; 3703 viewFlagMasks |= KEEP_SCREEN_ON; 3704 } 3705 break; 3706 case R.styleable.View_filterTouchesWhenObscured: 3707 if (a.getBoolean(attr, false)) { 3708 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 3709 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 3710 } 3711 break; 3712 case R.styleable.View_nextFocusLeft: 3713 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 3714 break; 3715 case R.styleable.View_nextFocusRight: 3716 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 3717 break; 3718 case R.styleable.View_nextFocusUp: 3719 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 3720 break; 3721 case R.styleable.View_nextFocusDown: 3722 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 3723 break; 3724 case R.styleable.View_nextFocusForward: 3725 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 3726 break; 3727 case R.styleable.View_minWidth: 3728 mMinWidth = a.getDimensionPixelSize(attr, 0); 3729 break; 3730 case R.styleable.View_minHeight: 3731 mMinHeight = a.getDimensionPixelSize(attr, 0); 3732 break; 3733 case R.styleable.View_onClick: 3734 if (context.isRestricted()) { 3735 throw new IllegalStateException("The android:onClick attribute cannot " 3736 + "be used within a restricted context"); 3737 } 3738 3739 final String handlerName = a.getString(attr); 3740 if (handlerName != null) { 3741 setOnClickListener(new OnClickListener() { 3742 private Method mHandler; 3743 3744 public void onClick(View v) { 3745 if (mHandler == null) { 3746 try { 3747 mHandler = getContext().getClass().getMethod(handlerName, 3748 View.class); 3749 } catch (NoSuchMethodException e) { 3750 int id = getId(); 3751 String idText = id == NO_ID ? "" : " with id '" 3752 + getContext().getResources().getResourceEntryName( 3753 id) + "'"; 3754 throw new IllegalStateException("Could not find a method " + 3755 handlerName + "(View) in the activity " 3756 + getContext().getClass() + " for onClick handler" 3757 + " on view " + View.this.getClass() + idText, e); 3758 } 3759 } 3760 3761 try { 3762 mHandler.invoke(getContext(), View.this); 3763 } catch (IllegalAccessException e) { 3764 throw new IllegalStateException("Could not execute non " 3765 + "public method of the activity", e); 3766 } catch (InvocationTargetException e) { 3767 throw new IllegalStateException("Could not execute " 3768 + "method of the activity", e); 3769 } 3770 } 3771 }); 3772 } 3773 break; 3774 case R.styleable.View_overScrollMode: 3775 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 3776 break; 3777 case R.styleable.View_verticalScrollbarPosition: 3778 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 3779 break; 3780 case R.styleable.View_layerType: 3781 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 3782 break; 3783 case R.styleable.View_textDirection: 3784 // Clear any text direction flag already set 3785 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 3786 // Set the text direction flags depending on the value of the attribute 3787 final int textDirection = a.getInt(attr, -1); 3788 if (textDirection != -1) { 3789 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection]; 3790 } 3791 break; 3792 case R.styleable.View_textAlignment: 3793 // Clear any text alignment flag already set 3794 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 3795 // Set the text alignment flag depending on the value of the attribute 3796 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); 3797 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment]; 3798 break; 3799 case R.styleable.View_importantForAccessibility: 3800 setImportantForAccessibility(a.getInt(attr, 3801 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); 3802 break; 3803 } 3804 } 3805 3806 setOverScrollMode(overScrollMode); 3807 3808 // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet 3809 // the resolved layout direction). Those cached values will be used later during padding 3810 // resolution. 3811 mUserPaddingStart = startPadding; 3812 mUserPaddingEnd = endPadding; 3813 3814 if (background != null) { 3815 setBackground(background); 3816 } 3817 3818 if (padding >= 0) { 3819 leftPadding = padding; 3820 topPadding = padding; 3821 rightPadding = padding; 3822 bottomPadding = padding; 3823 mUserPaddingLeftInitial = padding; 3824 mUserPaddingRightInitial = padding; 3825 } 3826 3827 if (isRtlCompatibilityMode()) { 3828 // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case. 3829 // left / right padding are used if defined (meaning here nothing to do). If they are not 3830 // defined and start / end padding are defined (e.g. in Frameworks resources), then we use 3831 // start / end and resolve them as left / right (layout direction is not taken into account). 3832 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 3833 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 3834 // defined. 3835 if (!leftPaddingDefined && startPaddingDefined) { 3836 leftPadding = startPadding; 3837 } 3838 mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial; 3839 if (!rightPaddingDefined && endPaddingDefined) { 3840 rightPadding = endPadding; 3841 } 3842 mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial; 3843 } else { 3844 // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right 3845 // values defined. Otherwise, left /right values are used. 3846 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 3847 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 3848 // defined. 3849 final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined; 3850 3851 if (leftPaddingDefined && !hasRelativePadding) { 3852 mUserPaddingLeftInitial = leftPadding; 3853 } 3854 if (rightPaddingDefined && !hasRelativePadding) { 3855 mUserPaddingRightInitial = rightPadding; 3856 } 3857 } 3858 3859 internalSetPadding( 3860 mUserPaddingLeftInitial, 3861 topPadding >= 0 ? topPadding : mPaddingTop, 3862 mUserPaddingRightInitial, 3863 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 3864 3865 if (viewFlagMasks != 0) { 3866 setFlags(viewFlagValues, viewFlagMasks); 3867 } 3868 3869 if (initializeScrollbars) { 3870 initializeScrollbars(a); 3871 } 3872 3873 a.recycle(); 3874 3875 // Needs to be called after mViewFlags is set 3876 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3877 recomputePadding(); 3878 } 3879 3880 if (x != 0 || y != 0) { 3881 scrollTo(x, y); 3882 } 3883 3884 if (transformSet) { 3885 setTranslationX(tx); 3886 setTranslationY(ty); 3887 setRotation(rotation); 3888 setRotationX(rotationX); 3889 setRotationY(rotationY); 3890 setScaleX(sx); 3891 setScaleY(sy); 3892 } 3893 3894 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 3895 setScrollContainer(true); 3896 } 3897 3898 computeOpaqueFlags(); 3899 } 3900 3901 /** 3902 * Non-public constructor for use in testing 3903 */ 3904 View() { 3905 mResources = null; 3906 } 3907 3908 public String toString() { 3909 StringBuilder out = new StringBuilder(128); 3910 out.append(getClass().getName()); 3911 out.append('{'); 3912 out.append(Integer.toHexString(System.identityHashCode(this))); 3913 out.append(' '); 3914 switch (mViewFlags&VISIBILITY_MASK) { 3915 case VISIBLE: out.append('V'); break; 3916 case INVISIBLE: out.append('I'); break; 3917 case GONE: out.append('G'); break; 3918 default: out.append('.'); break; 3919 } 3920 out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.'); 3921 out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.'); 3922 out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D'); 3923 out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.'); 3924 out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.'); 3925 out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.'); 3926 out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.'); 3927 out.append(' '); 3928 out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.'); 3929 out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.'); 3930 out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.'); 3931 if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) { 3932 out.append('p'); 3933 } else { 3934 out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.'); 3935 } 3936 out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.'); 3937 out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.'); 3938 out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.'); 3939 out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.'); 3940 out.append(' '); 3941 out.append(mLeft); 3942 out.append(','); 3943 out.append(mTop); 3944 out.append('-'); 3945 out.append(mRight); 3946 out.append(','); 3947 out.append(mBottom); 3948 final int id = getId(); 3949 if (id != NO_ID) { 3950 out.append(" #"); 3951 out.append(Integer.toHexString(id)); 3952 final Resources r = mResources; 3953 if (id != 0 && r != null) { 3954 try { 3955 String pkgname; 3956 switch (id&0xff000000) { 3957 case 0x7f000000: 3958 pkgname="app"; 3959 break; 3960 case 0x01000000: 3961 pkgname="android"; 3962 break; 3963 default: 3964 pkgname = r.getResourcePackageName(id); 3965 break; 3966 } 3967 String typename = r.getResourceTypeName(id); 3968 String entryname = r.getResourceEntryName(id); 3969 out.append(" "); 3970 out.append(pkgname); 3971 out.append(":"); 3972 out.append(typename); 3973 out.append("/"); 3974 out.append(entryname); 3975 } catch (Resources.NotFoundException e) { 3976 } 3977 } 3978 } 3979 out.append("}"); 3980 return out.toString(); 3981 } 3982 3983 /** 3984 * <p> 3985 * Initializes the fading edges from a given set of styled attributes. This 3986 * method should be called by subclasses that need fading edges and when an 3987 * instance of these subclasses is created programmatically rather than 3988 * being inflated from XML. This method is automatically called when the XML 3989 * is inflated. 3990 * </p> 3991 * 3992 * @param a the styled attributes set to initialize the fading edges from 3993 */ 3994 protected void initializeFadingEdge(TypedArray a) { 3995 initScrollCache(); 3996 3997 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 3998 R.styleable.View_fadingEdgeLength, 3999 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 4000 } 4001 4002 /** 4003 * Returns the size of the vertical faded edges used to indicate that more 4004 * content in this view is visible. 4005 * 4006 * @return The size in pixels of the vertical faded edge or 0 if vertical 4007 * faded edges are not enabled for this view. 4008 * @attr ref android.R.styleable#View_fadingEdgeLength 4009 */ 4010 public int getVerticalFadingEdgeLength() { 4011 if (isVerticalFadingEdgeEnabled()) { 4012 ScrollabilityCache cache = mScrollCache; 4013 if (cache != null) { 4014 return cache.fadingEdgeLength; 4015 } 4016 } 4017 return 0; 4018 } 4019 4020 /** 4021 * Set the size of the faded edge used to indicate that more content in this 4022 * view is available. Will not change whether the fading edge is enabled; use 4023 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 4024 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 4025 * for the vertical or horizontal fading edges. 4026 * 4027 * @param length The size in pixels of the faded edge used to indicate that more 4028 * content in this view is visible. 4029 */ 4030 public void setFadingEdgeLength(int length) { 4031 initScrollCache(); 4032 mScrollCache.fadingEdgeLength = length; 4033 } 4034 4035 /** 4036 * Returns the size of the horizontal faded edges used to indicate that more 4037 * content in this view is visible. 4038 * 4039 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 4040 * faded edges are not enabled for this view. 4041 * @attr ref android.R.styleable#View_fadingEdgeLength 4042 */ 4043 public int getHorizontalFadingEdgeLength() { 4044 if (isHorizontalFadingEdgeEnabled()) { 4045 ScrollabilityCache cache = mScrollCache; 4046 if (cache != null) { 4047 return cache.fadingEdgeLength; 4048 } 4049 } 4050 return 0; 4051 } 4052 4053 /** 4054 * Returns the width of the vertical scrollbar. 4055 * 4056 * @return The width in pixels of the vertical scrollbar or 0 if there 4057 * is no vertical scrollbar. 4058 */ 4059 public int getVerticalScrollbarWidth() { 4060 ScrollabilityCache cache = mScrollCache; 4061 if (cache != null) { 4062 ScrollBarDrawable scrollBar = cache.scrollBar; 4063 if (scrollBar != null) { 4064 int size = scrollBar.getSize(true); 4065 if (size <= 0) { 4066 size = cache.scrollBarSize; 4067 } 4068 return size; 4069 } 4070 return 0; 4071 } 4072 return 0; 4073 } 4074 4075 /** 4076 * Returns the height of the horizontal scrollbar. 4077 * 4078 * @return The height in pixels of the horizontal scrollbar or 0 if 4079 * there is no horizontal scrollbar. 4080 */ 4081 protected int getHorizontalScrollbarHeight() { 4082 ScrollabilityCache cache = mScrollCache; 4083 if (cache != null) { 4084 ScrollBarDrawable scrollBar = cache.scrollBar; 4085 if (scrollBar != null) { 4086 int size = scrollBar.getSize(false); 4087 if (size <= 0) { 4088 size = cache.scrollBarSize; 4089 } 4090 return size; 4091 } 4092 return 0; 4093 } 4094 return 0; 4095 } 4096 4097 /** 4098 * <p> 4099 * Initializes the scrollbars from a given set of styled attributes. This 4100 * method should be called by subclasses that need scrollbars and when an 4101 * instance of these subclasses is created programmatically rather than 4102 * being inflated from XML. This method is automatically called when the XML 4103 * is inflated. 4104 * </p> 4105 * 4106 * @param a the styled attributes set to initialize the scrollbars from 4107 */ 4108 protected void initializeScrollbars(TypedArray a) { 4109 initScrollCache(); 4110 4111 final ScrollabilityCache scrollabilityCache = mScrollCache; 4112 4113 if (scrollabilityCache.scrollBar == null) { 4114 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 4115 } 4116 4117 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 4118 4119 if (!fadeScrollbars) { 4120 scrollabilityCache.state = ScrollabilityCache.ON; 4121 } 4122 scrollabilityCache.fadeScrollBars = fadeScrollbars; 4123 4124 4125 scrollabilityCache.scrollBarFadeDuration = a.getInt( 4126 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 4127 .getScrollBarFadeDuration()); 4128 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 4129 R.styleable.View_scrollbarDefaultDelayBeforeFade, 4130 ViewConfiguration.getScrollDefaultDelay()); 4131 4132 4133 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 4134 com.android.internal.R.styleable.View_scrollbarSize, 4135 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 4136 4137 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 4138 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 4139 4140 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 4141 if (thumb != null) { 4142 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 4143 } 4144 4145 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 4146 false); 4147 if (alwaysDraw) { 4148 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 4149 } 4150 4151 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 4152 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 4153 4154 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 4155 if (thumb != null) { 4156 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 4157 } 4158 4159 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 4160 false); 4161 if (alwaysDraw) { 4162 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 4163 } 4164 4165 // Apply layout direction to the new Drawables if needed 4166 final int layoutDirection = getLayoutDirection(); 4167 if (track != null) { 4168 track.setLayoutDirection(layoutDirection); 4169 } 4170 if (thumb != null) { 4171 thumb.setLayoutDirection(layoutDirection); 4172 } 4173 4174 // Re-apply user/background padding so that scrollbar(s) get added 4175 resolvePadding(); 4176 } 4177 4178 /** 4179 * <p> 4180 * Initalizes the scrollability cache if necessary. 4181 * </p> 4182 */ 4183 private void initScrollCache() { 4184 if (mScrollCache == null) { 4185 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 4186 } 4187 } 4188 4189 private ScrollabilityCache getScrollCache() { 4190 initScrollCache(); 4191 return mScrollCache; 4192 } 4193 4194 /** 4195 * Set the position of the vertical scroll bar. Should be one of 4196 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 4197 * {@link #SCROLLBAR_POSITION_RIGHT}. 4198 * 4199 * @param position Where the vertical scroll bar should be positioned. 4200 */ 4201 public void setVerticalScrollbarPosition(int position) { 4202 if (mVerticalScrollbarPosition != position) { 4203 mVerticalScrollbarPosition = position; 4204 computeOpaqueFlags(); 4205 resolvePadding(); 4206 } 4207 } 4208 4209 /** 4210 * @return The position where the vertical scroll bar will show, if applicable. 4211 * @see #setVerticalScrollbarPosition(int) 4212 */ 4213 public int getVerticalScrollbarPosition() { 4214 return mVerticalScrollbarPosition; 4215 } 4216 4217 ListenerInfo getListenerInfo() { 4218 if (mListenerInfo != null) { 4219 return mListenerInfo; 4220 } 4221 mListenerInfo = new ListenerInfo(); 4222 return mListenerInfo; 4223 } 4224 4225 /** 4226 * Register a callback to be invoked when focus of this view changed. 4227 * 4228 * @param l The callback that will run. 4229 */ 4230 public void setOnFocusChangeListener(OnFocusChangeListener l) { 4231 getListenerInfo().mOnFocusChangeListener = l; 4232 } 4233 4234 /** 4235 * Add a listener that will be called when the bounds of the view change due to 4236 * layout processing. 4237 * 4238 * @param listener The listener that will be called when layout bounds change. 4239 */ 4240 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 4241 ListenerInfo li = getListenerInfo(); 4242 if (li.mOnLayoutChangeListeners == null) { 4243 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 4244 } 4245 if (!li.mOnLayoutChangeListeners.contains(listener)) { 4246 li.mOnLayoutChangeListeners.add(listener); 4247 } 4248 } 4249 4250 /** 4251 * Remove a listener for layout changes. 4252 * 4253 * @param listener The listener for layout bounds change. 4254 */ 4255 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 4256 ListenerInfo li = mListenerInfo; 4257 if (li == null || li.mOnLayoutChangeListeners == null) { 4258 return; 4259 } 4260 li.mOnLayoutChangeListeners.remove(listener); 4261 } 4262 4263 /** 4264 * Add a listener for attach state changes. 4265 * 4266 * This listener will be called whenever this view is attached or detached 4267 * from a window. Remove the listener using 4268 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 4269 * 4270 * @param listener Listener to attach 4271 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 4272 */ 4273 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4274 ListenerInfo li = getListenerInfo(); 4275 if (li.mOnAttachStateChangeListeners == null) { 4276 li.mOnAttachStateChangeListeners 4277 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 4278 } 4279 li.mOnAttachStateChangeListeners.add(listener); 4280 } 4281 4282 /** 4283 * Remove a listener for attach state changes. The listener will receive no further 4284 * notification of window attach/detach events. 4285 * 4286 * @param listener Listener to remove 4287 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 4288 */ 4289 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4290 ListenerInfo li = mListenerInfo; 4291 if (li == null || li.mOnAttachStateChangeListeners == null) { 4292 return; 4293 } 4294 li.mOnAttachStateChangeListeners.remove(listener); 4295 } 4296 4297 /** 4298 * Returns the focus-change callback registered for this view. 4299 * 4300 * @return The callback, or null if one is not registered. 4301 */ 4302 public OnFocusChangeListener getOnFocusChangeListener() { 4303 ListenerInfo li = mListenerInfo; 4304 return li != null ? li.mOnFocusChangeListener : null; 4305 } 4306 4307 /** 4308 * Register a callback to be invoked when this view is clicked. If this view is not 4309 * clickable, it becomes clickable. 4310 * 4311 * @param l The callback that will run 4312 * 4313 * @see #setClickable(boolean) 4314 */ 4315 public void setOnClickListener(OnClickListener l) { 4316 if (!isClickable()) { 4317 setClickable(true); 4318 } 4319 getListenerInfo().mOnClickListener = l; 4320 } 4321 4322 /** 4323 * Return whether this view has an attached OnClickListener. Returns 4324 * true if there is a listener, false if there is none. 4325 */ 4326 public boolean hasOnClickListeners() { 4327 ListenerInfo li = mListenerInfo; 4328 return (li != null && li.mOnClickListener != null); 4329 } 4330 4331 /** 4332 * Register a callback to be invoked when this view is clicked and held. If this view is not 4333 * long clickable, it becomes long clickable. 4334 * 4335 * @param l The callback that will run 4336 * 4337 * @see #setLongClickable(boolean) 4338 */ 4339 public void setOnLongClickListener(OnLongClickListener l) { 4340 if (!isLongClickable()) { 4341 setLongClickable(true); 4342 } 4343 getListenerInfo().mOnLongClickListener = l; 4344 } 4345 4346 /** 4347 * Register a callback to be invoked when the context menu for this view is 4348 * being built. If this view is not long clickable, it becomes long clickable. 4349 * 4350 * @param l The callback that will run 4351 * 4352 */ 4353 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 4354 if (!isLongClickable()) { 4355 setLongClickable(true); 4356 } 4357 getListenerInfo().mOnCreateContextMenuListener = l; 4358 } 4359 4360 /** 4361 * Call this view's OnClickListener, if it is defined. Performs all normal 4362 * actions associated with clicking: reporting accessibility event, playing 4363 * a sound, etc. 4364 * 4365 * @return True there was an assigned OnClickListener that was called, false 4366 * otherwise is returned. 4367 */ 4368 public boolean performClick() { 4369 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 4370 4371 ListenerInfo li = mListenerInfo; 4372 if (li != null && li.mOnClickListener != null) { 4373 playSoundEffect(SoundEffectConstants.CLICK); 4374 li.mOnClickListener.onClick(this); 4375 return true; 4376 } 4377 4378 return false; 4379 } 4380 4381 /** 4382 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 4383 * this only calls the listener, and does not do any associated clicking 4384 * actions like reporting an accessibility event. 4385 * 4386 * @return True there was an assigned OnClickListener that was called, false 4387 * otherwise is returned. 4388 */ 4389 public boolean callOnClick() { 4390 ListenerInfo li = mListenerInfo; 4391 if (li != null && li.mOnClickListener != null) { 4392 li.mOnClickListener.onClick(this); 4393 return true; 4394 } 4395 return false; 4396 } 4397 4398 /** 4399 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 4400 * OnLongClickListener did not consume the event. 4401 * 4402 * @return True if one of the above receivers consumed the event, false otherwise. 4403 */ 4404 public boolean performLongClick() { 4405 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 4406 4407 boolean handled = false; 4408 ListenerInfo li = mListenerInfo; 4409 if (li != null && li.mOnLongClickListener != null) { 4410 handled = li.mOnLongClickListener.onLongClick(View.this); 4411 } 4412 if (!handled) { 4413 handled = showContextMenu(); 4414 } 4415 if (handled) { 4416 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 4417 } 4418 return handled; 4419 } 4420 4421 /** 4422 * Performs button-related actions during a touch down event. 4423 * 4424 * @param event The event. 4425 * @return True if the down was consumed. 4426 * 4427 * @hide 4428 */ 4429 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 4430 if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 4431 if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) { 4432 return true; 4433 } 4434 } 4435 return false; 4436 } 4437 4438 /** 4439 * Bring up the context menu for this view. 4440 * 4441 * @return Whether a context menu was displayed. 4442 */ 4443 public boolean showContextMenu() { 4444 return getParent().showContextMenuForChild(this); 4445 } 4446 4447 /** 4448 * Bring up the context menu for this view, referring to the item under the specified point. 4449 * 4450 * @param x The referenced x coordinate. 4451 * @param y The referenced y coordinate. 4452 * @param metaState The keyboard modifiers that were pressed. 4453 * @return Whether a context menu was displayed. 4454 * 4455 * @hide 4456 */ 4457 public boolean showContextMenu(float x, float y, int metaState) { 4458 return showContextMenu(); 4459 } 4460 4461 /** 4462 * Start an action mode. 4463 * 4464 * @param callback Callback that will control the lifecycle of the action mode 4465 * @return The new action mode if it is started, null otherwise 4466 * 4467 * @see ActionMode 4468 */ 4469 public ActionMode startActionMode(ActionMode.Callback callback) { 4470 ViewParent parent = getParent(); 4471 if (parent == null) return null; 4472 return parent.startActionModeForChild(this, callback); 4473 } 4474 4475 /** 4476 * Register a callback to be invoked when a hardware key is pressed in this view. 4477 * Key presses in software input methods will generally not trigger the methods of 4478 * this listener. 4479 * @param l the key listener to attach to this view 4480 */ 4481 public void setOnKeyListener(OnKeyListener l) { 4482 getListenerInfo().mOnKeyListener = l; 4483 } 4484 4485 /** 4486 * Register a callback to be invoked when a touch event is sent to this view. 4487 * @param l the touch listener to attach to this view 4488 */ 4489 public void setOnTouchListener(OnTouchListener l) { 4490 getListenerInfo().mOnTouchListener = l; 4491 } 4492 4493 /** 4494 * Register a callback to be invoked when a generic motion event is sent to this view. 4495 * @param l the generic motion listener to attach to this view 4496 */ 4497 public void setOnGenericMotionListener(OnGenericMotionListener l) { 4498 getListenerInfo().mOnGenericMotionListener = l; 4499 } 4500 4501 /** 4502 * Register a callback to be invoked when a hover event is sent to this view. 4503 * @param l the hover listener to attach to this view 4504 */ 4505 public void setOnHoverListener(OnHoverListener l) { 4506 getListenerInfo().mOnHoverListener = l; 4507 } 4508 4509 /** 4510 * Register a drag event listener callback object for this View. The parameter is 4511 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 4512 * View, the system calls the 4513 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 4514 * @param l An implementation of {@link android.view.View.OnDragListener}. 4515 */ 4516 public void setOnDragListener(OnDragListener l) { 4517 getListenerInfo().mOnDragListener = l; 4518 } 4519 4520 /** 4521 * Give this view focus. This will cause 4522 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 4523 * 4524 * Note: this does not check whether this {@link View} should get focus, it just 4525 * gives it focus no matter what. It should only be called internally by framework 4526 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 4527 * 4528 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 4529 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 4530 * focus moved when requestFocus() is called. It may not always 4531 * apply, in which case use the default View.FOCUS_DOWN. 4532 * @param previouslyFocusedRect The rectangle of the view that had focus 4533 * prior in this View's coordinate system. 4534 */ 4535 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) { 4536 if (DBG) { 4537 System.out.println(this + " requestFocus()"); 4538 } 4539 4540 if ((mPrivateFlags & PFLAG_FOCUSED) == 0) { 4541 mPrivateFlags |= PFLAG_FOCUSED; 4542 4543 View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null; 4544 4545 if (mParent != null) { 4546 mParent.requestChildFocus(this, this); 4547 } 4548 4549 if (mAttachInfo != null) { 4550 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this); 4551 } 4552 4553 onFocusChanged(true, direction, previouslyFocusedRect); 4554 refreshDrawableState(); 4555 } 4556 } 4557 4558 /** 4559 * Request that a rectangle of this view be visible on the screen, 4560 * scrolling if necessary just enough. 4561 * 4562 * <p>A View should call this if it maintains some notion of which part 4563 * of its content is interesting. For example, a text editing view 4564 * should call this when its cursor moves. 4565 * 4566 * @param rectangle The rectangle. 4567 * @return Whether any parent scrolled. 4568 */ 4569 public boolean requestRectangleOnScreen(Rect rectangle) { 4570 return requestRectangleOnScreen(rectangle, false); 4571 } 4572 4573 /** 4574 * Request that a rectangle of this view be visible on the screen, 4575 * scrolling if necessary just enough. 4576 * 4577 * <p>A View should call this if it maintains some notion of which part 4578 * of its content is interesting. For example, a text editing view 4579 * should call this when its cursor moves. 4580 * 4581 * <p>When <code>immediate</code> is set to true, scrolling will not be 4582 * animated. 4583 * 4584 * @param rectangle The rectangle. 4585 * @param immediate True to forbid animated scrolling, false otherwise 4586 * @return Whether any parent scrolled. 4587 */ 4588 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 4589 if (mParent == null) { 4590 return false; 4591 } 4592 4593 View child = this; 4594 4595 RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF(); 4596 position.set(rectangle); 4597 4598 ViewParent parent = mParent; 4599 boolean scrolled = false; 4600 while (parent != null) { 4601 rectangle.set((int) position.left, (int) position.top, 4602 (int) position.right, (int) position.bottom); 4603 4604 scrolled |= parent.requestChildRectangleOnScreen(child, 4605 rectangle, immediate); 4606 4607 if (!child.hasIdentityMatrix()) { 4608 child.getMatrix().mapRect(position); 4609 } 4610 4611 position.offset(child.mLeft, child.mTop); 4612 4613 if (!(parent instanceof View)) { 4614 break; 4615 } 4616 4617 View parentView = (View) parent; 4618 4619 position.offset(-parentView.getScrollX(), -parentView.getScrollY()); 4620 4621 child = parentView; 4622 parent = child.getParent(); 4623 } 4624 4625 return scrolled; 4626 } 4627 4628 /** 4629 * Called when this view wants to give up focus. If focus is cleared 4630 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 4631 * <p> 4632 * <strong>Note:</strong> When a View clears focus the framework is trying 4633 * to give focus to the first focusable View from the top. Hence, if this 4634 * View is the first from the top that can take focus, then all callbacks 4635 * related to clearing focus will be invoked after wich the framework will 4636 * give focus to this view. 4637 * </p> 4638 */ 4639 public void clearFocus() { 4640 if (DBG) { 4641 System.out.println(this + " clearFocus()"); 4642 } 4643 4644 clearFocusInternal(true, true); 4645 } 4646 4647 /** 4648 * Clears focus from the view, optionally propagating the change up through 4649 * the parent hierarchy and requesting that the root view place new focus. 4650 * 4651 * @param propagate whether to propagate the change up through the parent 4652 * hierarchy 4653 * @param refocus when propagate is true, specifies whether to request the 4654 * root view place new focus 4655 */ 4656 void clearFocusInternal(boolean propagate, boolean refocus) { 4657 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 4658 mPrivateFlags &= ~PFLAG_FOCUSED; 4659 4660 if (propagate && mParent != null) { 4661 mParent.clearChildFocus(this); 4662 } 4663 4664 onFocusChanged(false, 0, null); 4665 4666 refreshDrawableState(); 4667 4668 if (propagate && (!refocus || !rootViewRequestFocus())) { 4669 notifyGlobalFocusCleared(this); 4670 } 4671 } 4672 } 4673 4674 void notifyGlobalFocusCleared(View oldFocus) { 4675 if (oldFocus != null && mAttachInfo != null) { 4676 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null); 4677 } 4678 } 4679 4680 boolean rootViewRequestFocus() { 4681 final View root = getRootView(); 4682 return root != null && root.requestFocus(); 4683 } 4684 4685 /** 4686 * Called internally by the view system when a new view is getting focus. 4687 * This is what clears the old focus. 4688 * <p> 4689 * <b>NOTE:</b> The parent view's focused child must be updated manually 4690 * after calling this method. Otherwise, the view hierarchy may be left in 4691 * an inconstent state. 4692 */ 4693 void unFocus() { 4694 if (DBG) { 4695 System.out.println(this + " unFocus()"); 4696 } 4697 4698 clearFocusInternal(false, false); 4699 } 4700 4701 /** 4702 * Returns true if this view has focus iteself, or is the ancestor of the 4703 * view that has focus. 4704 * 4705 * @return True if this view has or contains focus, false otherwise. 4706 */ 4707 @ViewDebug.ExportedProperty(category = "focus") 4708 public boolean hasFocus() { 4709 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 4710 } 4711 4712 /** 4713 * Returns true if this view is focusable or if it contains a reachable View 4714 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 4715 * is a View whose parents do not block descendants focus. 4716 * 4717 * Only {@link #VISIBLE} views are considered focusable. 4718 * 4719 * @return True if the view is focusable or if the view contains a focusable 4720 * View, false otherwise. 4721 * 4722 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 4723 */ 4724 public boolean hasFocusable() { 4725 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 4726 } 4727 4728 /** 4729 * Called by the view system when the focus state of this view changes. 4730 * When the focus change event is caused by directional navigation, direction 4731 * and previouslyFocusedRect provide insight into where the focus is coming from. 4732 * When overriding, be sure to call up through to the super class so that 4733 * the standard focus handling will occur. 4734 * 4735 * @param gainFocus True if the View has focus; false otherwise. 4736 * @param direction The direction focus has moved when requestFocus() 4737 * is called to give this view focus. Values are 4738 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 4739 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 4740 * It may not always apply, in which case use the default. 4741 * @param previouslyFocusedRect The rectangle, in this view's coordinate 4742 * system, of the previously focused view. If applicable, this will be 4743 * passed in as finer grained information about where the focus is coming 4744 * from (in addition to direction). Will be <code>null</code> otherwise. 4745 */ 4746 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) { 4747 if (gainFocus) { 4748 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 4749 } else { 4750 notifyViewAccessibilityStateChangedIfNeeded(); 4751 } 4752 4753 InputMethodManager imm = InputMethodManager.peekInstance(); 4754 if (!gainFocus) { 4755 if (isPressed()) { 4756 setPressed(false); 4757 } 4758 if (imm != null && mAttachInfo != null 4759 && mAttachInfo.mHasWindowFocus) { 4760 imm.focusOut(this); 4761 } 4762 onFocusLost(); 4763 } else if (imm != null && mAttachInfo != null 4764 && mAttachInfo.mHasWindowFocus) { 4765 imm.focusIn(this); 4766 } 4767 4768 invalidate(true); 4769 ListenerInfo li = mListenerInfo; 4770 if (li != null && li.mOnFocusChangeListener != null) { 4771 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 4772 } 4773 4774 if (mAttachInfo != null) { 4775 mAttachInfo.mKeyDispatchState.reset(this); 4776 } 4777 } 4778 4779 /** 4780 * Sends an accessibility event of the given type. If accessibility is 4781 * not enabled this method has no effect. The default implementation calls 4782 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 4783 * to populate information about the event source (this View), then calls 4784 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 4785 * populate the text content of the event source including its descendants, 4786 * and last calls 4787 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 4788 * on its parent to resuest sending of the event to interested parties. 4789 * <p> 4790 * If an {@link AccessibilityDelegate} has been specified via calling 4791 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4792 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 4793 * responsible for handling this call. 4794 * </p> 4795 * 4796 * @param eventType The type of the event to send, as defined by several types from 4797 * {@link android.view.accessibility.AccessibilityEvent}, such as 4798 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 4799 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 4800 * 4801 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 4802 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4803 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 4804 * @see AccessibilityDelegate 4805 */ 4806 public void sendAccessibilityEvent(int eventType) { 4807 // Excluded views do not send accessibility events. 4808 if (!includeForAccessibility()) { 4809 return; 4810 } 4811 if (mAccessibilityDelegate != null) { 4812 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 4813 } else { 4814 sendAccessibilityEventInternal(eventType); 4815 } 4816 } 4817 4818 /** 4819 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 4820 * {@link AccessibilityEvent} to make an announcement which is related to some 4821 * sort of a context change for which none of the events representing UI transitions 4822 * is a good fit. For example, announcing a new page in a book. If accessibility 4823 * is not enabled this method does nothing. 4824 * 4825 * @param text The announcement text. 4826 */ 4827 public void announceForAccessibility(CharSequence text) { 4828 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) { 4829 AccessibilityEvent event = AccessibilityEvent.obtain( 4830 AccessibilityEvent.TYPE_ANNOUNCEMENT); 4831 onInitializeAccessibilityEvent(event); 4832 event.getText().add(text); 4833 event.setContentDescription(null); 4834 mParent.requestSendAccessibilityEvent(this, event); 4835 } 4836 } 4837 4838 /** 4839 * @see #sendAccessibilityEvent(int) 4840 * 4841 * Note: Called from the default {@link AccessibilityDelegate}. 4842 */ 4843 void sendAccessibilityEventInternal(int eventType) { 4844 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 4845 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 4846 } 4847 } 4848 4849 /** 4850 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 4851 * takes as an argument an empty {@link AccessibilityEvent} and does not 4852 * perform a check whether accessibility is enabled. 4853 * <p> 4854 * If an {@link AccessibilityDelegate} has been specified via calling 4855 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4856 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 4857 * is responsible for handling this call. 4858 * </p> 4859 * 4860 * @param event The event to send. 4861 * 4862 * @see #sendAccessibilityEvent(int) 4863 */ 4864 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 4865 if (mAccessibilityDelegate != null) { 4866 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 4867 } else { 4868 sendAccessibilityEventUncheckedInternal(event); 4869 } 4870 } 4871 4872 /** 4873 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 4874 * 4875 * Note: Called from the default {@link AccessibilityDelegate}. 4876 */ 4877 void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 4878 if (!isShown()) { 4879 return; 4880 } 4881 onInitializeAccessibilityEvent(event); 4882 // Only a subset of accessibility events populates text content. 4883 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 4884 dispatchPopulateAccessibilityEvent(event); 4885 } 4886 // In the beginning we called #isShown(), so we know that getParent() is not null. 4887 getParent().requestSendAccessibilityEvent(this, event); 4888 } 4889 4890 /** 4891 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 4892 * to its children for adding their text content to the event. Note that the 4893 * event text is populated in a separate dispatch path since we add to the 4894 * event not only the text of the source but also the text of all its descendants. 4895 * A typical implementation will call 4896 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 4897 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 4898 * on each child. Override this method if custom population of the event text 4899 * content is required. 4900 * <p> 4901 * If an {@link AccessibilityDelegate} has been specified via calling 4902 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4903 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 4904 * is responsible for handling this call. 4905 * </p> 4906 * <p> 4907 * <em>Note:</em> Accessibility events of certain types are not dispatched for 4908 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 4909 * </p> 4910 * 4911 * @param event The event. 4912 * 4913 * @return True if the event population was completed. 4914 */ 4915 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 4916 if (mAccessibilityDelegate != null) { 4917 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 4918 } else { 4919 return dispatchPopulateAccessibilityEventInternal(event); 4920 } 4921 } 4922 4923 /** 4924 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4925 * 4926 * Note: Called from the default {@link AccessibilityDelegate}. 4927 */ 4928 boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 4929 onPopulateAccessibilityEvent(event); 4930 return false; 4931 } 4932 4933 /** 4934 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 4935 * giving a chance to this View to populate the accessibility event with its 4936 * text content. While this method is free to modify event 4937 * attributes other than text content, doing so should normally be performed in 4938 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 4939 * <p> 4940 * Example: Adding formatted date string to an accessibility event in addition 4941 * to the text added by the super implementation: 4942 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 4943 * super.onPopulateAccessibilityEvent(event); 4944 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 4945 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 4946 * mCurrentDate.getTimeInMillis(), flags); 4947 * event.getText().add(selectedDateUtterance); 4948 * }</pre> 4949 * <p> 4950 * If an {@link AccessibilityDelegate} has been specified via calling 4951 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4952 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 4953 * is responsible for handling this call. 4954 * </p> 4955 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 4956 * information to the event, in case the default implementation has basic information to add. 4957 * </p> 4958 * 4959 * @param event The accessibility event which to populate. 4960 * 4961 * @see #sendAccessibilityEvent(int) 4962 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4963 */ 4964 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 4965 if (mAccessibilityDelegate != null) { 4966 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 4967 } else { 4968 onPopulateAccessibilityEventInternal(event); 4969 } 4970 } 4971 4972 /** 4973 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 4974 * 4975 * Note: Called from the default {@link AccessibilityDelegate}. 4976 */ 4977 void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 4978 } 4979 4980 /** 4981 * Initializes an {@link AccessibilityEvent} with information about 4982 * this View which is the event source. In other words, the source of 4983 * an accessibility event is the view whose state change triggered firing 4984 * the event. 4985 * <p> 4986 * Example: Setting the password property of an event in addition 4987 * to properties set by the super implementation: 4988 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 4989 * super.onInitializeAccessibilityEvent(event); 4990 * event.setPassword(true); 4991 * }</pre> 4992 * <p> 4993 * If an {@link AccessibilityDelegate} has been specified via calling 4994 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4995 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 4996 * is responsible for handling this call. 4997 * </p> 4998 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 4999 * information to the event, in case the default implementation has basic information to add. 5000 * </p> 5001 * @param event The event to initialize. 5002 * 5003 * @see #sendAccessibilityEvent(int) 5004 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5005 */ 5006 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5007 if (mAccessibilityDelegate != null) { 5008 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 5009 } else { 5010 onInitializeAccessibilityEventInternal(event); 5011 } 5012 } 5013 5014 /** 5015 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5016 * 5017 * Note: Called from the default {@link AccessibilityDelegate}. 5018 */ 5019 void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 5020 event.setSource(this); 5021 event.setClassName(View.class.getName()); 5022 event.setPackageName(getContext().getPackageName()); 5023 event.setEnabled(isEnabled()); 5024 event.setContentDescription(mContentDescription); 5025 5026 switch (event.getEventType()) { 5027 case AccessibilityEvent.TYPE_VIEW_FOCUSED: { 5028 ArrayList<View> focusablesTempList = (mAttachInfo != null) 5029 ? mAttachInfo.mTempArrayList : new ArrayList<View>(); 5030 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL); 5031 event.setItemCount(focusablesTempList.size()); 5032 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 5033 if (mAttachInfo != null) { 5034 focusablesTempList.clear(); 5035 } 5036 } break; 5037 case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: { 5038 CharSequence text = getIterableTextForAccessibility(); 5039 if (text != null && text.length() > 0) { 5040 event.setFromIndex(getAccessibilitySelectionStart()); 5041 event.setToIndex(getAccessibilitySelectionEnd()); 5042 event.setItemCount(text.length()); 5043 } 5044 } break; 5045 } 5046 } 5047 5048 /** 5049 * Returns an {@link AccessibilityNodeInfo} representing this view from the 5050 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 5051 * This method is responsible for obtaining an accessibility node info from a 5052 * pool of reusable instances and calling 5053 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 5054 * initialize the former. 5055 * <p> 5056 * Note: The client is responsible for recycling the obtained instance by calling 5057 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 5058 * </p> 5059 * 5060 * @return A populated {@link AccessibilityNodeInfo}. 5061 * 5062 * @see AccessibilityNodeInfo 5063 */ 5064 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 5065 if (mAccessibilityDelegate != null) { 5066 return mAccessibilityDelegate.createAccessibilityNodeInfo(this); 5067 } else { 5068 return createAccessibilityNodeInfoInternal(); 5069 } 5070 } 5071 5072 /** 5073 * @see #createAccessibilityNodeInfo() 5074 */ 5075 AccessibilityNodeInfo createAccessibilityNodeInfoInternal() { 5076 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 5077 if (provider != null) { 5078 return provider.createAccessibilityNodeInfo(View.NO_ID); 5079 } else { 5080 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 5081 onInitializeAccessibilityNodeInfo(info); 5082 return info; 5083 } 5084 } 5085 5086 /** 5087 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 5088 * The base implementation sets: 5089 * <ul> 5090 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 5091 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 5092 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 5093 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 5094 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 5095 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 5096 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 5097 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 5098 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 5099 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 5100 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 5101 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 5102 * </ul> 5103 * <p> 5104 * Subclasses should override this method, call the super implementation, 5105 * and set additional attributes. 5106 * </p> 5107 * <p> 5108 * If an {@link AccessibilityDelegate} has been specified via calling 5109 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5110 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 5111 * is responsible for handling this call. 5112 * </p> 5113 * 5114 * @param info The instance to initialize. 5115 */ 5116 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 5117 if (mAccessibilityDelegate != null) { 5118 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 5119 } else { 5120 onInitializeAccessibilityNodeInfoInternal(info); 5121 } 5122 } 5123 5124 /** 5125 * Gets the location of this view in screen coordintates. 5126 * 5127 * @param outRect The output location 5128 */ 5129 void getBoundsOnScreen(Rect outRect) { 5130 if (mAttachInfo == null) { 5131 return; 5132 } 5133 5134 RectF position = mAttachInfo.mTmpTransformRect; 5135 position.set(0, 0, mRight - mLeft, mBottom - mTop); 5136 5137 if (!hasIdentityMatrix()) { 5138 getMatrix().mapRect(position); 5139 } 5140 5141 position.offset(mLeft, mTop); 5142 5143 ViewParent parent = mParent; 5144 while (parent instanceof View) { 5145 View parentView = (View) parent; 5146 5147 position.offset(-parentView.mScrollX, -parentView.mScrollY); 5148 5149 if (!parentView.hasIdentityMatrix()) { 5150 parentView.getMatrix().mapRect(position); 5151 } 5152 5153 position.offset(parentView.mLeft, parentView.mTop); 5154 5155 parent = parentView.mParent; 5156 } 5157 5158 if (parent instanceof ViewRootImpl) { 5159 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 5160 position.offset(0, -viewRootImpl.mCurScrollY); 5161 } 5162 5163 position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 5164 5165 outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f), 5166 (int) (position.right + 0.5f), (int) (position.bottom + 0.5f)); 5167 } 5168 5169 /** 5170 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 5171 * 5172 * Note: Called from the default {@link AccessibilityDelegate}. 5173 */ 5174 void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 5175 Rect bounds = mAttachInfo.mTmpInvalRect; 5176 5177 getDrawingRect(bounds); 5178 info.setBoundsInParent(bounds); 5179 5180 getBoundsOnScreen(bounds); 5181 info.setBoundsInScreen(bounds); 5182 5183 ViewParent parent = getParentForAccessibility(); 5184 if (parent instanceof View) { 5185 info.setParent((View) parent); 5186 } 5187 5188 if (mID != View.NO_ID) { 5189 View rootView = getRootView(); 5190 if (rootView == null) { 5191 rootView = this; 5192 } 5193 View label = rootView.findLabelForView(this, mID); 5194 if (label != null) { 5195 info.setLabeledBy(label); 5196 } 5197 5198 if ((mAttachInfo.mAccessibilityFetchFlags 5199 & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0 5200 && Resources.resourceHasPackage(mID)) { 5201 try { 5202 String viewId = getResources().getResourceName(mID); 5203 info.setViewIdResourceName(viewId); 5204 } catch (Resources.NotFoundException nfe) { 5205 /* ignore */ 5206 } 5207 } 5208 } 5209 5210 if (mLabelForId != View.NO_ID) { 5211 View rootView = getRootView(); 5212 if (rootView == null) { 5213 rootView = this; 5214 } 5215 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId); 5216 if (labeled != null) { 5217 info.setLabelFor(labeled); 5218 } 5219 } 5220 5221 info.setVisibleToUser(isVisibleToUser()); 5222 5223 info.setPackageName(mContext.getPackageName()); 5224 info.setClassName(View.class.getName()); 5225 info.setContentDescription(getContentDescription()); 5226 5227 info.setEnabled(isEnabled()); 5228 info.setClickable(isClickable()); 5229 info.setFocusable(isFocusable()); 5230 info.setFocused(isFocused()); 5231 info.setAccessibilityFocused(isAccessibilityFocused()); 5232 info.setSelected(isSelected()); 5233 info.setLongClickable(isLongClickable()); 5234 5235 // TODO: These make sense only if we are in an AdapterView but all 5236 // views can be selected. Maybe from accessibility perspective 5237 // we should report as selectable view in an AdapterView. 5238 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 5239 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 5240 5241 if (isFocusable()) { 5242 if (isFocused()) { 5243 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 5244 } else { 5245 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 5246 } 5247 } 5248 5249 if (!isAccessibilityFocused()) { 5250 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 5251 } else { 5252 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 5253 } 5254 5255 if (isClickable() && isEnabled()) { 5256 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 5257 } 5258 5259 if (isLongClickable() && isEnabled()) { 5260 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 5261 } 5262 5263 CharSequence text = getIterableTextForAccessibility(); 5264 if (text != null && text.length() > 0) { 5265 info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd()); 5266 5267 info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); 5268 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 5269 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 5270 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 5271 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 5272 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 5273 } 5274 } 5275 5276 private View findLabelForView(View view, int labeledId) { 5277 if (mMatchLabelForPredicate == null) { 5278 mMatchLabelForPredicate = new MatchLabelForPredicate(); 5279 } 5280 mMatchLabelForPredicate.mLabeledId = labeledId; 5281 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 5282 } 5283 5284 /** 5285 * Computes whether this view is visible to the user. Such a view is 5286 * attached, visible, all its predecessors are visible, it is not clipped 5287 * entirely by its predecessors, and has an alpha greater than zero. 5288 * 5289 * @return Whether the view is visible on the screen. 5290 * 5291 * @hide 5292 */ 5293 protected boolean isVisibleToUser() { 5294 return isVisibleToUser(null); 5295 } 5296 5297 /** 5298 * Computes whether the given portion of this view is visible to the user. 5299 * Such a view is attached, visible, all its predecessors are visible, 5300 * has an alpha greater than zero, and the specified portion is not 5301 * clipped entirely by its predecessors. 5302 * 5303 * @param boundInView the portion of the view to test; coordinates should be relative; may be 5304 * <code>null</code>, and the entire view will be tested in this case. 5305 * When <code>true</code> is returned by the function, the actual visible 5306 * region will be stored in this parameter; that is, if boundInView is fully 5307 * contained within the view, no modification will be made, otherwise regions 5308 * outside of the visible area of the view will be clipped. 5309 * 5310 * @return Whether the specified portion of the view is visible on the screen. 5311 * 5312 * @hide 5313 */ 5314 protected boolean isVisibleToUser(Rect boundInView) { 5315 if (mAttachInfo != null) { 5316 // Attached to invisible window means this view is not visible. 5317 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 5318 return false; 5319 } 5320 // An invisible predecessor or one with alpha zero means 5321 // that this view is not visible to the user. 5322 Object current = this; 5323 while (current instanceof View) { 5324 View view = (View) current; 5325 // We have attach info so this view is attached and there is no 5326 // need to check whether we reach to ViewRootImpl on the way up. 5327 if (view.getAlpha() <= 0 || view.getVisibility() != VISIBLE) { 5328 return false; 5329 } 5330 current = view.mParent; 5331 } 5332 // Check if the view is entirely covered by its predecessors. 5333 Rect visibleRect = mAttachInfo.mTmpInvalRect; 5334 Point offset = mAttachInfo.mPoint; 5335 if (!getGlobalVisibleRect(visibleRect, offset)) { 5336 return false; 5337 } 5338 // Check if the visible portion intersects the rectangle of interest. 5339 if (boundInView != null) { 5340 visibleRect.offset(-offset.x, -offset.y); 5341 return boundInView.intersect(visibleRect); 5342 } 5343 return true; 5344 } 5345 return false; 5346 } 5347 5348 /** 5349 * Returns the delegate for implementing accessibility support via 5350 * composition. For more details see {@link AccessibilityDelegate}. 5351 * 5352 * @return The delegate, or null if none set. 5353 * 5354 * @hide 5355 */ 5356 public AccessibilityDelegate getAccessibilityDelegate() { 5357 return mAccessibilityDelegate; 5358 } 5359 5360 /** 5361 * Sets a delegate for implementing accessibility support via composition as 5362 * opposed to inheritance. The delegate's primary use is for implementing 5363 * backwards compatible widgets. For more details see {@link AccessibilityDelegate}. 5364 * 5365 * @param delegate The delegate instance. 5366 * 5367 * @see AccessibilityDelegate 5368 */ 5369 public void setAccessibilityDelegate(AccessibilityDelegate delegate) { 5370 mAccessibilityDelegate = delegate; 5371 } 5372 5373 /** 5374 * Gets the provider for managing a virtual view hierarchy rooted at this View 5375 * and reported to {@link android.accessibilityservice.AccessibilityService}s 5376 * that explore the window content. 5377 * <p> 5378 * If this method returns an instance, this instance is responsible for managing 5379 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 5380 * View including the one representing the View itself. Similarly the returned 5381 * instance is responsible for performing accessibility actions on any virtual 5382 * view or the root view itself. 5383 * </p> 5384 * <p> 5385 * If an {@link AccessibilityDelegate} has been specified via calling 5386 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5387 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 5388 * is responsible for handling this call. 5389 * </p> 5390 * 5391 * @return The provider. 5392 * 5393 * @see AccessibilityNodeProvider 5394 */ 5395 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 5396 if (mAccessibilityDelegate != null) { 5397 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 5398 } else { 5399 return null; 5400 } 5401 } 5402 5403 /** 5404 * Gets the unique identifier of this view on the screen for accessibility purposes. 5405 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 5406 * 5407 * @return The view accessibility id. 5408 * 5409 * @hide 5410 */ 5411 public int getAccessibilityViewId() { 5412 if (mAccessibilityViewId == NO_ID) { 5413 mAccessibilityViewId = sNextAccessibilityViewId++; 5414 } 5415 return mAccessibilityViewId; 5416 } 5417 5418 /** 5419 * Gets the unique identifier of the window in which this View reseides. 5420 * 5421 * @return The window accessibility id. 5422 * 5423 * @hide 5424 */ 5425 public int getAccessibilityWindowId() { 5426 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID; 5427 } 5428 5429 /** 5430 * Gets the {@link View} description. It briefly describes the view and is 5431 * primarily used for accessibility support. Set this property to enable 5432 * better accessibility support for your application. This is especially 5433 * true for views that do not have textual representation (For example, 5434 * ImageButton). 5435 * 5436 * @return The content description. 5437 * 5438 * @attr ref android.R.styleable#View_contentDescription 5439 */ 5440 @ViewDebug.ExportedProperty(category = "accessibility") 5441 public CharSequence getContentDescription() { 5442 return mContentDescription; 5443 } 5444 5445 /** 5446 * Sets the {@link View} description. It briefly describes the view and is 5447 * primarily used for accessibility support. Set this property to enable 5448 * better accessibility support for your application. This is especially 5449 * true for views that do not have textual representation (For example, 5450 * ImageButton). 5451 * 5452 * @param contentDescription The content description. 5453 * 5454 * @attr ref android.R.styleable#View_contentDescription 5455 */ 5456 @RemotableViewMethod 5457 public void setContentDescription(CharSequence contentDescription) { 5458 if (mContentDescription == null) { 5459 if (contentDescription == null) { 5460 return; 5461 } 5462 } else if (mContentDescription.equals(contentDescription)) { 5463 return; 5464 } 5465 mContentDescription = contentDescription; 5466 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 5467 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 5468 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 5469 notifySubtreeAccessibilityStateChangedIfNeeded(); 5470 } else { 5471 notifyViewAccessibilityStateChangedIfNeeded(); 5472 } 5473 } 5474 5475 /** 5476 * Gets the id of a view for which this view serves as a label for 5477 * accessibility purposes. 5478 * 5479 * @return The labeled view id. 5480 */ 5481 @ViewDebug.ExportedProperty(category = "accessibility") 5482 public int getLabelFor() { 5483 return mLabelForId; 5484 } 5485 5486 /** 5487 * Sets the id of a view for which this view serves as a label for 5488 * accessibility purposes. 5489 * 5490 * @param id The labeled view id. 5491 */ 5492 @RemotableViewMethod 5493 public void setLabelFor(int id) { 5494 mLabelForId = id; 5495 if (mLabelForId != View.NO_ID 5496 && mID == View.NO_ID) { 5497 mID = generateViewId(); 5498 } 5499 } 5500 5501 /** 5502 * Invoked whenever this view loses focus, either by losing window focus or by losing 5503 * focus within its window. This method can be used to clear any state tied to the 5504 * focus. For instance, if a button is held pressed with the trackball and the window 5505 * loses focus, this method can be used to cancel the press. 5506 * 5507 * Subclasses of View overriding this method should always call super.onFocusLost(). 5508 * 5509 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 5510 * @see #onWindowFocusChanged(boolean) 5511 * 5512 * @hide pending API council approval 5513 */ 5514 protected void onFocusLost() { 5515 resetPressedState(); 5516 } 5517 5518 private void resetPressedState() { 5519 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 5520 return; 5521 } 5522 5523 if (isPressed()) { 5524 setPressed(false); 5525 5526 if (!mHasPerformedLongPress) { 5527 removeLongPressCallback(); 5528 } 5529 } 5530 } 5531 5532 /** 5533 * Returns true if this view has focus 5534 * 5535 * @return True if this view has focus, false otherwise. 5536 */ 5537 @ViewDebug.ExportedProperty(category = "focus") 5538 public boolean isFocused() { 5539 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 5540 } 5541 5542 /** 5543 * Find the view in the hierarchy rooted at this view that currently has 5544 * focus. 5545 * 5546 * @return The view that currently has focus, or null if no focused view can 5547 * be found. 5548 */ 5549 public View findFocus() { 5550 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 5551 } 5552 5553 /** 5554 * Indicates whether this view is one of the set of scrollable containers in 5555 * its window. 5556 * 5557 * @return whether this view is one of the set of scrollable containers in 5558 * its window 5559 * 5560 * @attr ref android.R.styleable#View_isScrollContainer 5561 */ 5562 public boolean isScrollContainer() { 5563 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 5564 } 5565 5566 /** 5567 * Change whether this view is one of the set of scrollable containers in 5568 * its window. This will be used to determine whether the window can 5569 * resize or must pan when a soft input area is open -- scrollable 5570 * containers allow the window to use resize mode since the container 5571 * will appropriately shrink. 5572 * 5573 * @attr ref android.R.styleable#View_isScrollContainer 5574 */ 5575 public void setScrollContainer(boolean isScrollContainer) { 5576 if (isScrollContainer) { 5577 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 5578 mAttachInfo.mScrollContainers.add(this); 5579 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 5580 } 5581 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 5582 } else { 5583 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 5584 mAttachInfo.mScrollContainers.remove(this); 5585 } 5586 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 5587 } 5588 } 5589 5590 /** 5591 * Returns the quality of the drawing cache. 5592 * 5593 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5594 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5595 * 5596 * @see #setDrawingCacheQuality(int) 5597 * @see #setDrawingCacheEnabled(boolean) 5598 * @see #isDrawingCacheEnabled() 5599 * 5600 * @attr ref android.R.styleable#View_drawingCacheQuality 5601 */ 5602 public int getDrawingCacheQuality() { 5603 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 5604 } 5605 5606 /** 5607 * Set the drawing cache quality of this view. This value is used only when the 5608 * drawing cache is enabled 5609 * 5610 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5611 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5612 * 5613 * @see #getDrawingCacheQuality() 5614 * @see #setDrawingCacheEnabled(boolean) 5615 * @see #isDrawingCacheEnabled() 5616 * 5617 * @attr ref android.R.styleable#View_drawingCacheQuality 5618 */ 5619 public void setDrawingCacheQuality(int quality) { 5620 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 5621 } 5622 5623 /** 5624 * Returns whether the screen should remain on, corresponding to the current 5625 * value of {@link #KEEP_SCREEN_ON}. 5626 * 5627 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 5628 * 5629 * @see #setKeepScreenOn(boolean) 5630 * 5631 * @attr ref android.R.styleable#View_keepScreenOn 5632 */ 5633 public boolean getKeepScreenOn() { 5634 return (mViewFlags & KEEP_SCREEN_ON) != 0; 5635 } 5636 5637 /** 5638 * Controls whether the screen should remain on, modifying the 5639 * value of {@link #KEEP_SCREEN_ON}. 5640 * 5641 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 5642 * 5643 * @see #getKeepScreenOn() 5644 * 5645 * @attr ref android.R.styleable#View_keepScreenOn 5646 */ 5647 public void setKeepScreenOn(boolean keepScreenOn) { 5648 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 5649 } 5650 5651 /** 5652 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5653 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5654 * 5655 * @attr ref android.R.styleable#View_nextFocusLeft 5656 */ 5657 public int getNextFocusLeftId() { 5658 return mNextFocusLeftId; 5659 } 5660 5661 /** 5662 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5663 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 5664 * decide automatically. 5665 * 5666 * @attr ref android.R.styleable#View_nextFocusLeft 5667 */ 5668 public void setNextFocusLeftId(int nextFocusLeftId) { 5669 mNextFocusLeftId = nextFocusLeftId; 5670 } 5671 5672 /** 5673 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5674 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5675 * 5676 * @attr ref android.R.styleable#View_nextFocusRight 5677 */ 5678 public int getNextFocusRightId() { 5679 return mNextFocusRightId; 5680 } 5681 5682 /** 5683 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5684 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 5685 * decide automatically. 5686 * 5687 * @attr ref android.R.styleable#View_nextFocusRight 5688 */ 5689 public void setNextFocusRightId(int nextFocusRightId) { 5690 mNextFocusRightId = nextFocusRightId; 5691 } 5692 5693 /** 5694 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 5695 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5696 * 5697 * @attr ref android.R.styleable#View_nextFocusUp 5698 */ 5699 public int getNextFocusUpId() { 5700 return mNextFocusUpId; 5701 } 5702 5703 /** 5704 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 5705 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 5706 * decide automatically. 5707 * 5708 * @attr ref android.R.styleable#View_nextFocusUp 5709 */ 5710 public void setNextFocusUpId(int nextFocusUpId) { 5711 mNextFocusUpId = nextFocusUpId; 5712 } 5713 5714 /** 5715 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 5716 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5717 * 5718 * @attr ref android.R.styleable#View_nextFocusDown 5719 */ 5720 public int getNextFocusDownId() { 5721 return mNextFocusDownId; 5722 } 5723 5724 /** 5725 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 5726 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 5727 * decide automatically. 5728 * 5729 * @attr ref android.R.styleable#View_nextFocusDown 5730 */ 5731 public void setNextFocusDownId(int nextFocusDownId) { 5732 mNextFocusDownId = nextFocusDownId; 5733 } 5734 5735 /** 5736 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 5737 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5738 * 5739 * @attr ref android.R.styleable#View_nextFocusForward 5740 */ 5741 public int getNextFocusForwardId() { 5742 return mNextFocusForwardId; 5743 } 5744 5745 /** 5746 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 5747 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 5748 * decide automatically. 5749 * 5750 * @attr ref android.R.styleable#View_nextFocusForward 5751 */ 5752 public void setNextFocusForwardId(int nextFocusForwardId) { 5753 mNextFocusForwardId = nextFocusForwardId; 5754 } 5755 5756 /** 5757 * Returns the visibility of this view and all of its ancestors 5758 * 5759 * @return True if this view and all of its ancestors are {@link #VISIBLE} 5760 */ 5761 public boolean isShown() { 5762 View current = this; 5763 //noinspection ConstantConditions 5764 do { 5765 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 5766 return false; 5767 } 5768 ViewParent parent = current.mParent; 5769 if (parent == null) { 5770 return false; // We are not attached to the view root 5771 } 5772 if (!(parent instanceof View)) { 5773 return true; 5774 } 5775 current = (View) parent; 5776 } while (current != null); 5777 5778 return false; 5779 } 5780 5781 /** 5782 * Called by the view hierarchy when the content insets for a window have 5783 * changed, to allow it to adjust its content to fit within those windows. 5784 * The content insets tell you the space that the status bar, input method, 5785 * and other system windows infringe on the application's window. 5786 * 5787 * <p>You do not normally need to deal with this function, since the default 5788 * window decoration given to applications takes care of applying it to the 5789 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 5790 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 5791 * and your content can be placed under those system elements. You can then 5792 * use this method within your view hierarchy if you have parts of your UI 5793 * which you would like to ensure are not being covered. 5794 * 5795 * <p>The default implementation of this method simply applies the content 5796 * insets to the view's padding, consuming that content (modifying the 5797 * insets to be 0), and returning true. This behavior is off by default, but can 5798 * be enabled through {@link #setFitsSystemWindows(boolean)}. 5799 * 5800 * <p>This function's traversal down the hierarchy is depth-first. The same content 5801 * insets object is propagated down the hierarchy, so any changes made to it will 5802 * be seen by all following views (including potentially ones above in 5803 * the hierarchy since this is a depth-first traversal). The first view 5804 * that returns true will abort the entire traversal. 5805 * 5806 * <p>The default implementation works well for a situation where it is 5807 * used with a container that covers the entire window, allowing it to 5808 * apply the appropriate insets to its content on all edges. If you need 5809 * a more complicated layout (such as two different views fitting system 5810 * windows, one on the top of the window, and one on the bottom), 5811 * you can override the method and handle the insets however you would like. 5812 * Note that the insets provided by the framework are always relative to the 5813 * far edges of the window, not accounting for the location of the called view 5814 * within that window. (In fact when this method is called you do not yet know 5815 * where the layout will place the view, as it is done before layout happens.) 5816 * 5817 * <p>Note: unlike many View methods, there is no dispatch phase to this 5818 * call. If you are overriding it in a ViewGroup and want to allow the 5819 * call to continue to your children, you must be sure to call the super 5820 * implementation. 5821 * 5822 * <p>Here is a sample layout that makes use of fitting system windows 5823 * to have controls for a video view placed inside of the window decorations 5824 * that it hides and shows. This can be used with code like the second 5825 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 5826 * 5827 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 5828 * 5829 * @param insets Current content insets of the window. Prior to 5830 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 5831 * the insets or else you and Android will be unhappy. 5832 * 5833 * @return {@code true} if this view applied the insets and it should not 5834 * continue propagating further down the hierarchy, {@code false} otherwise. 5835 * @see #getFitsSystemWindows() 5836 * @see #setFitsSystemWindows(boolean) 5837 * @see #setSystemUiVisibility(int) 5838 */ 5839 protected boolean fitSystemWindows(Rect insets) { 5840 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 5841 mUserPaddingStart = UNDEFINED_PADDING; 5842 mUserPaddingEnd = UNDEFINED_PADDING; 5843 Rect localInsets = sThreadLocal.get(); 5844 if (localInsets == null) { 5845 localInsets = new Rect(); 5846 sThreadLocal.set(localInsets); 5847 } 5848 boolean res = computeFitSystemWindows(insets, localInsets); 5849 internalSetPadding(localInsets.left, localInsets.top, 5850 localInsets.right, localInsets.bottom); 5851 return res; 5852 } 5853 return false; 5854 } 5855 5856 /** 5857 * @hide Compute the insets that should be consumed by this view and the ones 5858 * that should propagate to those under it. 5859 */ 5860 protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) { 5861 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 5862 || mAttachInfo == null 5863 || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0 5864 && !mAttachInfo.mOverscanRequested)) { 5865 outLocalInsets.set(inoutInsets); 5866 inoutInsets.set(0, 0, 0, 0); 5867 return true; 5868 } else { 5869 // The application wants to take care of fitting system window for 5870 // the content... however we still need to take care of any overscan here. 5871 final Rect overscan = mAttachInfo.mOverscanInsets; 5872 outLocalInsets.set(overscan); 5873 inoutInsets.left -= overscan.left; 5874 inoutInsets.top -= overscan.top; 5875 inoutInsets.right -= overscan.right; 5876 inoutInsets.bottom -= overscan.bottom; 5877 return false; 5878 } 5879 } 5880 5881 /** 5882 * Sets whether or not this view should account for system screen decorations 5883 * such as the status bar and inset its content; that is, controlling whether 5884 * the default implementation of {@link #fitSystemWindows(Rect)} will be 5885 * executed. See that method for more details. 5886 * 5887 * <p>Note that if you are providing your own implementation of 5888 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 5889 * flag to true -- your implementation will be overriding the default 5890 * implementation that checks this flag. 5891 * 5892 * @param fitSystemWindows If true, then the default implementation of 5893 * {@link #fitSystemWindows(Rect)} will be executed. 5894 * 5895 * @attr ref android.R.styleable#View_fitsSystemWindows 5896 * @see #getFitsSystemWindows() 5897 * @see #fitSystemWindows(Rect) 5898 * @see #setSystemUiVisibility(int) 5899 */ 5900 public void setFitsSystemWindows(boolean fitSystemWindows) { 5901 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 5902 } 5903 5904 /** 5905 * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method 5906 * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)} 5907 * will be executed. 5908 * 5909 * @return {@code true} if the default implementation of 5910 * {@link #fitSystemWindows(Rect)} will be executed. 5911 * 5912 * @attr ref android.R.styleable#View_fitsSystemWindows 5913 * @see #setFitsSystemWindows(boolean) 5914 * @see #fitSystemWindows(Rect) 5915 * @see #setSystemUiVisibility(int) 5916 */ 5917 public boolean getFitsSystemWindows() { 5918 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 5919 } 5920 5921 /** @hide */ 5922 public boolean fitsSystemWindows() { 5923 return getFitsSystemWindows(); 5924 } 5925 5926 /** 5927 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 5928 */ 5929 public void requestFitSystemWindows() { 5930 if (mParent != null) { 5931 mParent.requestFitSystemWindows(); 5932 } 5933 } 5934 5935 /** 5936 * For use by PhoneWindow to make its own system window fitting optional. 5937 * @hide 5938 */ 5939 public void makeOptionalFitsSystemWindows() { 5940 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 5941 } 5942 5943 /** 5944 * Returns the visibility status for this view. 5945 * 5946 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 5947 * @attr ref android.R.styleable#View_visibility 5948 */ 5949 @ViewDebug.ExportedProperty(mapping = { 5950 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 5951 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 5952 @ViewDebug.IntToString(from = GONE, to = "GONE") 5953 }) 5954 public int getVisibility() { 5955 return mViewFlags & VISIBILITY_MASK; 5956 } 5957 5958 /** 5959 * Set the enabled state of this view. 5960 * 5961 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 5962 * @attr ref android.R.styleable#View_visibility 5963 */ 5964 @RemotableViewMethod 5965 public void setVisibility(int visibility) { 5966 setFlags(visibility, VISIBILITY_MASK); 5967 if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false); 5968 } 5969 5970 /** 5971 * Returns the enabled status for this view. The interpretation of the 5972 * enabled state varies by subclass. 5973 * 5974 * @return True if this view is enabled, false otherwise. 5975 */ 5976 @ViewDebug.ExportedProperty 5977 public boolean isEnabled() { 5978 return (mViewFlags & ENABLED_MASK) == ENABLED; 5979 } 5980 5981 /** 5982 * Set the enabled state of this view. The interpretation of the enabled 5983 * state varies by subclass. 5984 * 5985 * @param enabled True if this view is enabled, false otherwise. 5986 */ 5987 @RemotableViewMethod 5988 public void setEnabled(boolean enabled) { 5989 if (enabled == isEnabled()) return; 5990 5991 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 5992 5993 /* 5994 * The View most likely has to change its appearance, so refresh 5995 * the drawable state. 5996 */ 5997 refreshDrawableState(); 5998 5999 // Invalidate too, since the default behavior for views is to be 6000 // be drawn at 50% alpha rather than to change the drawable. 6001 invalidate(true); 6002 6003 if (!enabled) { 6004 cancelPendingInputEvents(); 6005 } 6006 } 6007 6008 /** 6009 * Set whether this view can receive the focus. 6010 * 6011 * Setting this to false will also ensure that this view is not focusable 6012 * in touch mode. 6013 * 6014 * @param focusable If true, this view can receive the focus. 6015 * 6016 * @see #setFocusableInTouchMode(boolean) 6017 * @attr ref android.R.styleable#View_focusable 6018 */ 6019 public void setFocusable(boolean focusable) { 6020 if (!focusable) { 6021 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 6022 } 6023 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 6024 } 6025 6026 /** 6027 * Set whether this view can receive focus while in touch mode. 6028 * 6029 * Setting this to true will also ensure that this view is focusable. 6030 * 6031 * @param focusableInTouchMode If true, this view can receive the focus while 6032 * in touch mode. 6033 * 6034 * @see #setFocusable(boolean) 6035 * @attr ref android.R.styleable#View_focusableInTouchMode 6036 */ 6037 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 6038 // Focusable in touch mode should always be set before the focusable flag 6039 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 6040 // which, in touch mode, will not successfully request focus on this view 6041 // because the focusable in touch mode flag is not set 6042 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 6043 if (focusableInTouchMode) { 6044 setFlags(FOCUSABLE, FOCUSABLE_MASK); 6045 } 6046 } 6047 6048 /** 6049 * Set whether this view should have sound effects enabled for events such as 6050 * clicking and touching. 6051 * 6052 * <p>You may wish to disable sound effects for a view if you already play sounds, 6053 * for instance, a dial key that plays dtmf tones. 6054 * 6055 * @param soundEffectsEnabled whether sound effects are enabled for this view. 6056 * @see #isSoundEffectsEnabled() 6057 * @see #playSoundEffect(int) 6058 * @attr ref android.R.styleable#View_soundEffectsEnabled 6059 */ 6060 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 6061 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 6062 } 6063 6064 /** 6065 * @return whether this view should have sound effects enabled for events such as 6066 * clicking and touching. 6067 * 6068 * @see #setSoundEffectsEnabled(boolean) 6069 * @see #playSoundEffect(int) 6070 * @attr ref android.R.styleable#View_soundEffectsEnabled 6071 */ 6072 @ViewDebug.ExportedProperty 6073 public boolean isSoundEffectsEnabled() { 6074 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 6075 } 6076 6077 /** 6078 * Set whether this view should have haptic feedback for events such as 6079 * long presses. 6080 * 6081 * <p>You may wish to disable haptic feedback if your view already controls 6082 * its own haptic feedback. 6083 * 6084 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 6085 * @see #isHapticFeedbackEnabled() 6086 * @see #performHapticFeedback(int) 6087 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6088 */ 6089 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 6090 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 6091 } 6092 6093 /** 6094 * @return whether this view should have haptic feedback enabled for events 6095 * long presses. 6096 * 6097 * @see #setHapticFeedbackEnabled(boolean) 6098 * @see #performHapticFeedback(int) 6099 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6100 */ 6101 @ViewDebug.ExportedProperty 6102 public boolean isHapticFeedbackEnabled() { 6103 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 6104 } 6105 6106 /** 6107 * Returns the layout direction for this view. 6108 * 6109 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 6110 * {@link #LAYOUT_DIRECTION_RTL}, 6111 * {@link #LAYOUT_DIRECTION_INHERIT} or 6112 * {@link #LAYOUT_DIRECTION_LOCALE}. 6113 * 6114 * @attr ref android.R.styleable#View_layoutDirection 6115 * 6116 * @hide 6117 */ 6118 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6119 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 6120 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 6121 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 6122 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 6123 }) 6124 public int getRawLayoutDirection() { 6125 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 6126 } 6127 6128 /** 6129 * Set the layout direction for this view. This will propagate a reset of layout direction 6130 * resolution to the view's children and resolve layout direction for this view. 6131 * 6132 * @param layoutDirection the layout direction to set. Should be one of: 6133 * 6134 * {@link #LAYOUT_DIRECTION_LTR}, 6135 * {@link #LAYOUT_DIRECTION_RTL}, 6136 * {@link #LAYOUT_DIRECTION_INHERIT}, 6137 * {@link #LAYOUT_DIRECTION_LOCALE}. 6138 * 6139 * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution 6140 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 6141 * will return the default {@link #LAYOUT_DIRECTION_LTR}. 6142 * 6143 * @attr ref android.R.styleable#View_layoutDirection 6144 */ 6145 @RemotableViewMethod 6146 public void setLayoutDirection(int layoutDirection) { 6147 if (getRawLayoutDirection() != layoutDirection) { 6148 // Reset the current layout direction and the resolved one 6149 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 6150 resetRtlProperties(); 6151 // Set the new layout direction (filtered) 6152 mPrivateFlags2 |= 6153 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 6154 // We need to resolve all RTL properties as they all depend on layout direction 6155 resolveRtlPropertiesIfNeeded(); 6156 requestLayout(); 6157 invalidate(true); 6158 } 6159 } 6160 6161 /** 6162 * Returns the resolved layout direction for this view. 6163 * 6164 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 6165 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 6166 * 6167 * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version 6168 * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}. 6169 * 6170 * @attr ref android.R.styleable#View_layoutDirection 6171 */ 6172 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6173 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 6174 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 6175 }) 6176 public int getLayoutDirection() { 6177 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 6178 if (targetSdkVersion < JELLY_BEAN_MR1) { 6179 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 6180 return LAYOUT_DIRECTION_RESOLVED_DEFAULT; 6181 } 6182 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == 6183 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 6184 } 6185 6186 /** 6187 * Indicates whether or not this view's layout is right-to-left. This is resolved from 6188 * layout attribute and/or the inherited value from the parent 6189 * 6190 * @return true if the layout is right-to-left. 6191 * 6192 * @hide 6193 */ 6194 @ViewDebug.ExportedProperty(category = "layout") 6195 public boolean isLayoutRtl() { 6196 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 6197 } 6198 6199 /** 6200 * Indicates whether the view is currently tracking transient state that the 6201 * app should not need to concern itself with saving and restoring, but that 6202 * the framework should take special note to preserve when possible. 6203 * 6204 * <p>A view with transient state cannot be trivially rebound from an external 6205 * data source, such as an adapter binding item views in a list. This may be 6206 * because the view is performing an animation, tracking user selection 6207 * of content, or similar.</p> 6208 * 6209 * @return true if the view has transient state 6210 */ 6211 @ViewDebug.ExportedProperty(category = "layout") 6212 public boolean hasTransientState() { 6213 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 6214 } 6215 6216 /** 6217 * Set whether this view is currently tracking transient state that the 6218 * framework should attempt to preserve when possible. This flag is reference counted, 6219 * so every call to setHasTransientState(true) should be paired with a later call 6220 * to setHasTransientState(false). 6221 * 6222 * <p>A view with transient state cannot be trivially rebound from an external 6223 * data source, such as an adapter binding item views in a list. This may be 6224 * because the view is performing an animation, tracking user selection 6225 * of content, or similar.</p> 6226 * 6227 * @param hasTransientState true if this view has transient state 6228 */ 6229 public void setHasTransientState(boolean hasTransientState) { 6230 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 6231 mTransientStateCount - 1; 6232 if (mTransientStateCount < 0) { 6233 mTransientStateCount = 0; 6234 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 6235 "unmatched pair of setHasTransientState calls"); 6236 } else if ((hasTransientState && mTransientStateCount == 1) || 6237 (!hasTransientState && mTransientStateCount == 0)) { 6238 // update flag if we've just incremented up from 0 or decremented down to 0 6239 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 6240 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 6241 if (mParent != null) { 6242 try { 6243 mParent.childHasTransientStateChanged(this, hasTransientState); 6244 } catch (AbstractMethodError e) { 6245 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 6246 " does not fully implement ViewParent", e); 6247 } 6248 } 6249 } 6250 } 6251 6252 /** 6253 * Returns true if this view is currently attached to a window. 6254 */ 6255 public boolean isAttachedToWindow() { 6256 return mAttachInfo != null; 6257 } 6258 6259 /** 6260 * Returns true if this view has been through at least one layout since it 6261 * was last attached to or detached from a window. 6262 */ 6263 public boolean isLaidOut() { 6264 return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT; 6265 } 6266 6267 /** 6268 * If this view doesn't do any drawing on its own, set this flag to 6269 * allow further optimizations. By default, this flag is not set on 6270 * View, but could be set on some View subclasses such as ViewGroup. 6271 * 6272 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 6273 * you should clear this flag. 6274 * 6275 * @param willNotDraw whether or not this View draw on its own 6276 */ 6277 public void setWillNotDraw(boolean willNotDraw) { 6278 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 6279 } 6280 6281 /** 6282 * Returns whether or not this View draws on its own. 6283 * 6284 * @return true if this view has nothing to draw, false otherwise 6285 */ 6286 @ViewDebug.ExportedProperty(category = "drawing") 6287 public boolean willNotDraw() { 6288 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 6289 } 6290 6291 /** 6292 * When a View's drawing cache is enabled, drawing is redirected to an 6293 * offscreen bitmap. Some views, like an ImageView, must be able to 6294 * bypass this mechanism if they already draw a single bitmap, to avoid 6295 * unnecessary usage of the memory. 6296 * 6297 * @param willNotCacheDrawing true if this view does not cache its 6298 * drawing, false otherwise 6299 */ 6300 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 6301 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 6302 } 6303 6304 /** 6305 * Returns whether or not this View can cache its drawing or not. 6306 * 6307 * @return true if this view does not cache its drawing, false otherwise 6308 */ 6309 @ViewDebug.ExportedProperty(category = "drawing") 6310 public boolean willNotCacheDrawing() { 6311 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 6312 } 6313 6314 /** 6315 * Indicates whether this view reacts to click events or not. 6316 * 6317 * @return true if the view is clickable, false otherwise 6318 * 6319 * @see #setClickable(boolean) 6320 * @attr ref android.R.styleable#View_clickable 6321 */ 6322 @ViewDebug.ExportedProperty 6323 public boolean isClickable() { 6324 return (mViewFlags & CLICKABLE) == CLICKABLE; 6325 } 6326 6327 /** 6328 * Enables or disables click events for this view. When a view 6329 * is clickable it will change its state to "pressed" on every click. 6330 * Subclasses should set the view clickable to visually react to 6331 * user's clicks. 6332 * 6333 * @param clickable true to make the view clickable, false otherwise 6334 * 6335 * @see #isClickable() 6336 * @attr ref android.R.styleable#View_clickable 6337 */ 6338 public void setClickable(boolean clickable) { 6339 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 6340 } 6341 6342 /** 6343 * Indicates whether this view reacts to long click events or not. 6344 * 6345 * @return true if the view is long clickable, false otherwise 6346 * 6347 * @see #setLongClickable(boolean) 6348 * @attr ref android.R.styleable#View_longClickable 6349 */ 6350 public boolean isLongClickable() { 6351 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 6352 } 6353 6354 /** 6355 * Enables or disables long click events for this view. When a view is long 6356 * clickable it reacts to the user holding down the button for a longer 6357 * duration than a tap. This event can either launch the listener or a 6358 * context menu. 6359 * 6360 * @param longClickable true to make the view long clickable, false otherwise 6361 * @see #isLongClickable() 6362 * @attr ref android.R.styleable#View_longClickable 6363 */ 6364 public void setLongClickable(boolean longClickable) { 6365 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 6366 } 6367 6368 /** 6369 * Sets the pressed state for this view. 6370 * 6371 * @see #isClickable() 6372 * @see #setClickable(boolean) 6373 * 6374 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 6375 * the View's internal state from a previously set "pressed" state. 6376 */ 6377 public void setPressed(boolean pressed) { 6378 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 6379 6380 if (pressed) { 6381 mPrivateFlags |= PFLAG_PRESSED; 6382 } else { 6383 mPrivateFlags &= ~PFLAG_PRESSED; 6384 } 6385 6386 if (needsRefresh) { 6387 refreshDrawableState(); 6388 } 6389 dispatchSetPressed(pressed); 6390 } 6391 6392 /** 6393 * Dispatch setPressed to all of this View's children. 6394 * 6395 * @see #setPressed(boolean) 6396 * 6397 * @param pressed The new pressed state 6398 */ 6399 protected void dispatchSetPressed(boolean pressed) { 6400 } 6401 6402 /** 6403 * Indicates whether the view is currently in pressed state. Unless 6404 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 6405 * the pressed state. 6406 * 6407 * @see #setPressed(boolean) 6408 * @see #isClickable() 6409 * @see #setClickable(boolean) 6410 * 6411 * @return true if the view is currently pressed, false otherwise 6412 */ 6413 public boolean isPressed() { 6414 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 6415 } 6416 6417 /** 6418 * Indicates whether this view will save its state (that is, 6419 * whether its {@link #onSaveInstanceState} method will be called). 6420 * 6421 * @return Returns true if the view state saving is enabled, else false. 6422 * 6423 * @see #setSaveEnabled(boolean) 6424 * @attr ref android.R.styleable#View_saveEnabled 6425 */ 6426 public boolean isSaveEnabled() { 6427 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 6428 } 6429 6430 /** 6431 * Controls whether the saving of this view's state is 6432 * enabled (that is, whether its {@link #onSaveInstanceState} method 6433 * will be called). Note that even if freezing is enabled, the 6434 * view still must have an id assigned to it (via {@link #setId(int)}) 6435 * for its state to be saved. This flag can only disable the 6436 * saving of this view; any child views may still have their state saved. 6437 * 6438 * @param enabled Set to false to <em>disable</em> state saving, or true 6439 * (the default) to allow it. 6440 * 6441 * @see #isSaveEnabled() 6442 * @see #setId(int) 6443 * @see #onSaveInstanceState() 6444 * @attr ref android.R.styleable#View_saveEnabled 6445 */ 6446 public void setSaveEnabled(boolean enabled) { 6447 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 6448 } 6449 6450 /** 6451 * Gets whether the framework should discard touches when the view's 6452 * window is obscured by another visible window. 6453 * Refer to the {@link View} security documentation for more details. 6454 * 6455 * @return True if touch filtering is enabled. 6456 * 6457 * @see #setFilterTouchesWhenObscured(boolean) 6458 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6459 */ 6460 @ViewDebug.ExportedProperty 6461 public boolean getFilterTouchesWhenObscured() { 6462 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 6463 } 6464 6465 /** 6466 * Sets whether the framework should discard touches when the view's 6467 * window is obscured by another visible window. 6468 * Refer to the {@link View} security documentation for more details. 6469 * 6470 * @param enabled True if touch filtering should be enabled. 6471 * 6472 * @see #getFilterTouchesWhenObscured 6473 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6474 */ 6475 public void setFilterTouchesWhenObscured(boolean enabled) { 6476 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED, 6477 FILTER_TOUCHES_WHEN_OBSCURED); 6478 } 6479 6480 /** 6481 * Indicates whether the entire hierarchy under this view will save its 6482 * state when a state saving traversal occurs from its parent. The default 6483 * is true; if false, these views will not be saved unless 6484 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6485 * 6486 * @return Returns true if the view state saving from parent is enabled, else false. 6487 * 6488 * @see #setSaveFromParentEnabled(boolean) 6489 */ 6490 public boolean isSaveFromParentEnabled() { 6491 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 6492 } 6493 6494 /** 6495 * Controls whether the entire hierarchy under this view will save its 6496 * state when a state saving traversal occurs from its parent. The default 6497 * is true; if false, these views will not be saved unless 6498 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6499 * 6500 * @param enabled Set to false to <em>disable</em> state saving, or true 6501 * (the default) to allow it. 6502 * 6503 * @see #isSaveFromParentEnabled() 6504 * @see #setId(int) 6505 * @see #onSaveInstanceState() 6506 */ 6507 public void setSaveFromParentEnabled(boolean enabled) { 6508 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 6509 } 6510 6511 6512 /** 6513 * Returns whether this View is able to take focus. 6514 * 6515 * @return True if this view can take focus, or false otherwise. 6516 * @attr ref android.R.styleable#View_focusable 6517 */ 6518 @ViewDebug.ExportedProperty(category = "focus") 6519 public final boolean isFocusable() { 6520 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 6521 } 6522 6523 /** 6524 * When a view is focusable, it may not want to take focus when in touch mode. 6525 * For example, a button would like focus when the user is navigating via a D-pad 6526 * so that the user can click on it, but once the user starts touching the screen, 6527 * the button shouldn't take focus 6528 * @return Whether the view is focusable in touch mode. 6529 * @attr ref android.R.styleable#View_focusableInTouchMode 6530 */ 6531 @ViewDebug.ExportedProperty 6532 public final boolean isFocusableInTouchMode() { 6533 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 6534 } 6535 6536 /** 6537 * Find the nearest view in the specified direction that can take focus. 6538 * This does not actually give focus to that view. 6539 * 6540 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 6541 * 6542 * @return The nearest focusable in the specified direction, or null if none 6543 * can be found. 6544 */ 6545 public View focusSearch(int direction) { 6546 if (mParent != null) { 6547 return mParent.focusSearch(this, direction); 6548 } else { 6549 return null; 6550 } 6551 } 6552 6553 /** 6554 * This method is the last chance for the focused view and its ancestors to 6555 * respond to an arrow key. This is called when the focused view did not 6556 * consume the key internally, nor could the view system find a new view in 6557 * the requested direction to give focus to. 6558 * 6559 * @param focused The currently focused view. 6560 * @param direction The direction focus wants to move. One of FOCUS_UP, 6561 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 6562 * @return True if the this view consumed this unhandled move. 6563 */ 6564 public boolean dispatchUnhandledMove(View focused, int direction) { 6565 return false; 6566 } 6567 6568 /** 6569 * If a user manually specified the next view id for a particular direction, 6570 * use the root to look up the view. 6571 * @param root The root view of the hierarchy containing this view. 6572 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 6573 * or FOCUS_BACKWARD. 6574 * @return The user specified next view, or null if there is none. 6575 */ 6576 View findUserSetNextFocus(View root, int direction) { 6577 switch (direction) { 6578 case FOCUS_LEFT: 6579 if (mNextFocusLeftId == View.NO_ID) return null; 6580 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 6581 case FOCUS_RIGHT: 6582 if (mNextFocusRightId == View.NO_ID) return null; 6583 return findViewInsideOutShouldExist(root, mNextFocusRightId); 6584 case FOCUS_UP: 6585 if (mNextFocusUpId == View.NO_ID) return null; 6586 return findViewInsideOutShouldExist(root, mNextFocusUpId); 6587 case FOCUS_DOWN: 6588 if (mNextFocusDownId == View.NO_ID) return null; 6589 return findViewInsideOutShouldExist(root, mNextFocusDownId); 6590 case FOCUS_FORWARD: 6591 if (mNextFocusForwardId == View.NO_ID) return null; 6592 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 6593 case FOCUS_BACKWARD: { 6594 if (mID == View.NO_ID) return null; 6595 final int id = mID; 6596 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 6597 @Override 6598 public boolean apply(View t) { 6599 return t.mNextFocusForwardId == id; 6600 } 6601 }); 6602 } 6603 } 6604 return null; 6605 } 6606 6607 private View findViewInsideOutShouldExist(View root, int id) { 6608 if (mMatchIdPredicate == null) { 6609 mMatchIdPredicate = new MatchIdPredicate(); 6610 } 6611 mMatchIdPredicate.mId = id; 6612 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 6613 if (result == null) { 6614 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 6615 } 6616 return result; 6617 } 6618 6619 /** 6620 * Find and return all focusable views that are descendants of this view, 6621 * possibly including this view if it is focusable itself. 6622 * 6623 * @param direction The direction of the focus 6624 * @return A list of focusable views 6625 */ 6626 public ArrayList<View> getFocusables(int direction) { 6627 ArrayList<View> result = new ArrayList<View>(24); 6628 addFocusables(result, direction); 6629 return result; 6630 } 6631 6632 /** 6633 * Add any focusable views that are descendants of this view (possibly 6634 * including this view if it is focusable itself) to views. If we are in touch mode, 6635 * only add views that are also focusable in touch mode. 6636 * 6637 * @param views Focusable views found so far 6638 * @param direction The direction of the focus 6639 */ 6640 public void addFocusables(ArrayList<View> views, int direction) { 6641 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 6642 } 6643 6644 /** 6645 * Adds any focusable views that are descendants of this view (possibly 6646 * including this view if it is focusable itself) to views. This method 6647 * adds all focusable views regardless if we are in touch mode or 6648 * only views focusable in touch mode if we are in touch mode or 6649 * only views that can take accessibility focus if accessibility is enabeld 6650 * depending on the focusable mode paramater. 6651 * 6652 * @param views Focusable views found so far or null if all we are interested is 6653 * the number of focusables. 6654 * @param direction The direction of the focus. 6655 * @param focusableMode The type of focusables to be added. 6656 * 6657 * @see #FOCUSABLES_ALL 6658 * @see #FOCUSABLES_TOUCH_MODE 6659 */ 6660 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { 6661 if (views == null) { 6662 return; 6663 } 6664 if (!isFocusable()) { 6665 return; 6666 } 6667 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 6668 && isInTouchMode() && !isFocusableInTouchMode()) { 6669 return; 6670 } 6671 views.add(this); 6672 } 6673 6674 /** 6675 * Finds the Views that contain given text. The containment is case insensitive. 6676 * The search is performed by either the text that the View renders or the content 6677 * description that describes the view for accessibility purposes and the view does 6678 * not render or both. Clients can specify how the search is to be performed via 6679 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 6680 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 6681 * 6682 * @param outViews The output list of matching Views. 6683 * @param searched The text to match against. 6684 * 6685 * @see #FIND_VIEWS_WITH_TEXT 6686 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 6687 * @see #setContentDescription(CharSequence) 6688 */ 6689 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) { 6690 if (getAccessibilityNodeProvider() != null) { 6691 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 6692 outViews.add(this); 6693 } 6694 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 6695 && (searched != null && searched.length() > 0) 6696 && (mContentDescription != null && mContentDescription.length() > 0)) { 6697 String searchedLowerCase = searched.toString().toLowerCase(); 6698 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 6699 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 6700 outViews.add(this); 6701 } 6702 } 6703 } 6704 6705 /** 6706 * Find and return all touchable views that are descendants of this view, 6707 * possibly including this view if it is touchable itself. 6708 * 6709 * @return A list of touchable views 6710 */ 6711 public ArrayList<View> getTouchables() { 6712 ArrayList<View> result = new ArrayList<View>(); 6713 addTouchables(result); 6714 return result; 6715 } 6716 6717 /** 6718 * Add any touchable views that are descendants of this view (possibly 6719 * including this view if it is touchable itself) to views. 6720 * 6721 * @param views Touchable views found so far 6722 */ 6723 public void addTouchables(ArrayList<View> views) { 6724 final int viewFlags = mViewFlags; 6725 6726 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 6727 && (viewFlags & ENABLED_MASK) == ENABLED) { 6728 views.add(this); 6729 } 6730 } 6731 6732 /** 6733 * Returns whether this View is accessibility focused. 6734 * 6735 * @return True if this View is accessibility focused. 6736 * @hide 6737 */ 6738 public boolean isAccessibilityFocused() { 6739 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 6740 } 6741 6742 /** 6743 * Call this to try to give accessibility focus to this view. 6744 * 6745 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 6746 * returns false or the view is no visible or the view already has accessibility 6747 * focus. 6748 * 6749 * See also {@link #focusSearch(int)}, which is what you call to say that you 6750 * have focus, and you want your parent to look for the next one. 6751 * 6752 * @return Whether this view actually took accessibility focus. 6753 * 6754 * @hide 6755 */ 6756 public boolean requestAccessibilityFocus() { 6757 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 6758 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 6759 return false; 6760 } 6761 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 6762 return false; 6763 } 6764 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 6765 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 6766 ViewRootImpl viewRootImpl = getViewRootImpl(); 6767 if (viewRootImpl != null) { 6768 viewRootImpl.setAccessibilityFocus(this, null); 6769 } 6770 invalidate(); 6771 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 6772 return true; 6773 } 6774 return false; 6775 } 6776 6777 /** 6778 * Call this to try to clear accessibility focus of this view. 6779 * 6780 * See also {@link #focusSearch(int)}, which is what you call to say that you 6781 * have focus, and you want your parent to look for the next one. 6782 * 6783 * @hide 6784 */ 6785 public void clearAccessibilityFocus() { 6786 clearAccessibilityFocusNoCallbacks(); 6787 // Clear the global reference of accessibility focus if this 6788 // view or any of its descendants had accessibility focus. 6789 ViewRootImpl viewRootImpl = getViewRootImpl(); 6790 if (viewRootImpl != null) { 6791 View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 6792 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 6793 viewRootImpl.setAccessibilityFocus(null, null); 6794 } 6795 } 6796 } 6797 6798 private void sendAccessibilityHoverEvent(int eventType) { 6799 // Since we are not delivering to a client accessibility events from not 6800 // important views (unless the clinet request that) we need to fire the 6801 // event from the deepest view exposed to the client. As a consequence if 6802 // the user crosses a not exposed view the client will see enter and exit 6803 // of the exposed predecessor followed by and enter and exit of that same 6804 // predecessor when entering and exiting the not exposed descendant. This 6805 // is fine since the client has a clear idea which view is hovered at the 6806 // price of a couple more events being sent. This is a simple and 6807 // working solution. 6808 View source = this; 6809 while (true) { 6810 if (source.includeForAccessibility()) { 6811 source.sendAccessibilityEvent(eventType); 6812 return; 6813 } 6814 ViewParent parent = source.getParent(); 6815 if (parent instanceof View) { 6816 source = (View) parent; 6817 } else { 6818 return; 6819 } 6820 } 6821 } 6822 6823 /** 6824 * Clears accessibility focus without calling any callback methods 6825 * normally invoked in {@link #clearAccessibilityFocus()}. This method 6826 * is used for clearing accessibility focus when giving this focus to 6827 * another view. 6828 */ 6829 void clearAccessibilityFocusNoCallbacks() { 6830 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 6831 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 6832 invalidate(); 6833 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 6834 } 6835 } 6836 6837 /** 6838 * Call this to try to give focus to a specific view or to one of its 6839 * descendants. 6840 * 6841 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 6842 * false), or if it is focusable and it is not focusable in touch mode 6843 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 6844 * 6845 * See also {@link #focusSearch(int)}, which is what you call to say that you 6846 * have focus, and you want your parent to look for the next one. 6847 * 6848 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 6849 * {@link #FOCUS_DOWN} and <code>null</code>. 6850 * 6851 * @return Whether this view or one of its descendants actually took focus. 6852 */ 6853 public final boolean requestFocus() { 6854 return requestFocus(View.FOCUS_DOWN); 6855 } 6856 6857 /** 6858 * Call this to try to give focus to a specific view or to one of its 6859 * descendants and give it a hint about what direction focus is heading. 6860 * 6861 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 6862 * false), or if it is focusable and it is not focusable in touch mode 6863 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 6864 * 6865 * See also {@link #focusSearch(int)}, which is what you call to say that you 6866 * have focus, and you want your parent to look for the next one. 6867 * 6868 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 6869 * <code>null</code> set for the previously focused rectangle. 6870 * 6871 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 6872 * @return Whether this view or one of its descendants actually took focus. 6873 */ 6874 public final boolean requestFocus(int direction) { 6875 return requestFocus(direction, null); 6876 } 6877 6878 /** 6879 * Call this to try to give focus to a specific view or to one of its descendants 6880 * and give it hints about the direction and a specific rectangle that the focus 6881 * is coming from. The rectangle can help give larger views a finer grained hint 6882 * about where focus is coming from, and therefore, where to show selection, or 6883 * forward focus change internally. 6884 * 6885 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 6886 * false), or if it is focusable and it is not focusable in touch mode 6887 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 6888 * 6889 * A View will not take focus if it is not visible. 6890 * 6891 * A View will not take focus if one of its parents has 6892 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 6893 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 6894 * 6895 * See also {@link #focusSearch(int)}, which is what you call to say that you 6896 * have focus, and you want your parent to look for the next one. 6897 * 6898 * You may wish to override this method if your custom {@link View} has an internal 6899 * {@link View} that it wishes to forward the request to. 6900 * 6901 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 6902 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 6903 * to give a finer grained hint about where focus is coming from. May be null 6904 * if there is no hint. 6905 * @return Whether this view or one of its descendants actually took focus. 6906 */ 6907 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 6908 return requestFocusNoSearch(direction, previouslyFocusedRect); 6909 } 6910 6911 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 6912 // need to be focusable 6913 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 6914 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 6915 return false; 6916 } 6917 6918 // need to be focusable in touch mode if in touch mode 6919 if (isInTouchMode() && 6920 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 6921 return false; 6922 } 6923 6924 // need to not have any parents blocking us 6925 if (hasAncestorThatBlocksDescendantFocus()) { 6926 return false; 6927 } 6928 6929 handleFocusGainInternal(direction, previouslyFocusedRect); 6930 return true; 6931 } 6932 6933 /** 6934 * Call this to try to give focus to a specific view or to one of its descendants. This is a 6935 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 6936 * touch mode to request focus when they are touched. 6937 * 6938 * @return Whether this view or one of its descendants actually took focus. 6939 * 6940 * @see #isInTouchMode() 6941 * 6942 */ 6943 public final boolean requestFocusFromTouch() { 6944 // Leave touch mode if we need to 6945 if (isInTouchMode()) { 6946 ViewRootImpl viewRoot = getViewRootImpl(); 6947 if (viewRoot != null) { 6948 viewRoot.ensureTouchMode(false); 6949 } 6950 } 6951 return requestFocus(View.FOCUS_DOWN); 6952 } 6953 6954 /** 6955 * @return Whether any ancestor of this view blocks descendant focus. 6956 */ 6957 private boolean hasAncestorThatBlocksDescendantFocus() { 6958 ViewParent ancestor = mParent; 6959 while (ancestor instanceof ViewGroup) { 6960 final ViewGroup vgAncestor = (ViewGroup) ancestor; 6961 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) { 6962 return true; 6963 } else { 6964 ancestor = vgAncestor.getParent(); 6965 } 6966 } 6967 return false; 6968 } 6969 6970 /** 6971 * Gets the mode for determining whether this View is important for accessibility 6972 * which is if it fires accessibility events and if it is reported to 6973 * accessibility services that query the screen. 6974 * 6975 * @return The mode for determining whether a View is important for accessibility. 6976 * 6977 * @attr ref android.R.styleable#View_importantForAccessibility 6978 * 6979 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 6980 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 6981 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 6982 */ 6983 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 6984 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 6985 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 6986 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no") 6987 }) 6988 public int getImportantForAccessibility() { 6989 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 6990 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 6991 } 6992 6993 /** 6994 * Sets how to determine whether this view is important for accessibility 6995 * which is if it fires accessibility events and if it is reported to 6996 * accessibility services that query the screen. 6997 * 6998 * @param mode How to determine whether this view is important for accessibility. 6999 * 7000 * @attr ref android.R.styleable#View_importantForAccessibility 7001 * 7002 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7003 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7004 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7005 */ 7006 public void setImportantForAccessibility(int mode) { 7007 final boolean oldIncludeForAccessibility = includeForAccessibility(); 7008 if (mode != getImportantForAccessibility()) { 7009 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7010 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 7011 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7012 if (oldIncludeForAccessibility != includeForAccessibility()) { 7013 notifySubtreeAccessibilityStateChangedIfNeeded(); 7014 } else { 7015 notifyViewAccessibilityStateChangedIfNeeded(); 7016 } 7017 } 7018 } 7019 7020 /** 7021 * Gets whether this view should be exposed for accessibility. 7022 * 7023 * @return Whether the view is exposed for accessibility. 7024 * 7025 * @hide 7026 */ 7027 public boolean isImportantForAccessibility() { 7028 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7029 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7030 switch (mode) { 7031 case IMPORTANT_FOR_ACCESSIBILITY_YES: 7032 return true; 7033 case IMPORTANT_FOR_ACCESSIBILITY_NO: 7034 return false; 7035 case IMPORTANT_FOR_ACCESSIBILITY_AUTO: 7036 return isActionableForAccessibility() || hasListenersForAccessibility() 7037 || getAccessibilityNodeProvider() != null; 7038 default: 7039 throw new IllegalArgumentException("Unknow important for accessibility mode: " 7040 + mode); 7041 } 7042 } 7043 7044 /** 7045 * Gets the parent for accessibility purposes. Note that the parent for 7046 * accessibility is not necessary the immediate parent. It is the first 7047 * predecessor that is important for accessibility. 7048 * 7049 * @return The parent for accessibility purposes. 7050 */ 7051 public ViewParent getParentForAccessibility() { 7052 if (mParent instanceof View) { 7053 View parentView = (View) mParent; 7054 if (parentView.includeForAccessibility()) { 7055 return mParent; 7056 } else { 7057 return mParent.getParentForAccessibility(); 7058 } 7059 } 7060 return null; 7061 } 7062 7063 /** 7064 * Adds the children of a given View for accessibility. Since some Views are 7065 * not important for accessibility the children for accessibility are not 7066 * necessarily direct children of the view, rather they are the first level of 7067 * descendants important for accessibility. 7068 * 7069 * @param children The list of children for accessibility. 7070 */ 7071 public void addChildrenForAccessibility(ArrayList<View> children) { 7072 if (includeForAccessibility()) { 7073 children.add(this); 7074 } 7075 } 7076 7077 /** 7078 * Whether to regard this view for accessibility. A view is regarded for 7079 * accessibility if it is important for accessibility or the querying 7080 * accessibility service has explicitly requested that view not 7081 * important for accessibility are regarded. 7082 * 7083 * @return Whether to regard the view for accessibility. 7084 * 7085 * @hide 7086 */ 7087 public boolean includeForAccessibility() { 7088 //noinspection SimplifiableIfStatement 7089 if (mAttachInfo != null) { 7090 return (mAttachInfo.mAccessibilityFetchFlags 7091 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0 7092 || isImportantForAccessibility(); 7093 } 7094 return false; 7095 } 7096 7097 /** 7098 * Returns whether the View is considered actionable from 7099 * accessibility perspective. Such view are important for 7100 * accessibility. 7101 * 7102 * @return True if the view is actionable for accessibility. 7103 * 7104 * @hide 7105 */ 7106 public boolean isActionableForAccessibility() { 7107 return (isClickable() || isLongClickable() || isFocusable()); 7108 } 7109 7110 /** 7111 * Returns whether the View has registered callbacks wich makes it 7112 * important for accessibility. 7113 * 7114 * @return True if the view is actionable for accessibility. 7115 */ 7116 private boolean hasListenersForAccessibility() { 7117 ListenerInfo info = getListenerInfo(); 7118 return mTouchDelegate != null || info.mOnKeyListener != null 7119 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 7120 || info.mOnHoverListener != null || info.mOnDragListener != null; 7121 } 7122 7123 /** 7124 * Notifies that the accessibility state of this view changed. The change 7125 * is local to this view and does not represent structural changes such 7126 * as children and parent. For example, the view became focusable. The 7127 * notification is at at most once every 7128 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7129 * to avoid unnecessary load to the system. Also once a view has a pending 7130 * notifucation this method is a NOP until the notification has been sent. 7131 * 7132 * @hide 7133 */ 7134 public void notifyViewAccessibilityStateChangedIfNeeded() { 7135 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7136 return; 7137 } 7138 if (mSendViewStateChangedAccessibilityEvent == null) { 7139 mSendViewStateChangedAccessibilityEvent = 7140 new SendViewStateChangedAccessibilityEvent(); 7141 } 7142 mSendViewStateChangedAccessibilityEvent.runOrPost(); 7143 } 7144 7145 /** 7146 * Notifies that the accessibility state of this view changed. The change 7147 * is *not* local to this view and does represent structural changes such 7148 * as children and parent. For example, the view size changed. The 7149 * notification is at at most once every 7150 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7151 * to avoid unnecessary load to the system. Also once a view has a pending 7152 * notifucation this method is a NOP until the notification has been sent. 7153 * 7154 * @hide 7155 */ 7156 public void notifySubtreeAccessibilityStateChangedIfNeeded() { 7157 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7158 return; 7159 } 7160 if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) { 7161 mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 7162 if (mParent != null) { 7163 try { 7164 mParent.childAccessibilityStateChanged(this); 7165 } catch (AbstractMethodError e) { 7166 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 7167 " does not fully implement ViewParent", e); 7168 } 7169 } 7170 } 7171 } 7172 7173 /** 7174 * Reset the flag indicating the accessibility state of the subtree rooted 7175 * at this view changed. 7176 */ 7177 void resetSubtreeAccessibilityStateChanged() { 7178 mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 7179 } 7180 7181 /** 7182 * Performs the specified accessibility action on the view. For 7183 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 7184 * <p> 7185 * If an {@link AccessibilityDelegate} has been specified via calling 7186 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 7187 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 7188 * is responsible for handling this call. 7189 * </p> 7190 * 7191 * @param action The action to perform. 7192 * @param arguments Optional action arguments. 7193 * @return Whether the action was performed. 7194 */ 7195 public boolean performAccessibilityAction(int action, Bundle arguments) { 7196 if (mAccessibilityDelegate != null) { 7197 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 7198 } else { 7199 return performAccessibilityActionInternal(action, arguments); 7200 } 7201 } 7202 7203 /** 7204 * @see #performAccessibilityAction(int, Bundle) 7205 * 7206 * Note: Called from the default {@link AccessibilityDelegate}. 7207 */ 7208 boolean performAccessibilityActionInternal(int action, Bundle arguments) { 7209 switch (action) { 7210 case AccessibilityNodeInfo.ACTION_CLICK: { 7211 if (isClickable()) { 7212 performClick(); 7213 return true; 7214 } 7215 } break; 7216 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 7217 if (isLongClickable()) { 7218 performLongClick(); 7219 return true; 7220 } 7221 } break; 7222 case AccessibilityNodeInfo.ACTION_FOCUS: { 7223 if (!hasFocus()) { 7224 // Get out of touch mode since accessibility 7225 // wants to move focus around. 7226 getViewRootImpl().ensureTouchMode(false); 7227 return requestFocus(); 7228 } 7229 } break; 7230 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 7231 if (hasFocus()) { 7232 clearFocus(); 7233 return !isFocused(); 7234 } 7235 } break; 7236 case AccessibilityNodeInfo.ACTION_SELECT: { 7237 if (!isSelected()) { 7238 setSelected(true); 7239 return isSelected(); 7240 } 7241 } break; 7242 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 7243 if (isSelected()) { 7244 setSelected(false); 7245 return !isSelected(); 7246 } 7247 } break; 7248 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 7249 if (!isAccessibilityFocused()) { 7250 return requestAccessibilityFocus(); 7251 } 7252 } break; 7253 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 7254 if (isAccessibilityFocused()) { 7255 clearAccessibilityFocus(); 7256 return true; 7257 } 7258 } break; 7259 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 7260 if (arguments != null) { 7261 final int granularity = arguments.getInt( 7262 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 7263 final boolean extendSelection = arguments.getBoolean( 7264 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 7265 return traverseAtGranularity(granularity, true, extendSelection); 7266 } 7267 } break; 7268 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 7269 if (arguments != null) { 7270 final int granularity = arguments.getInt( 7271 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 7272 final boolean extendSelection = arguments.getBoolean( 7273 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 7274 return traverseAtGranularity(granularity, false, extendSelection); 7275 } 7276 } break; 7277 case AccessibilityNodeInfo.ACTION_SET_SELECTION: { 7278 CharSequence text = getIterableTextForAccessibility(); 7279 if (text == null) { 7280 return false; 7281 } 7282 final int start = (arguments != null) ? arguments.getInt( 7283 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1; 7284 final int end = (arguments != null) ? arguments.getInt( 7285 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1; 7286 // Only cursor position can be specified (selection length == 0) 7287 if ((getAccessibilitySelectionStart() != start 7288 || getAccessibilitySelectionEnd() != end) 7289 && (start == end)) { 7290 setAccessibilitySelection(start, end); 7291 notifyViewAccessibilityStateChangedIfNeeded(); 7292 return true; 7293 } 7294 } break; 7295 } 7296 return false; 7297 } 7298 7299 private boolean traverseAtGranularity(int granularity, boolean forward, 7300 boolean extendSelection) { 7301 CharSequence text = getIterableTextForAccessibility(); 7302 if (text == null || text.length() == 0) { 7303 return false; 7304 } 7305 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 7306 if (iterator == null) { 7307 return false; 7308 } 7309 int current = getAccessibilitySelectionEnd(); 7310 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 7311 current = forward ? 0 : text.length(); 7312 } 7313 final int[] range = forward ? iterator.following(current) : iterator.preceding(current); 7314 if (range == null) { 7315 return false; 7316 } 7317 final int segmentStart = range[0]; 7318 final int segmentEnd = range[1]; 7319 int selectionStart; 7320 int selectionEnd; 7321 if (extendSelection && isAccessibilitySelectionExtendable()) { 7322 selectionStart = getAccessibilitySelectionStart(); 7323 if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 7324 selectionStart = forward ? segmentStart : segmentEnd; 7325 } 7326 selectionEnd = forward ? segmentEnd : segmentStart; 7327 } else { 7328 selectionStart = selectionEnd= forward ? segmentEnd : segmentStart; 7329 } 7330 setAccessibilitySelection(selectionStart, selectionEnd); 7331 final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY 7332 : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY; 7333 sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd); 7334 return true; 7335 } 7336 7337 /** 7338 * Gets the text reported for accessibility purposes. 7339 * 7340 * @return The accessibility text. 7341 * 7342 * @hide 7343 */ 7344 public CharSequence getIterableTextForAccessibility() { 7345 return getContentDescription(); 7346 } 7347 7348 /** 7349 * Gets whether accessibility selection can be extended. 7350 * 7351 * @return If selection is extensible. 7352 * 7353 * @hide 7354 */ 7355 public boolean isAccessibilitySelectionExtendable() { 7356 return false; 7357 } 7358 7359 /** 7360 * @hide 7361 */ 7362 public int getAccessibilitySelectionStart() { 7363 return mAccessibilityCursorPosition; 7364 } 7365 7366 /** 7367 * @hide 7368 */ 7369 public int getAccessibilitySelectionEnd() { 7370 return getAccessibilitySelectionStart(); 7371 } 7372 7373 /** 7374 * @hide 7375 */ 7376 public void setAccessibilitySelection(int start, int end) { 7377 if (start == end && end == mAccessibilityCursorPosition) { 7378 return; 7379 } 7380 if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) { 7381 mAccessibilityCursorPosition = start; 7382 } else { 7383 mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 7384 } 7385 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 7386 } 7387 7388 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 7389 int fromIndex, int toIndex) { 7390 if (mParent == null) { 7391 return; 7392 } 7393 AccessibilityEvent event = AccessibilityEvent.obtain( 7394 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 7395 onInitializeAccessibilityEvent(event); 7396 onPopulateAccessibilityEvent(event); 7397 event.setFromIndex(fromIndex); 7398 event.setToIndex(toIndex); 7399 event.setAction(action); 7400 event.setMovementGranularity(granularity); 7401 mParent.requestSendAccessibilityEvent(this, event); 7402 } 7403 7404 /** 7405 * @hide 7406 */ 7407 public TextSegmentIterator getIteratorForGranularity(int granularity) { 7408 switch (granularity) { 7409 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 7410 CharSequence text = getIterableTextForAccessibility(); 7411 if (text != null && text.length() > 0) { 7412 CharacterTextSegmentIterator iterator = 7413 CharacterTextSegmentIterator.getInstance( 7414 mContext.getResources().getConfiguration().locale); 7415 iterator.initialize(text.toString()); 7416 return iterator; 7417 } 7418 } break; 7419 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 7420 CharSequence text = getIterableTextForAccessibility(); 7421 if (text != null && text.length() > 0) { 7422 WordTextSegmentIterator iterator = 7423 WordTextSegmentIterator.getInstance( 7424 mContext.getResources().getConfiguration().locale); 7425 iterator.initialize(text.toString()); 7426 return iterator; 7427 } 7428 } break; 7429 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 7430 CharSequence text = getIterableTextForAccessibility(); 7431 if (text != null && text.length() > 0) { 7432 ParagraphTextSegmentIterator iterator = 7433 ParagraphTextSegmentIterator.getInstance(); 7434 iterator.initialize(text.toString()); 7435 return iterator; 7436 } 7437 } break; 7438 } 7439 return null; 7440 } 7441 7442 /** 7443 * @hide 7444 */ 7445 public void dispatchStartTemporaryDetach() { 7446 clearDisplayList(); 7447 7448 onStartTemporaryDetach(); 7449 } 7450 7451 /** 7452 * This is called when a container is going to temporarily detach a child, with 7453 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 7454 * It will either be followed by {@link #onFinishTemporaryDetach()} or 7455 * {@link #onDetachedFromWindow()} when the container is done. 7456 */ 7457 public void onStartTemporaryDetach() { 7458 removeUnsetPressCallback(); 7459 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 7460 } 7461 7462 /** 7463 * @hide 7464 */ 7465 public void dispatchFinishTemporaryDetach() { 7466 onFinishTemporaryDetach(); 7467 } 7468 7469 /** 7470 * Called after {@link #onStartTemporaryDetach} when the container is done 7471 * changing the view. 7472 */ 7473 public void onFinishTemporaryDetach() { 7474 } 7475 7476 /** 7477 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 7478 * for this view's window. Returns null if the view is not currently attached 7479 * to the window. Normally you will not need to use this directly, but 7480 * just use the standard high-level event callbacks like 7481 * {@link #onKeyDown(int, KeyEvent)}. 7482 */ 7483 public KeyEvent.DispatcherState getKeyDispatcherState() { 7484 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 7485 } 7486 7487 /** 7488 * Dispatch a key event before it is processed by any input method 7489 * associated with the view hierarchy. This can be used to intercept 7490 * key events in special situations before the IME consumes them; a 7491 * typical example would be handling the BACK key to update the application's 7492 * UI instead of allowing the IME to see it and close itself. 7493 * 7494 * @param event The key event to be dispatched. 7495 * @return True if the event was handled, false otherwise. 7496 */ 7497 public boolean dispatchKeyEventPreIme(KeyEvent event) { 7498 return onKeyPreIme(event.getKeyCode(), event); 7499 } 7500 7501 /** 7502 * Dispatch a key event to the next view on the focus path. This path runs 7503 * from the top of the view tree down to the currently focused view. If this 7504 * view has focus, it will dispatch to itself. Otherwise it will dispatch 7505 * the next node down the focus path. This method also fires any key 7506 * listeners. 7507 * 7508 * @param event The key event to be dispatched. 7509 * @return True if the event was handled, false otherwise. 7510 */ 7511 public boolean dispatchKeyEvent(KeyEvent event) { 7512 if (mInputEventConsistencyVerifier != null) { 7513 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 7514 } 7515 7516 // Give any attached key listener a first crack at the event. 7517 //noinspection SimplifiableIfStatement 7518 ListenerInfo li = mListenerInfo; 7519 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 7520 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 7521 return true; 7522 } 7523 7524 if (event.dispatch(this, mAttachInfo != null 7525 ? mAttachInfo.mKeyDispatchState : null, this)) { 7526 return true; 7527 } 7528 7529 if (mInputEventConsistencyVerifier != null) { 7530 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7531 } 7532 return false; 7533 } 7534 7535 /** 7536 * Dispatches a key shortcut event. 7537 * 7538 * @param event The key event to be dispatched. 7539 * @return True if the event was handled by the view, false otherwise. 7540 */ 7541 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 7542 return onKeyShortcut(event.getKeyCode(), event); 7543 } 7544 7545 /** 7546 * Pass the touch screen motion event down to the target view, or this 7547 * view if it is the target. 7548 * 7549 * @param event The motion event to be dispatched. 7550 * @return True if the event was handled by the view, false otherwise. 7551 */ 7552 public boolean dispatchTouchEvent(MotionEvent event) { 7553 if (mInputEventConsistencyVerifier != null) { 7554 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 7555 } 7556 7557 if (onFilterTouchEventForSecurity(event)) { 7558 //noinspection SimplifiableIfStatement 7559 ListenerInfo li = mListenerInfo; 7560 if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 7561 && li.mOnTouchListener.onTouch(this, event)) { 7562 return true; 7563 } 7564 7565 if (onTouchEvent(event)) { 7566 return true; 7567 } 7568 } 7569 7570 if (mInputEventConsistencyVerifier != null) { 7571 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7572 } 7573 return false; 7574 } 7575 7576 /** 7577 * Filter the touch event to apply security policies. 7578 * 7579 * @param event The motion event to be filtered. 7580 * @return True if the event should be dispatched, false if the event should be dropped. 7581 * 7582 * @see #getFilterTouchesWhenObscured 7583 */ 7584 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 7585 //noinspection RedundantIfStatement 7586 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 7587 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 7588 // Window is obscured, drop this touch. 7589 return false; 7590 } 7591 return true; 7592 } 7593 7594 /** 7595 * Pass a trackball motion event down to the focused view. 7596 * 7597 * @param event The motion event to be dispatched. 7598 * @return True if the event was handled by the view, false otherwise. 7599 */ 7600 public boolean dispatchTrackballEvent(MotionEvent event) { 7601 if (mInputEventConsistencyVerifier != null) { 7602 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 7603 } 7604 7605 return onTrackballEvent(event); 7606 } 7607 7608 /** 7609 * Dispatch a generic motion event. 7610 * <p> 7611 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 7612 * are delivered to the view under the pointer. All other generic motion events are 7613 * delivered to the focused view. Hover events are handled specially and are delivered 7614 * to {@link #onHoverEvent(MotionEvent)}. 7615 * </p> 7616 * 7617 * @param event The motion event to be dispatched. 7618 * @return True if the event was handled by the view, false otherwise. 7619 */ 7620 public boolean dispatchGenericMotionEvent(MotionEvent event) { 7621 if (mInputEventConsistencyVerifier != null) { 7622 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 7623 } 7624 7625 final int source = event.getSource(); 7626 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 7627 final int action = event.getAction(); 7628 if (action == MotionEvent.ACTION_HOVER_ENTER 7629 || action == MotionEvent.ACTION_HOVER_MOVE 7630 || action == MotionEvent.ACTION_HOVER_EXIT) { 7631 if (dispatchHoverEvent(event)) { 7632 return true; 7633 } 7634 } else if (dispatchGenericPointerEvent(event)) { 7635 return true; 7636 } 7637 } else if (dispatchGenericFocusedEvent(event)) { 7638 return true; 7639 } 7640 7641 if (dispatchGenericMotionEventInternal(event)) { 7642 return true; 7643 } 7644 7645 if (mInputEventConsistencyVerifier != null) { 7646 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7647 } 7648 return false; 7649 } 7650 7651 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 7652 //noinspection SimplifiableIfStatement 7653 ListenerInfo li = mListenerInfo; 7654 if (li != null && li.mOnGenericMotionListener != null 7655 && (mViewFlags & ENABLED_MASK) == ENABLED 7656 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 7657 return true; 7658 } 7659 7660 if (onGenericMotionEvent(event)) { 7661 return true; 7662 } 7663 7664 if (mInputEventConsistencyVerifier != null) { 7665 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7666 } 7667 return false; 7668 } 7669 7670 /** 7671 * Dispatch a hover event. 7672 * <p> 7673 * Do not call this method directly. 7674 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 7675 * </p> 7676 * 7677 * @param event The motion event to be dispatched. 7678 * @return True if the event was handled by the view, false otherwise. 7679 */ 7680 protected boolean dispatchHoverEvent(MotionEvent event) { 7681 ListenerInfo li = mListenerInfo; 7682 //noinspection SimplifiableIfStatement 7683 if (li != null && li.mOnHoverListener != null 7684 && (mViewFlags & ENABLED_MASK) == ENABLED 7685 && li.mOnHoverListener.onHover(this, event)) { 7686 return true; 7687 } 7688 7689 return onHoverEvent(event); 7690 } 7691 7692 /** 7693 * Returns true if the view has a child to which it has recently sent 7694 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 7695 * it does not have a hovered child, then it must be the innermost hovered view. 7696 * @hide 7697 */ 7698 protected boolean hasHoveredChild() { 7699 return false; 7700 } 7701 7702 /** 7703 * Dispatch a generic motion event to the view under the first pointer. 7704 * <p> 7705 * Do not call this method directly. 7706 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 7707 * </p> 7708 * 7709 * @param event The motion event to be dispatched. 7710 * @return True if the event was handled by the view, false otherwise. 7711 */ 7712 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 7713 return false; 7714 } 7715 7716 /** 7717 * Dispatch a generic motion event to the currently focused view. 7718 * <p> 7719 * Do not call this method directly. 7720 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 7721 * </p> 7722 * 7723 * @param event The motion event to be dispatched. 7724 * @return True if the event was handled by the view, false otherwise. 7725 */ 7726 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 7727 return false; 7728 } 7729 7730 /** 7731 * Dispatch a pointer event. 7732 * <p> 7733 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 7734 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 7735 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 7736 * and should not be expected to handle other pointing device features. 7737 * </p> 7738 * 7739 * @param event The motion event to be dispatched. 7740 * @return True if the event was handled by the view, false otherwise. 7741 * @hide 7742 */ 7743 public final boolean dispatchPointerEvent(MotionEvent event) { 7744 if (event.isTouchEvent()) { 7745 return dispatchTouchEvent(event); 7746 } else { 7747 return dispatchGenericMotionEvent(event); 7748 } 7749 } 7750 7751 /** 7752 * Called when the window containing this view gains or loses window focus. 7753 * ViewGroups should override to route to their children. 7754 * 7755 * @param hasFocus True if the window containing this view now has focus, 7756 * false otherwise. 7757 */ 7758 public void dispatchWindowFocusChanged(boolean hasFocus) { 7759 onWindowFocusChanged(hasFocus); 7760 } 7761 7762 /** 7763 * Called when the window containing this view gains or loses focus. Note 7764 * that this is separate from view focus: to receive key events, both 7765 * your view and its window must have focus. If a window is displayed 7766 * on top of yours that takes input focus, then your own window will lose 7767 * focus but the view focus will remain unchanged. 7768 * 7769 * @param hasWindowFocus True if the window containing this view now has 7770 * focus, false otherwise. 7771 */ 7772 public void onWindowFocusChanged(boolean hasWindowFocus) { 7773 InputMethodManager imm = InputMethodManager.peekInstance(); 7774 if (!hasWindowFocus) { 7775 if (isPressed()) { 7776 setPressed(false); 7777 } 7778 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 7779 imm.focusOut(this); 7780 } 7781 removeLongPressCallback(); 7782 removeTapCallback(); 7783 onFocusLost(); 7784 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 7785 imm.focusIn(this); 7786 } 7787 refreshDrawableState(); 7788 } 7789 7790 /** 7791 * Returns true if this view is in a window that currently has window focus. 7792 * Note that this is not the same as the view itself having focus. 7793 * 7794 * @return True if this view is in a window that currently has window focus. 7795 */ 7796 public boolean hasWindowFocus() { 7797 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 7798 } 7799 7800 /** 7801 * Dispatch a view visibility change down the view hierarchy. 7802 * ViewGroups should override to route to their children. 7803 * @param changedView The view whose visibility changed. Could be 'this' or 7804 * an ancestor view. 7805 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 7806 * {@link #INVISIBLE} or {@link #GONE}. 7807 */ 7808 protected void dispatchVisibilityChanged(View changedView, int visibility) { 7809 onVisibilityChanged(changedView, visibility); 7810 } 7811 7812 /** 7813 * Called when the visibility of the view or an ancestor of the view is changed. 7814 * @param changedView The view whose visibility changed. Could be 'this' or 7815 * an ancestor view. 7816 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 7817 * {@link #INVISIBLE} or {@link #GONE}. 7818 */ 7819 protected void onVisibilityChanged(View changedView, int visibility) { 7820 if (visibility == VISIBLE) { 7821 if (mAttachInfo != null) { 7822 initialAwakenScrollBars(); 7823 } else { 7824 mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 7825 } 7826 } 7827 } 7828 7829 /** 7830 * Dispatch a hint about whether this view is displayed. For instance, when 7831 * a View moves out of the screen, it might receives a display hint indicating 7832 * the view is not displayed. Applications should not <em>rely</em> on this hint 7833 * as there is no guarantee that they will receive one. 7834 * 7835 * @param hint A hint about whether or not this view is displayed: 7836 * {@link #VISIBLE} or {@link #INVISIBLE}. 7837 */ 7838 public void dispatchDisplayHint(int hint) { 7839 onDisplayHint(hint); 7840 } 7841 7842 /** 7843 * Gives this view a hint about whether is displayed or not. For instance, when 7844 * a View moves out of the screen, it might receives a display hint indicating 7845 * the view is not displayed. Applications should not <em>rely</em> on this hint 7846 * as there is no guarantee that they will receive one. 7847 * 7848 * @param hint A hint about whether or not this view is displayed: 7849 * {@link #VISIBLE} or {@link #INVISIBLE}. 7850 */ 7851 protected void onDisplayHint(int hint) { 7852 } 7853 7854 /** 7855 * Dispatch a window visibility change down the view hierarchy. 7856 * ViewGroups should override to route to their children. 7857 * 7858 * @param visibility The new visibility of the window. 7859 * 7860 * @see #onWindowVisibilityChanged(int) 7861 */ 7862 public void dispatchWindowVisibilityChanged(int visibility) { 7863 onWindowVisibilityChanged(visibility); 7864 } 7865 7866 /** 7867 * Called when the window containing has change its visibility 7868 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 7869 * that this tells you whether or not your window is being made visible 7870 * to the window manager; this does <em>not</em> tell you whether or not 7871 * your window is obscured by other windows on the screen, even if it 7872 * is itself visible. 7873 * 7874 * @param visibility The new visibility of the window. 7875 */ 7876 protected void onWindowVisibilityChanged(int visibility) { 7877 if (visibility == VISIBLE) { 7878 initialAwakenScrollBars(); 7879 } 7880 } 7881 7882 /** 7883 * Returns the current visibility of the window this view is attached to 7884 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 7885 * 7886 * @return Returns the current visibility of the view's window. 7887 */ 7888 public int getWindowVisibility() { 7889 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 7890 } 7891 7892 /** 7893 * Retrieve the overall visible display size in which the window this view is 7894 * attached to has been positioned in. This takes into account screen 7895 * decorations above the window, for both cases where the window itself 7896 * is being position inside of them or the window is being placed under 7897 * then and covered insets are used for the window to position its content 7898 * inside. In effect, this tells you the available area where content can 7899 * be placed and remain visible to users. 7900 * 7901 * <p>This function requires an IPC back to the window manager to retrieve 7902 * the requested information, so should not be used in performance critical 7903 * code like drawing. 7904 * 7905 * @param outRect Filled in with the visible display frame. If the view 7906 * is not attached to a window, this is simply the raw display size. 7907 */ 7908 public void getWindowVisibleDisplayFrame(Rect outRect) { 7909 if (mAttachInfo != null) { 7910 try { 7911 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 7912 } catch (RemoteException e) { 7913 return; 7914 } 7915 // XXX This is really broken, and probably all needs to be done 7916 // in the window manager, and we need to know more about whether 7917 // we want the area behind or in front of the IME. 7918 final Rect insets = mAttachInfo.mVisibleInsets; 7919 outRect.left += insets.left; 7920 outRect.top += insets.top; 7921 outRect.right -= insets.right; 7922 outRect.bottom -= insets.bottom; 7923 return; 7924 } 7925 // The view is not attached to a display so we don't have a context. 7926 // Make a best guess about the display size. 7927 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 7928 d.getRectSize(outRect); 7929 } 7930 7931 /** 7932 * Dispatch a notification about a resource configuration change down 7933 * the view hierarchy. 7934 * ViewGroups should override to route to their children. 7935 * 7936 * @param newConfig The new resource configuration. 7937 * 7938 * @see #onConfigurationChanged(android.content.res.Configuration) 7939 */ 7940 public void dispatchConfigurationChanged(Configuration newConfig) { 7941 onConfigurationChanged(newConfig); 7942 } 7943 7944 /** 7945 * Called when the current configuration of the resources being used 7946 * by the application have changed. You can use this to decide when 7947 * to reload resources that can changed based on orientation and other 7948 * configuration characterstics. You only need to use this if you are 7949 * not relying on the normal {@link android.app.Activity} mechanism of 7950 * recreating the activity instance upon a configuration change. 7951 * 7952 * @param newConfig The new resource configuration. 7953 */ 7954 protected void onConfigurationChanged(Configuration newConfig) { 7955 } 7956 7957 /** 7958 * Private function to aggregate all per-view attributes in to the view 7959 * root. 7960 */ 7961 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 7962 performCollectViewAttributes(attachInfo, visibility); 7963 } 7964 7965 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 7966 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 7967 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 7968 attachInfo.mKeepScreenOn = true; 7969 } 7970 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 7971 ListenerInfo li = mListenerInfo; 7972 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 7973 attachInfo.mHasSystemUiListeners = true; 7974 } 7975 } 7976 } 7977 7978 void needGlobalAttributesUpdate(boolean force) { 7979 final AttachInfo ai = mAttachInfo; 7980 if (ai != null && !ai.mRecomputeGlobalAttributes) { 7981 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 7982 || ai.mHasSystemUiListeners) { 7983 ai.mRecomputeGlobalAttributes = true; 7984 } 7985 } 7986 } 7987 7988 /** 7989 * Returns whether the device is currently in touch mode. Touch mode is entered 7990 * once the user begins interacting with the device by touch, and affects various 7991 * things like whether focus is always visible to the user. 7992 * 7993 * @return Whether the device is in touch mode. 7994 */ 7995 @ViewDebug.ExportedProperty 7996 public boolean isInTouchMode() { 7997 if (mAttachInfo != null) { 7998 return mAttachInfo.mInTouchMode; 7999 } else { 8000 return ViewRootImpl.isInTouchMode(); 8001 } 8002 } 8003 8004 /** 8005 * Returns the context the view is running in, through which it can 8006 * access the current theme, resources, etc. 8007 * 8008 * @return The view's Context. 8009 */ 8010 @ViewDebug.CapturedViewProperty 8011 public final Context getContext() { 8012 return mContext; 8013 } 8014 8015 /** 8016 * Handle a key event before it is processed by any input method 8017 * associated with the view hierarchy. This can be used to intercept 8018 * key events in special situations before the IME consumes them; a 8019 * typical example would be handling the BACK key to update the application's 8020 * UI instead of allowing the IME to see it and close itself. 8021 * 8022 * @param keyCode The value in event.getKeyCode(). 8023 * @param event Description of the key event. 8024 * @return If you handled the event, return true. If you want to allow the 8025 * event to be handled by the next receiver, return false. 8026 */ 8027 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 8028 return false; 8029 } 8030 8031 /** 8032 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 8033 * KeyEvent.Callback.onKeyDown()}: perform press of the view 8034 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 8035 * is released, if the view is enabled and clickable. 8036 * 8037 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8038 * although some may elect to do so in some situations. Do not rely on this to 8039 * catch software key presses. 8040 * 8041 * @param keyCode A key code that represents the button pressed, from 8042 * {@link android.view.KeyEvent}. 8043 * @param event The KeyEvent object that defines the button action. 8044 */ 8045 public boolean onKeyDown(int keyCode, KeyEvent event) { 8046 boolean result = false; 8047 8048 if (KeyEvent.isConfirmKey(event.getKeyCode())) { 8049 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8050 return true; 8051 } 8052 // Long clickable items don't necessarily have to be clickable 8053 if (((mViewFlags & CLICKABLE) == CLICKABLE || 8054 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 8055 (event.getRepeatCount() == 0)) { 8056 setPressed(true); 8057 checkForLongClick(0); 8058 return true; 8059 } 8060 } 8061 return result; 8062 } 8063 8064 /** 8065 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 8066 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 8067 * the event). 8068 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8069 * although some may elect to do so in some situations. Do not rely on this to 8070 * catch software key presses. 8071 */ 8072 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 8073 return false; 8074 } 8075 8076 /** 8077 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 8078 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 8079 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 8080 * {@link KeyEvent#KEYCODE_ENTER} is released. 8081 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8082 * although some may elect to do so in some situations. Do not rely on this to 8083 * catch software key presses. 8084 * 8085 * @param keyCode A key code that represents the button pressed, from 8086 * {@link android.view.KeyEvent}. 8087 * @param event The KeyEvent object that defines the button action. 8088 */ 8089 public boolean onKeyUp(int keyCode, KeyEvent event) { 8090 boolean result = false; 8091 8092 switch (keyCode) { 8093 case KeyEvent.KEYCODE_DPAD_CENTER: 8094 case KeyEvent.KEYCODE_ENTER: { 8095 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8096 return true; 8097 } 8098 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 8099 setPressed(false); 8100 8101 if (!mHasPerformedLongPress) { 8102 // This is a tap, so remove the longpress check 8103 removeLongPressCallback(); 8104 8105 result = performClick(); 8106 } 8107 } 8108 break; 8109 } 8110 } 8111 return result; 8112 } 8113 8114 /** 8115 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 8116 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 8117 * the event). 8118 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8119 * although some may elect to do so in some situations. Do not rely on this to 8120 * catch software key presses. 8121 * 8122 * @param keyCode A key code that represents the button pressed, from 8123 * {@link android.view.KeyEvent}. 8124 * @param repeatCount The number of times the action was made. 8125 * @param event The KeyEvent object that defines the button action. 8126 */ 8127 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 8128 return false; 8129 } 8130 8131 /** 8132 * Called on the focused view when a key shortcut event is not handled. 8133 * Override this method to implement local key shortcuts for the View. 8134 * Key shortcuts can also be implemented by setting the 8135 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 8136 * 8137 * @param keyCode The value in event.getKeyCode(). 8138 * @param event Description of the key event. 8139 * @return If you handled the event, return true. If you want to allow the 8140 * event to be handled by the next receiver, return false. 8141 */ 8142 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 8143 return false; 8144 } 8145 8146 /** 8147 * Check whether the called view is a text editor, in which case it 8148 * would make sense to automatically display a soft input window for 8149 * it. Subclasses should override this if they implement 8150 * {@link #onCreateInputConnection(EditorInfo)} to return true if 8151 * a call on that method would return a non-null InputConnection, and 8152 * they are really a first-class editor that the user would normally 8153 * start typing on when the go into a window containing your view. 8154 * 8155 * <p>The default implementation always returns false. This does 8156 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 8157 * will not be called or the user can not otherwise perform edits on your 8158 * view; it is just a hint to the system that this is not the primary 8159 * purpose of this view. 8160 * 8161 * @return Returns true if this view is a text editor, else false. 8162 */ 8163 public boolean onCheckIsTextEditor() { 8164 return false; 8165 } 8166 8167 /** 8168 * Create a new InputConnection for an InputMethod to interact 8169 * with the view. The default implementation returns null, since it doesn't 8170 * support input methods. You can override this to implement such support. 8171 * This is only needed for views that take focus and text input. 8172 * 8173 * <p>When implementing this, you probably also want to implement 8174 * {@link #onCheckIsTextEditor()} to indicate you will return a 8175 * non-null InputConnection. 8176 * 8177 * @param outAttrs Fill in with attribute information about the connection. 8178 */ 8179 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 8180 return null; 8181 } 8182 8183 /** 8184 * Called by the {@link android.view.inputmethod.InputMethodManager} 8185 * when a view who is not the current 8186 * input connection target is trying to make a call on the manager. The 8187 * default implementation returns false; you can override this to return 8188 * true for certain views if you are performing InputConnection proxying 8189 * to them. 8190 * @param view The View that is making the InputMethodManager call. 8191 * @return Return true to allow the call, false to reject. 8192 */ 8193 public boolean checkInputConnectionProxy(View view) { 8194 return false; 8195 } 8196 8197 /** 8198 * Show the context menu for this view. It is not safe to hold on to the 8199 * menu after returning from this method. 8200 * 8201 * You should normally not overload this method. Overload 8202 * {@link #onCreateContextMenu(ContextMenu)} or define an 8203 * {@link OnCreateContextMenuListener} to add items to the context menu. 8204 * 8205 * @param menu The context menu to populate 8206 */ 8207 public void createContextMenu(ContextMenu menu) { 8208 ContextMenuInfo menuInfo = getContextMenuInfo(); 8209 8210 // Sets the current menu info so all items added to menu will have 8211 // my extra info set. 8212 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 8213 8214 onCreateContextMenu(menu); 8215 ListenerInfo li = mListenerInfo; 8216 if (li != null && li.mOnCreateContextMenuListener != null) { 8217 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 8218 } 8219 8220 // Clear the extra information so subsequent items that aren't mine don't 8221 // have my extra info. 8222 ((MenuBuilder)menu).setCurrentMenuInfo(null); 8223 8224 if (mParent != null) { 8225 mParent.createContextMenu(menu); 8226 } 8227 } 8228 8229 /** 8230 * Views should implement this if they have extra information to associate 8231 * with the context menu. The return result is supplied as a parameter to 8232 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 8233 * callback. 8234 * 8235 * @return Extra information about the item for which the context menu 8236 * should be shown. This information will vary across different 8237 * subclasses of View. 8238 */ 8239 protected ContextMenuInfo getContextMenuInfo() { 8240 return null; 8241 } 8242 8243 /** 8244 * Views should implement this if the view itself is going to add items to 8245 * the context menu. 8246 * 8247 * @param menu the context menu to populate 8248 */ 8249 protected void onCreateContextMenu(ContextMenu menu) { 8250 } 8251 8252 /** 8253 * Implement this method to handle trackball motion events. The 8254 * <em>relative</em> movement of the trackball since the last event 8255 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 8256 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 8257 * that a movement of 1 corresponds to the user pressing one DPAD key (so 8258 * they will often be fractional values, representing the more fine-grained 8259 * movement information available from a trackball). 8260 * 8261 * @param event The motion event. 8262 * @return True if the event was handled, false otherwise. 8263 */ 8264 public boolean onTrackballEvent(MotionEvent event) { 8265 return false; 8266 } 8267 8268 /** 8269 * Implement this method to handle generic motion events. 8270 * <p> 8271 * Generic motion events describe joystick movements, mouse hovers, track pad 8272 * touches, scroll wheel movements and other input events. The 8273 * {@link MotionEvent#getSource() source} of the motion event specifies 8274 * the class of input that was received. Implementations of this method 8275 * must examine the bits in the source before processing the event. 8276 * The following code example shows how this is done. 8277 * </p><p> 8278 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 8279 * are delivered to the view under the pointer. All other generic motion events are 8280 * delivered to the focused view. 8281 * </p> 8282 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 8283 * if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) { 8284 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 8285 * // process the joystick movement... 8286 * return true; 8287 * } 8288 * } 8289 * if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { 8290 * switch (event.getAction()) { 8291 * case MotionEvent.ACTION_HOVER_MOVE: 8292 * // process the mouse hover movement... 8293 * return true; 8294 * case MotionEvent.ACTION_SCROLL: 8295 * // process the scroll wheel movement... 8296 * return true; 8297 * } 8298 * } 8299 * return super.onGenericMotionEvent(event); 8300 * }</pre> 8301 * 8302 * @param event The generic motion event being processed. 8303 * @return True if the event was handled, false otherwise. 8304 */ 8305 public boolean onGenericMotionEvent(MotionEvent event) { 8306 return false; 8307 } 8308 8309 /** 8310 * Implement this method to handle hover events. 8311 * <p> 8312 * This method is called whenever a pointer is hovering into, over, or out of the 8313 * bounds of a view and the view is not currently being touched. 8314 * Hover events are represented as pointer events with action 8315 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 8316 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 8317 * </p> 8318 * <ul> 8319 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 8320 * when the pointer enters the bounds of the view.</li> 8321 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 8322 * when the pointer has already entered the bounds of the view and has moved.</li> 8323 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 8324 * when the pointer has exited the bounds of the view or when the pointer is 8325 * about to go down due to a button click, tap, or similar user action that 8326 * causes the view to be touched.</li> 8327 * </ul> 8328 * <p> 8329 * The view should implement this method to return true to indicate that it is 8330 * handling the hover event, such as by changing its drawable state. 8331 * </p><p> 8332 * The default implementation calls {@link #setHovered} to update the hovered state 8333 * of the view when a hover enter or hover exit event is received, if the view 8334 * is enabled and is clickable. The default implementation also sends hover 8335 * accessibility events. 8336 * </p> 8337 * 8338 * @param event The motion event that describes the hover. 8339 * @return True if the view handled the hover event. 8340 * 8341 * @see #isHovered 8342 * @see #setHovered 8343 * @see #onHoverChanged 8344 */ 8345 public boolean onHoverEvent(MotionEvent event) { 8346 // The root view may receive hover (or touch) events that are outside the bounds of 8347 // the window. This code ensures that we only send accessibility events for 8348 // hovers that are actually within the bounds of the root view. 8349 final int action = event.getActionMasked(); 8350 if (!mSendingHoverAccessibilityEvents) { 8351 if ((action == MotionEvent.ACTION_HOVER_ENTER 8352 || action == MotionEvent.ACTION_HOVER_MOVE) 8353 && !hasHoveredChild() 8354 && pointInView(event.getX(), event.getY())) { 8355 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 8356 mSendingHoverAccessibilityEvents = true; 8357 } 8358 } else { 8359 if (action == MotionEvent.ACTION_HOVER_EXIT 8360 || (action == MotionEvent.ACTION_MOVE 8361 && !pointInView(event.getX(), event.getY()))) { 8362 mSendingHoverAccessibilityEvents = false; 8363 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 8364 // If the window does not have input focus we take away accessibility 8365 // focus as soon as the user stop hovering over the view. 8366 if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) { 8367 getViewRootImpl().setAccessibilityFocus(null, null); 8368 } 8369 } 8370 } 8371 8372 if (isHoverable()) { 8373 switch (action) { 8374 case MotionEvent.ACTION_HOVER_ENTER: 8375 setHovered(true); 8376 break; 8377 case MotionEvent.ACTION_HOVER_EXIT: 8378 setHovered(false); 8379 break; 8380 } 8381 8382 // Dispatch the event to onGenericMotionEvent before returning true. 8383 // This is to provide compatibility with existing applications that 8384 // handled HOVER_MOVE events in onGenericMotionEvent and that would 8385 // break because of the new default handling for hoverable views 8386 // in onHoverEvent. 8387 // Note that onGenericMotionEvent will be called by default when 8388 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 8389 dispatchGenericMotionEventInternal(event); 8390 // The event was already handled by calling setHovered(), so always 8391 // return true. 8392 return true; 8393 } 8394 8395 return false; 8396 } 8397 8398 /** 8399 * Returns true if the view should handle {@link #onHoverEvent} 8400 * by calling {@link #setHovered} to change its hovered state. 8401 * 8402 * @return True if the view is hoverable. 8403 */ 8404 private boolean isHoverable() { 8405 final int viewFlags = mViewFlags; 8406 if ((viewFlags & ENABLED_MASK) == DISABLED) { 8407 return false; 8408 } 8409 8410 return (viewFlags & CLICKABLE) == CLICKABLE 8411 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 8412 } 8413 8414 /** 8415 * Returns true if the view is currently hovered. 8416 * 8417 * @return True if the view is currently hovered. 8418 * 8419 * @see #setHovered 8420 * @see #onHoverChanged 8421 */ 8422 @ViewDebug.ExportedProperty 8423 public boolean isHovered() { 8424 return (mPrivateFlags & PFLAG_HOVERED) != 0; 8425 } 8426 8427 /** 8428 * Sets whether the view is currently hovered. 8429 * <p> 8430 * Calling this method also changes the drawable state of the view. This 8431 * enables the view to react to hover by using different drawable resources 8432 * to change its appearance. 8433 * </p><p> 8434 * The {@link #onHoverChanged} method is called when the hovered state changes. 8435 * </p> 8436 * 8437 * @param hovered True if the view is hovered. 8438 * 8439 * @see #isHovered 8440 * @see #onHoverChanged 8441 */ 8442 public void setHovered(boolean hovered) { 8443 if (hovered) { 8444 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 8445 mPrivateFlags |= PFLAG_HOVERED; 8446 refreshDrawableState(); 8447 onHoverChanged(true); 8448 } 8449 } else { 8450 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 8451 mPrivateFlags &= ~PFLAG_HOVERED; 8452 refreshDrawableState(); 8453 onHoverChanged(false); 8454 } 8455 } 8456 } 8457 8458 /** 8459 * Implement this method to handle hover state changes. 8460 * <p> 8461 * This method is called whenever the hover state changes as a result of a 8462 * call to {@link #setHovered}. 8463 * </p> 8464 * 8465 * @param hovered The current hover state, as returned by {@link #isHovered}. 8466 * 8467 * @see #isHovered 8468 * @see #setHovered 8469 */ 8470 public void onHoverChanged(boolean hovered) { 8471 } 8472 8473 /** 8474 * Implement this method to handle touch screen motion events. 8475 * <p> 8476 * If this method is used to detect click actions, it is recommended that 8477 * the actions be performed by implementing and calling 8478 * {@link #performClick()}. This will ensure consistent system behavior, 8479 * including: 8480 * <ul> 8481 * <li>obeying click sound preferences 8482 * <li>dispatching OnClickListener calls 8483 * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when 8484 * accessibility features are enabled 8485 * </ul> 8486 * 8487 * @param event The motion event. 8488 * @return True if the event was handled, false otherwise. 8489 */ 8490 public boolean onTouchEvent(MotionEvent event) { 8491 final int viewFlags = mViewFlags; 8492 8493 if ((viewFlags & ENABLED_MASK) == DISABLED) { 8494 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 8495 setPressed(false); 8496 } 8497 // A disabled view that is clickable still consumes the touch 8498 // events, it just doesn't respond to them. 8499 return (((viewFlags & CLICKABLE) == CLICKABLE || 8500 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 8501 } 8502 8503 if (mTouchDelegate != null) { 8504 if (mTouchDelegate.onTouchEvent(event)) { 8505 return true; 8506 } 8507 } 8508 8509 if (((viewFlags & CLICKABLE) == CLICKABLE || 8510 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 8511 switch (event.getAction()) { 8512 case MotionEvent.ACTION_UP: 8513 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 8514 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 8515 // take focus if we don't have it already and we should in 8516 // touch mode. 8517 boolean focusTaken = false; 8518 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 8519 focusTaken = requestFocus(); 8520 } 8521 8522 if (prepressed) { 8523 // The button is being released before we actually 8524 // showed it as pressed. Make it show the pressed 8525 // state now (before scheduling the click) to ensure 8526 // the user sees it. 8527 setPressed(true); 8528 } 8529 8530 if (!mHasPerformedLongPress) { 8531 // This is a tap, so remove the longpress check 8532 removeLongPressCallback(); 8533 8534 // Only perform take click actions if we were in the pressed state 8535 if (!focusTaken) { 8536 // Use a Runnable and post this rather than calling 8537 // performClick directly. This lets other visual state 8538 // of the view update before click actions start. 8539 if (mPerformClick == null) { 8540 mPerformClick = new PerformClick(); 8541 } 8542 if (!post(mPerformClick)) { 8543 performClick(); 8544 } 8545 } 8546 } 8547 8548 if (mUnsetPressedState == null) { 8549 mUnsetPressedState = new UnsetPressedState(); 8550 } 8551 8552 if (prepressed) { 8553 postDelayed(mUnsetPressedState, 8554 ViewConfiguration.getPressedStateDuration()); 8555 } else if (!post(mUnsetPressedState)) { 8556 // If the post failed, unpress right now 8557 mUnsetPressedState.run(); 8558 } 8559 removeTapCallback(); 8560 } 8561 break; 8562 8563 case MotionEvent.ACTION_DOWN: 8564 mHasPerformedLongPress = false; 8565 8566 if (performButtonActionOnTouchDown(event)) { 8567 break; 8568 } 8569 8570 // Walk up the hierarchy to determine if we're inside a scrolling container. 8571 boolean isInScrollingContainer = isInScrollingContainer(); 8572 8573 // For views inside a scrolling container, delay the pressed feedback for 8574 // a short period in case this is a scroll. 8575 if (isInScrollingContainer) { 8576 mPrivateFlags |= PFLAG_PREPRESSED; 8577 if (mPendingCheckForTap == null) { 8578 mPendingCheckForTap = new CheckForTap(); 8579 } 8580 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 8581 } else { 8582 // Not inside a scrolling container, so show the feedback right away 8583 setPressed(true); 8584 checkForLongClick(0); 8585 } 8586 break; 8587 8588 case MotionEvent.ACTION_CANCEL: 8589 setPressed(false); 8590 removeTapCallback(); 8591 removeLongPressCallback(); 8592 break; 8593 8594 case MotionEvent.ACTION_MOVE: 8595 final int x = (int) event.getX(); 8596 final int y = (int) event.getY(); 8597 8598 // Be lenient about moving outside of buttons 8599 if (!pointInView(x, y, mTouchSlop)) { 8600 // Outside button 8601 removeTapCallback(); 8602 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 8603 // Remove any future long press/tap checks 8604 removeLongPressCallback(); 8605 8606 setPressed(false); 8607 } 8608 } 8609 break; 8610 } 8611 return true; 8612 } 8613 8614 return false; 8615 } 8616 8617 /** 8618 * @hide 8619 */ 8620 public boolean isInScrollingContainer() { 8621 ViewParent p = getParent(); 8622 while (p != null && p instanceof ViewGroup) { 8623 if (((ViewGroup) p).shouldDelayChildPressedState()) { 8624 return true; 8625 } 8626 p = p.getParent(); 8627 } 8628 return false; 8629 } 8630 8631 /** 8632 * Remove the longpress detection timer. 8633 */ 8634 private void removeLongPressCallback() { 8635 if (mPendingCheckForLongPress != null) { 8636 removeCallbacks(mPendingCheckForLongPress); 8637 } 8638 } 8639 8640 /** 8641 * Remove the pending click action 8642 */ 8643 private void removePerformClickCallback() { 8644 if (mPerformClick != null) { 8645 removeCallbacks(mPerformClick); 8646 } 8647 } 8648 8649 /** 8650 * Remove the prepress detection timer. 8651 */ 8652 private void removeUnsetPressCallback() { 8653 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 8654 setPressed(false); 8655 removeCallbacks(mUnsetPressedState); 8656 } 8657 } 8658 8659 /** 8660 * Remove the tap detection timer. 8661 */ 8662 private void removeTapCallback() { 8663 if (mPendingCheckForTap != null) { 8664 mPrivateFlags &= ~PFLAG_PREPRESSED; 8665 removeCallbacks(mPendingCheckForTap); 8666 } 8667 } 8668 8669 /** 8670 * Cancels a pending long press. Your subclass can use this if you 8671 * want the context menu to come up if the user presses and holds 8672 * at the same place, but you don't want it to come up if they press 8673 * and then move around enough to cause scrolling. 8674 */ 8675 public void cancelLongPress() { 8676 removeLongPressCallback(); 8677 8678 /* 8679 * The prepressed state handled by the tap callback is a display 8680 * construct, but the tap callback will post a long press callback 8681 * less its own timeout. Remove it here. 8682 */ 8683 removeTapCallback(); 8684 } 8685 8686 /** 8687 * Remove the pending callback for sending a 8688 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 8689 */ 8690 private void removeSendViewScrolledAccessibilityEventCallback() { 8691 if (mSendViewScrolledAccessibilityEvent != null) { 8692 removeCallbacks(mSendViewScrolledAccessibilityEvent); 8693 mSendViewScrolledAccessibilityEvent.mIsPending = false; 8694 } 8695 } 8696 8697 /** 8698 * Sets the TouchDelegate for this View. 8699 */ 8700 public void setTouchDelegate(TouchDelegate delegate) { 8701 mTouchDelegate = delegate; 8702 } 8703 8704 /** 8705 * Gets the TouchDelegate for this View. 8706 */ 8707 public TouchDelegate getTouchDelegate() { 8708 return mTouchDelegate; 8709 } 8710 8711 /** 8712 * Set flags controlling behavior of this view. 8713 * 8714 * @param flags Constant indicating the value which should be set 8715 * @param mask Constant indicating the bit range that should be changed 8716 */ 8717 void setFlags(int flags, int mask) { 8718 final boolean accessibilityEnabled = 8719 AccessibilityManager.getInstance(mContext).isEnabled(); 8720 final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility(); 8721 8722 int old = mViewFlags; 8723 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 8724 8725 int changed = mViewFlags ^ old; 8726 if (changed == 0) { 8727 return; 8728 } 8729 int privateFlags = mPrivateFlags; 8730 8731 /* Check if the FOCUSABLE bit has changed */ 8732 if (((changed & FOCUSABLE_MASK) != 0) && 8733 ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) { 8734 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 8735 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 8736 /* Give up focus if we are no longer focusable */ 8737 clearFocus(); 8738 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 8739 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 8740 /* 8741 * Tell the view system that we are now available to take focus 8742 * if no one else already has it. 8743 */ 8744 if (mParent != null) mParent.focusableViewAvailable(this); 8745 } 8746 } 8747 8748 final int newVisibility = flags & VISIBILITY_MASK; 8749 if (newVisibility == VISIBLE) { 8750 if ((changed & VISIBILITY_MASK) != 0) { 8751 /* 8752 * If this view is becoming visible, invalidate it in case it changed while 8753 * it was not visible. Marking it drawn ensures that the invalidation will 8754 * go through. 8755 */ 8756 mPrivateFlags |= PFLAG_DRAWN; 8757 invalidate(true); 8758 8759 needGlobalAttributesUpdate(true); 8760 8761 // a view becoming visible is worth notifying the parent 8762 // about in case nothing has focus. even if this specific view 8763 // isn't focusable, it may contain something that is, so let 8764 // the root view try to give this focus if nothing else does. 8765 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 8766 mParent.focusableViewAvailable(this); 8767 } 8768 } 8769 } 8770 8771 /* Check if the GONE bit has changed */ 8772 if ((changed & GONE) != 0) { 8773 needGlobalAttributesUpdate(false); 8774 requestLayout(); 8775 8776 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 8777 if (hasFocus()) clearFocus(); 8778 clearAccessibilityFocus(); 8779 destroyDrawingCache(); 8780 if (mParent instanceof View) { 8781 // GONE views noop invalidation, so invalidate the parent 8782 ((View) mParent).invalidate(true); 8783 } 8784 // Mark the view drawn to ensure that it gets invalidated properly the next 8785 // time it is visible and gets invalidated 8786 mPrivateFlags |= PFLAG_DRAWN; 8787 } 8788 if (mAttachInfo != null) { 8789 mAttachInfo.mViewVisibilityChanged = true; 8790 } 8791 } 8792 8793 /* Check if the VISIBLE bit has changed */ 8794 if ((changed & INVISIBLE) != 0) { 8795 needGlobalAttributesUpdate(false); 8796 /* 8797 * If this view is becoming invisible, set the DRAWN flag so that 8798 * the next invalidate() will not be skipped. 8799 */ 8800 mPrivateFlags |= PFLAG_DRAWN; 8801 8802 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) { 8803 // root view becoming invisible shouldn't clear focus and accessibility focus 8804 if (getRootView() != this) { 8805 clearFocus(); 8806 clearAccessibilityFocus(); 8807 } 8808 } 8809 if (mAttachInfo != null) { 8810 mAttachInfo.mViewVisibilityChanged = true; 8811 } 8812 } 8813 8814 if ((changed & VISIBILITY_MASK) != 0) { 8815 // If the view is invisible, cleanup its display list to free up resources 8816 if (newVisibility != VISIBLE) { 8817 cleanupDraw(); 8818 } 8819 8820 if (mParent instanceof ViewGroup) { 8821 ((ViewGroup) mParent).onChildVisibilityChanged(this, 8822 (changed & VISIBILITY_MASK), newVisibility); 8823 ((View) mParent).invalidate(true); 8824 } else if (mParent != null) { 8825 mParent.invalidateChild(this, null); 8826 } 8827 dispatchVisibilityChanged(this, newVisibility); 8828 } 8829 8830 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 8831 destroyDrawingCache(); 8832 } 8833 8834 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 8835 destroyDrawingCache(); 8836 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 8837 invalidateParentCaches(); 8838 } 8839 8840 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 8841 destroyDrawingCache(); 8842 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 8843 } 8844 8845 if ((changed & DRAW_MASK) != 0) { 8846 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 8847 if (mBackground != null) { 8848 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 8849 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 8850 } else { 8851 mPrivateFlags |= PFLAG_SKIP_DRAW; 8852 } 8853 } else { 8854 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 8855 } 8856 requestLayout(); 8857 invalidate(true); 8858 } 8859 8860 if ((changed & KEEP_SCREEN_ON) != 0) { 8861 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 8862 mParent.recomputeViewAttributes(this); 8863 } 8864 } 8865 8866 if (accessibilityEnabled) { 8867 if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0 8868 || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) { 8869 if (oldIncludeForAccessibility != includeForAccessibility()) { 8870 notifySubtreeAccessibilityStateChangedIfNeeded(); 8871 } else { 8872 notifyViewAccessibilityStateChangedIfNeeded(); 8873 } 8874 } 8875 if ((changed & ENABLED_MASK) != 0) { 8876 notifyViewAccessibilityStateChangedIfNeeded(); 8877 } 8878 } 8879 } 8880 8881 /** 8882 * Change the view's z order in the tree, so it's on top of other sibling 8883 * views. This ordering change may affect layout, if the parent container 8884 * uses an order-dependent layout scheme (e.g., LinearLayout). Prior 8885 * to {@link android.os.Build.VERSION_CODES#KITKAT} this 8886 * method should be followed by calls to {@link #requestLayout()} and 8887 * {@link View#invalidate()} on the view's parent to force the parent to redraw 8888 * with the new child ordering. 8889 * 8890 * @see ViewGroup#bringChildToFront(View) 8891 */ 8892 public void bringToFront() { 8893 if (mParent != null) { 8894 mParent.bringChildToFront(this); 8895 } 8896 } 8897 8898 /** 8899 * This is called in response to an internal scroll in this view (i.e., the 8900 * view scrolled its own contents). This is typically as a result of 8901 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 8902 * called. 8903 * 8904 * @param l Current horizontal scroll origin. 8905 * @param t Current vertical scroll origin. 8906 * @param oldl Previous horizontal scroll origin. 8907 * @param oldt Previous vertical scroll origin. 8908 */ 8909 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 8910 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 8911 postSendViewScrolledAccessibilityEventCallback(); 8912 } 8913 8914 mBackgroundSizeChanged = true; 8915 8916 final AttachInfo ai = mAttachInfo; 8917 if (ai != null) { 8918 ai.mViewScrollChanged = true; 8919 } 8920 } 8921 8922 /** 8923 * Interface definition for a callback to be invoked when the layout bounds of a view 8924 * changes due to layout processing. 8925 */ 8926 public interface OnLayoutChangeListener { 8927 /** 8928 * Called when the focus state of a view has changed. 8929 * 8930 * @param v The view whose state has changed. 8931 * @param left The new value of the view's left property. 8932 * @param top The new value of the view's top property. 8933 * @param right The new value of the view's right property. 8934 * @param bottom The new value of the view's bottom property. 8935 * @param oldLeft The previous value of the view's left property. 8936 * @param oldTop The previous value of the view's top property. 8937 * @param oldRight The previous value of the view's right property. 8938 * @param oldBottom The previous value of the view's bottom property. 8939 */ 8940 void onLayoutChange(View v, int left, int top, int right, int bottom, 8941 int oldLeft, int oldTop, int oldRight, int oldBottom); 8942 } 8943 8944 /** 8945 * This is called during layout when the size of this view has changed. If 8946 * you were just added to the view hierarchy, you're called with the old 8947 * values of 0. 8948 * 8949 * @param w Current width of this view. 8950 * @param h Current height of this view. 8951 * @param oldw Old width of this view. 8952 * @param oldh Old height of this view. 8953 */ 8954 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 8955 } 8956 8957 /** 8958 * Called by draw to draw the child views. This may be overridden 8959 * by derived classes to gain control just before its children are drawn 8960 * (but after its own view has been drawn). 8961 * @param canvas the canvas on which to draw the view 8962 */ 8963 protected void dispatchDraw(Canvas canvas) { 8964 8965 } 8966 8967 /** 8968 * Gets the parent of this view. Note that the parent is a 8969 * ViewParent and not necessarily a View. 8970 * 8971 * @return Parent of this view. 8972 */ 8973 public final ViewParent getParent() { 8974 return mParent; 8975 } 8976 8977 /** 8978 * Set the horizontal scrolled position of your view. This will cause a call to 8979 * {@link #onScrollChanged(int, int, int, int)} and the view will be 8980 * invalidated. 8981 * @param value the x position to scroll to 8982 */ 8983 public void setScrollX(int value) { 8984 scrollTo(value, mScrollY); 8985 } 8986 8987 /** 8988 * Set the vertical scrolled position of your view. This will cause a call to 8989 * {@link #onScrollChanged(int, int, int, int)} and the view will be 8990 * invalidated. 8991 * @param value the y position to scroll to 8992 */ 8993 public void setScrollY(int value) { 8994 scrollTo(mScrollX, value); 8995 } 8996 8997 /** 8998 * Return the scrolled left position of this view. This is the left edge of 8999 * the displayed part of your view. You do not need to draw any pixels 9000 * farther left, since those are outside of the frame of your view on 9001 * screen. 9002 * 9003 * @return The left edge of the displayed part of your view, in pixels. 9004 */ 9005 public final int getScrollX() { 9006 return mScrollX; 9007 } 9008 9009 /** 9010 * Return the scrolled top position of this view. This is the top edge of 9011 * the displayed part of your view. You do not need to draw any pixels above 9012 * it, since those are outside of the frame of your view on screen. 9013 * 9014 * @return The top edge of the displayed part of your view, in pixels. 9015 */ 9016 public final int getScrollY() { 9017 return mScrollY; 9018 } 9019 9020 /** 9021 * Return the width of the your view. 9022 * 9023 * @return The width of your view, in pixels. 9024 */ 9025 @ViewDebug.ExportedProperty(category = "layout") 9026 public final int getWidth() { 9027 return mRight - mLeft; 9028 } 9029 9030 /** 9031 * Return the height of your view. 9032 * 9033 * @return The height of your view, in pixels. 9034 */ 9035 @ViewDebug.ExportedProperty(category = "layout") 9036 public final int getHeight() { 9037 return mBottom - mTop; 9038 } 9039 9040 /** 9041 * Return the visible drawing bounds of your view. Fills in the output 9042 * rectangle with the values from getScrollX(), getScrollY(), 9043 * getWidth(), and getHeight(). These bounds do not account for any 9044 * transformation properties currently set on the view, such as 9045 * {@link #setScaleX(float)} or {@link #setRotation(float)}. 9046 * 9047 * @param outRect The (scrolled) drawing bounds of the view. 9048 */ 9049 public void getDrawingRect(Rect outRect) { 9050 outRect.left = mScrollX; 9051 outRect.top = mScrollY; 9052 outRect.right = mScrollX + (mRight - mLeft); 9053 outRect.bottom = mScrollY + (mBottom - mTop); 9054 } 9055 9056 /** 9057 * Like {@link #getMeasuredWidthAndState()}, but only returns the 9058 * raw width component (that is the result is masked by 9059 * {@link #MEASURED_SIZE_MASK}). 9060 * 9061 * @return The raw measured width of this view. 9062 */ 9063 public final int getMeasuredWidth() { 9064 return mMeasuredWidth & MEASURED_SIZE_MASK; 9065 } 9066 9067 /** 9068 * Return the full width measurement information for this view as computed 9069 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 9070 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 9071 * This should be used during measurement and layout calculations only. Use 9072 * {@link #getWidth()} to see how wide a view is after layout. 9073 * 9074 * @return The measured width of this view as a bit mask. 9075 */ 9076 public final int getMeasuredWidthAndState() { 9077 return mMeasuredWidth; 9078 } 9079 9080 /** 9081 * Like {@link #getMeasuredHeightAndState()}, but only returns the 9082 * raw width component (that is the result is masked by 9083 * {@link #MEASURED_SIZE_MASK}). 9084 * 9085 * @return The raw measured height of this view. 9086 */ 9087 public final int getMeasuredHeight() { 9088 return mMeasuredHeight & MEASURED_SIZE_MASK; 9089 } 9090 9091 /** 9092 * Return the full height measurement information for this view as computed 9093 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 9094 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 9095 * This should be used during measurement and layout calculations only. Use 9096 * {@link #getHeight()} to see how wide a view is after layout. 9097 * 9098 * @return The measured width of this view as a bit mask. 9099 */ 9100 public final int getMeasuredHeightAndState() { 9101 return mMeasuredHeight; 9102 } 9103 9104 /** 9105 * Return only the state bits of {@link #getMeasuredWidthAndState()} 9106 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 9107 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 9108 * and the height component is at the shifted bits 9109 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 9110 */ 9111 public final int getMeasuredState() { 9112 return (mMeasuredWidth&MEASURED_STATE_MASK) 9113 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 9114 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 9115 } 9116 9117 /** 9118 * The transform matrix of this view, which is calculated based on the current 9119 * roation, scale, and pivot properties. 9120 * 9121 * @see #getRotation() 9122 * @see #getScaleX() 9123 * @see #getScaleY() 9124 * @see #getPivotX() 9125 * @see #getPivotY() 9126 * @return The current transform matrix for the view 9127 */ 9128 public Matrix getMatrix() { 9129 if (mTransformationInfo != null) { 9130 updateMatrix(); 9131 return mTransformationInfo.mMatrix; 9132 } 9133 return Matrix.IDENTITY_MATRIX; 9134 } 9135 9136 /** 9137 * Utility function to determine if the value is far enough away from zero to be 9138 * considered non-zero. 9139 * @param value A floating point value to check for zero-ness 9140 * @return whether the passed-in value is far enough away from zero to be considered non-zero 9141 */ 9142 private static boolean nonzero(float value) { 9143 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON); 9144 } 9145 9146 /** 9147 * Returns true if the transform matrix is the identity matrix. 9148 * Recomputes the matrix if necessary. 9149 * 9150 * @return True if the transform matrix is the identity matrix, false otherwise. 9151 */ 9152 final boolean hasIdentityMatrix() { 9153 if (mTransformationInfo != null) { 9154 updateMatrix(); 9155 return mTransformationInfo.mMatrixIsIdentity; 9156 } 9157 return true; 9158 } 9159 9160 void ensureTransformationInfo() { 9161 if (mTransformationInfo == null) { 9162 mTransformationInfo = new TransformationInfo(); 9163 } 9164 } 9165 9166 /** 9167 * Recomputes the transform matrix if necessary. 9168 */ 9169 private void updateMatrix() { 9170 final TransformationInfo info = mTransformationInfo; 9171 if (info == null) { 9172 return; 9173 } 9174 if (info.mMatrixDirty) { 9175 // transform-related properties have changed since the last time someone 9176 // asked for the matrix; recalculate it with the current values 9177 9178 // Figure out if we need to update the pivot point 9179 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 9180 if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) { 9181 info.mPrevWidth = mRight - mLeft; 9182 info.mPrevHeight = mBottom - mTop; 9183 info.mPivotX = info.mPrevWidth / 2f; 9184 info.mPivotY = info.mPrevHeight / 2f; 9185 } 9186 } 9187 info.mMatrix.reset(); 9188 if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) { 9189 info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY); 9190 info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY); 9191 info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY); 9192 } else { 9193 if (info.mCamera == null) { 9194 info.mCamera = new Camera(); 9195 info.matrix3D = new Matrix(); 9196 } 9197 info.mCamera.save(); 9198 info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY); 9199 info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation); 9200 info.mCamera.getMatrix(info.matrix3D); 9201 info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY); 9202 info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX, 9203 info.mPivotY + info.mTranslationY); 9204 info.mMatrix.postConcat(info.matrix3D); 9205 info.mCamera.restore(); 9206 } 9207 info.mMatrixDirty = false; 9208 info.mMatrixIsIdentity = info.mMatrix.isIdentity(); 9209 info.mInverseMatrixDirty = true; 9210 } 9211 } 9212 9213 /** 9214 * Utility method to retrieve the inverse of the current mMatrix property. 9215 * We cache the matrix to avoid recalculating it when transform properties 9216 * have not changed. 9217 * 9218 * @return The inverse of the current matrix of this view. 9219 */ 9220 final Matrix getInverseMatrix() { 9221 final TransformationInfo info = mTransformationInfo; 9222 if (info != null) { 9223 updateMatrix(); 9224 if (info.mInverseMatrixDirty) { 9225 if (info.mInverseMatrix == null) { 9226 info.mInverseMatrix = new Matrix(); 9227 } 9228 info.mMatrix.invert(info.mInverseMatrix); 9229 info.mInverseMatrixDirty = false; 9230 } 9231 return info.mInverseMatrix; 9232 } 9233 return Matrix.IDENTITY_MATRIX; 9234 } 9235 9236 /** 9237 * Gets the distance along the Z axis from the camera to this view. 9238 * 9239 * @see #setCameraDistance(float) 9240 * 9241 * @return The distance along the Z axis. 9242 */ 9243 public float getCameraDistance() { 9244 ensureTransformationInfo(); 9245 final float dpi = mResources.getDisplayMetrics().densityDpi; 9246 final TransformationInfo info = mTransformationInfo; 9247 if (info.mCamera == null) { 9248 info.mCamera = new Camera(); 9249 info.matrix3D = new Matrix(); 9250 } 9251 return -(info.mCamera.getLocationZ() * dpi); 9252 } 9253 9254 /** 9255 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 9256 * views are drawn) from the camera to this view. The camera's distance 9257 * affects 3D transformations, for instance rotations around the X and Y 9258 * axis. If the rotationX or rotationY properties are changed and this view is 9259 * large (more than half the size of the screen), it is recommended to always 9260 * use a camera distance that's greater than the height (X axis rotation) or 9261 * the width (Y axis rotation) of this view.</p> 9262 * 9263 * <p>The distance of the camera from the view plane can have an affect on the 9264 * perspective distortion of the view when it is rotated around the x or y axis. 9265 * For example, a large distance will result in a large viewing angle, and there 9266 * will not be much perspective distortion of the view as it rotates. A short 9267 * distance may cause much more perspective distortion upon rotation, and can 9268 * also result in some drawing artifacts if the rotated view ends up partially 9269 * behind the camera (which is why the recommendation is to use a distance at 9270 * least as far as the size of the view, if the view is to be rotated.)</p> 9271 * 9272 * <p>The distance is expressed in "depth pixels." The default distance depends 9273 * on the screen density. For instance, on a medium density display, the 9274 * default distance is 1280. On a high density display, the default distance 9275 * is 1920.</p> 9276 * 9277 * <p>If you want to specify a distance that leads to visually consistent 9278 * results across various densities, use the following formula:</p> 9279 * <pre> 9280 * float scale = context.getResources().getDisplayMetrics().density; 9281 * view.setCameraDistance(distance * scale); 9282 * </pre> 9283 * 9284 * <p>The density scale factor of a high density display is 1.5, 9285 * and 1920 = 1280 * 1.5.</p> 9286 * 9287 * @param distance The distance in "depth pixels", if negative the opposite 9288 * value is used 9289 * 9290 * @see #setRotationX(float) 9291 * @see #setRotationY(float) 9292 */ 9293 public void setCameraDistance(float distance) { 9294 invalidateViewProperty(true, false); 9295 9296 ensureTransformationInfo(); 9297 final float dpi = mResources.getDisplayMetrics().densityDpi; 9298 final TransformationInfo info = mTransformationInfo; 9299 if (info.mCamera == null) { 9300 info.mCamera = new Camera(); 9301 info.matrix3D = new Matrix(); 9302 } 9303 9304 info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi); 9305 info.mMatrixDirty = true; 9306 9307 invalidateViewProperty(false, false); 9308 if (mDisplayList != null) { 9309 mDisplayList.setCameraDistance(-Math.abs(distance) / dpi); 9310 } 9311 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9312 // View was rejected last time it was drawn by its parent; this may have changed 9313 invalidateParentIfNeeded(); 9314 } 9315 } 9316 9317 /** 9318 * The degrees that the view is rotated around the pivot point. 9319 * 9320 * @see #setRotation(float) 9321 * @see #getPivotX() 9322 * @see #getPivotY() 9323 * 9324 * @return The degrees of rotation. 9325 */ 9326 @ViewDebug.ExportedProperty(category = "drawing") 9327 public float getRotation() { 9328 return mTransformationInfo != null ? mTransformationInfo.mRotation : 0; 9329 } 9330 9331 /** 9332 * Sets the degrees that the view is rotated around the pivot point. Increasing values 9333 * result in clockwise rotation. 9334 * 9335 * @param rotation The degrees of rotation. 9336 * 9337 * @see #getRotation() 9338 * @see #getPivotX() 9339 * @see #getPivotY() 9340 * @see #setRotationX(float) 9341 * @see #setRotationY(float) 9342 * 9343 * @attr ref android.R.styleable#View_rotation 9344 */ 9345 public void setRotation(float rotation) { 9346 ensureTransformationInfo(); 9347 final TransformationInfo info = mTransformationInfo; 9348 if (info.mRotation != rotation) { 9349 // Double-invalidation is necessary to capture view's old and new areas 9350 invalidateViewProperty(true, false); 9351 info.mRotation = rotation; 9352 info.mMatrixDirty = true; 9353 invalidateViewProperty(false, true); 9354 if (mDisplayList != null) { 9355 mDisplayList.setRotation(rotation); 9356 } 9357 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9358 // View was rejected last time it was drawn by its parent; this may have changed 9359 invalidateParentIfNeeded(); 9360 } 9361 } 9362 } 9363 9364 /** 9365 * The degrees that the view is rotated around the vertical axis through the pivot point. 9366 * 9367 * @see #getPivotX() 9368 * @see #getPivotY() 9369 * @see #setRotationY(float) 9370 * 9371 * @return The degrees of Y rotation. 9372 */ 9373 @ViewDebug.ExportedProperty(category = "drawing") 9374 public float getRotationY() { 9375 return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0; 9376 } 9377 9378 /** 9379 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 9380 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 9381 * down the y axis. 9382 * 9383 * When rotating large views, it is recommended to adjust the camera distance 9384 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 9385 * 9386 * @param rotationY The degrees of Y rotation. 9387 * 9388 * @see #getRotationY() 9389 * @see #getPivotX() 9390 * @see #getPivotY() 9391 * @see #setRotation(float) 9392 * @see #setRotationX(float) 9393 * @see #setCameraDistance(float) 9394 * 9395 * @attr ref android.R.styleable#View_rotationY 9396 */ 9397 public void setRotationY(float rotationY) { 9398 ensureTransformationInfo(); 9399 final TransformationInfo info = mTransformationInfo; 9400 if (info.mRotationY != rotationY) { 9401 invalidateViewProperty(true, false); 9402 info.mRotationY = rotationY; 9403 info.mMatrixDirty = true; 9404 invalidateViewProperty(false, true); 9405 if (mDisplayList != null) { 9406 mDisplayList.setRotationY(rotationY); 9407 } 9408 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9409 // View was rejected last time it was drawn by its parent; this may have changed 9410 invalidateParentIfNeeded(); 9411 } 9412 } 9413 } 9414 9415 /** 9416 * The degrees that the view is rotated around the horizontal axis through the pivot point. 9417 * 9418 * @see #getPivotX() 9419 * @see #getPivotY() 9420 * @see #setRotationX(float) 9421 * 9422 * @return The degrees of X rotation. 9423 */ 9424 @ViewDebug.ExportedProperty(category = "drawing") 9425 public float getRotationX() { 9426 return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0; 9427 } 9428 9429 /** 9430 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 9431 * Increasing values result in clockwise rotation from the viewpoint of looking down the 9432 * x axis. 9433 * 9434 * When rotating large views, it is recommended to adjust the camera distance 9435 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 9436 * 9437 * @param rotationX The degrees of X rotation. 9438 * 9439 * @see #getRotationX() 9440 * @see #getPivotX() 9441 * @see #getPivotY() 9442 * @see #setRotation(float) 9443 * @see #setRotationY(float) 9444 * @see #setCameraDistance(float) 9445 * 9446 * @attr ref android.R.styleable#View_rotationX 9447 */ 9448 public void setRotationX(float rotationX) { 9449 ensureTransformationInfo(); 9450 final TransformationInfo info = mTransformationInfo; 9451 if (info.mRotationX != rotationX) { 9452 invalidateViewProperty(true, false); 9453 info.mRotationX = rotationX; 9454 info.mMatrixDirty = true; 9455 invalidateViewProperty(false, true); 9456 if (mDisplayList != null) { 9457 mDisplayList.setRotationX(rotationX); 9458 } 9459 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9460 // View was rejected last time it was drawn by its parent; this may have changed 9461 invalidateParentIfNeeded(); 9462 } 9463 } 9464 } 9465 9466 /** 9467 * The amount that the view is scaled in x around the pivot point, as a proportion of 9468 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 9469 * 9470 * <p>By default, this is 1.0f. 9471 * 9472 * @see #getPivotX() 9473 * @see #getPivotY() 9474 * @return The scaling factor. 9475 */ 9476 @ViewDebug.ExportedProperty(category = "drawing") 9477 public float getScaleX() { 9478 return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1; 9479 } 9480 9481 /** 9482 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 9483 * the view's unscaled width. A value of 1 means that no scaling is applied. 9484 * 9485 * @param scaleX The scaling factor. 9486 * @see #getPivotX() 9487 * @see #getPivotY() 9488 * 9489 * @attr ref android.R.styleable#View_scaleX 9490 */ 9491 public void setScaleX(float scaleX) { 9492 ensureTransformationInfo(); 9493 final TransformationInfo info = mTransformationInfo; 9494 if (info.mScaleX != scaleX) { 9495 invalidateViewProperty(true, false); 9496 info.mScaleX = scaleX; 9497 info.mMatrixDirty = true; 9498 invalidateViewProperty(false, true); 9499 if (mDisplayList != null) { 9500 mDisplayList.setScaleX(scaleX); 9501 } 9502 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9503 // View was rejected last time it was drawn by its parent; this may have changed 9504 invalidateParentIfNeeded(); 9505 } 9506 } 9507 } 9508 9509 /** 9510 * The amount that the view is scaled in y around the pivot point, as a proportion of 9511 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 9512 * 9513 * <p>By default, this is 1.0f. 9514 * 9515 * @see #getPivotX() 9516 * @see #getPivotY() 9517 * @return The scaling factor. 9518 */ 9519 @ViewDebug.ExportedProperty(category = "drawing") 9520 public float getScaleY() { 9521 return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1; 9522 } 9523 9524 /** 9525 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 9526 * the view's unscaled width. A value of 1 means that no scaling is applied. 9527 * 9528 * @param scaleY The scaling factor. 9529 * @see #getPivotX() 9530 * @see #getPivotY() 9531 * 9532 * @attr ref android.R.styleable#View_scaleY 9533 */ 9534 public void setScaleY(float scaleY) { 9535 ensureTransformationInfo(); 9536 final TransformationInfo info = mTransformationInfo; 9537 if (info.mScaleY != scaleY) { 9538 invalidateViewProperty(true, false); 9539 info.mScaleY = scaleY; 9540 info.mMatrixDirty = true; 9541 invalidateViewProperty(false, true); 9542 if (mDisplayList != null) { 9543 mDisplayList.setScaleY(scaleY); 9544 } 9545 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9546 // View was rejected last time it was drawn by its parent; this may have changed 9547 invalidateParentIfNeeded(); 9548 } 9549 } 9550 } 9551 9552 /** 9553 * The x location of the point around which the view is {@link #setRotation(float) rotated} 9554 * and {@link #setScaleX(float) scaled}. 9555 * 9556 * @see #getRotation() 9557 * @see #getScaleX() 9558 * @see #getScaleY() 9559 * @see #getPivotY() 9560 * @return The x location of the pivot point. 9561 * 9562 * @attr ref android.R.styleable#View_transformPivotX 9563 */ 9564 @ViewDebug.ExportedProperty(category = "drawing") 9565 public float getPivotX() { 9566 return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0; 9567 } 9568 9569 /** 9570 * Sets the x location of the point around which the view is 9571 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 9572 * By default, the pivot point is centered on the object. 9573 * Setting this property disables this behavior and causes the view to use only the 9574 * explicitly set pivotX and pivotY values. 9575 * 9576 * @param pivotX The x location of the pivot point. 9577 * @see #getRotation() 9578 * @see #getScaleX() 9579 * @see #getScaleY() 9580 * @see #getPivotY() 9581 * 9582 * @attr ref android.R.styleable#View_transformPivotX 9583 */ 9584 public void setPivotX(float pivotX) { 9585 ensureTransformationInfo(); 9586 final TransformationInfo info = mTransformationInfo; 9587 boolean pivotSet = (mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 9588 PFLAG_PIVOT_EXPLICITLY_SET; 9589 if (info.mPivotX != pivotX || !pivotSet) { 9590 mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET; 9591 invalidateViewProperty(true, false); 9592 info.mPivotX = pivotX; 9593 info.mMatrixDirty = true; 9594 invalidateViewProperty(false, true); 9595 if (mDisplayList != null) { 9596 mDisplayList.setPivotX(pivotX); 9597 } 9598 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9599 // View was rejected last time it was drawn by its parent; this may have changed 9600 invalidateParentIfNeeded(); 9601 } 9602 } 9603 } 9604 9605 /** 9606 * The y location of the point around which the view is {@link #setRotation(float) rotated} 9607 * and {@link #setScaleY(float) scaled}. 9608 * 9609 * @see #getRotation() 9610 * @see #getScaleX() 9611 * @see #getScaleY() 9612 * @see #getPivotY() 9613 * @return The y location of the pivot point. 9614 * 9615 * @attr ref android.R.styleable#View_transformPivotY 9616 */ 9617 @ViewDebug.ExportedProperty(category = "drawing") 9618 public float getPivotY() { 9619 return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0; 9620 } 9621 9622 /** 9623 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 9624 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 9625 * Setting this property disables this behavior and causes the view to use only the 9626 * explicitly set pivotX and pivotY values. 9627 * 9628 * @param pivotY The y location of the pivot point. 9629 * @see #getRotation() 9630 * @see #getScaleX() 9631 * @see #getScaleY() 9632 * @see #getPivotY() 9633 * 9634 * @attr ref android.R.styleable#View_transformPivotY 9635 */ 9636 public void setPivotY(float pivotY) { 9637 ensureTransformationInfo(); 9638 final TransformationInfo info = mTransformationInfo; 9639 boolean pivotSet = (mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 9640 PFLAG_PIVOT_EXPLICITLY_SET; 9641 if (info.mPivotY != pivotY || !pivotSet) { 9642 mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET; 9643 invalidateViewProperty(true, false); 9644 info.mPivotY = pivotY; 9645 info.mMatrixDirty = true; 9646 invalidateViewProperty(false, true); 9647 if (mDisplayList != null) { 9648 mDisplayList.setPivotY(pivotY); 9649 } 9650 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9651 // View was rejected last time it was drawn by its parent; this may have changed 9652 invalidateParentIfNeeded(); 9653 } 9654 } 9655 } 9656 9657 /** 9658 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 9659 * completely transparent and 1 means the view is completely opaque. 9660 * 9661 * <p>By default this is 1.0f. 9662 * @return The opacity of the view. 9663 */ 9664 @ViewDebug.ExportedProperty(category = "drawing") 9665 public float getAlpha() { 9666 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 9667 } 9668 9669 /** 9670 * Returns whether this View has content which overlaps. This function, intended to be 9671 * overridden by specific View types, is an optimization when alpha is set on a view. If 9672 * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer 9673 * and then composited it into place, which can be expensive. If the view has no overlapping 9674 * rendering, the view can draw each primitive with the appropriate alpha value directly. 9675 * An example of overlapping rendering is a TextView with a background image, such as a 9676 * Button. An example of non-overlapping rendering is a TextView with no background, or 9677 * an ImageView with only the foreground image. The default implementation returns true; 9678 * subclasses should override if they have cases which can be optimized. 9679 * 9680 * @return true if the content in this view might overlap, false otherwise. 9681 */ 9682 public boolean hasOverlappingRendering() { 9683 return true; 9684 } 9685 9686 /** 9687 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 9688 * completely transparent and 1 means the view is completely opaque.</p> 9689 * 9690 * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant 9691 * performance implications, especially for large views. It is best to use the alpha property 9692 * sparingly and transiently, as in the case of fading animations.</p> 9693 * 9694 * <p>For a view with a frequently changing alpha, such as during a fading animation, it is 9695 * strongly recommended for performance reasons to either override 9696 * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a 9697 * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p> 9698 * 9699 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 9700 * responsible for applying the opacity itself.</p> 9701 * 9702 * <p>Note that if the view is backed by a 9703 * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a 9704 * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than 9705 * 1.0 will supercede the alpha of the layer paint.</p> 9706 * 9707 * @param alpha The opacity of the view. 9708 * 9709 * @see #hasOverlappingRendering() 9710 * @see #setLayerType(int, android.graphics.Paint) 9711 * 9712 * @attr ref android.R.styleable#View_alpha 9713 */ 9714 public void setAlpha(float alpha) { 9715 ensureTransformationInfo(); 9716 if (mTransformationInfo.mAlpha != alpha) { 9717 mTransformationInfo.mAlpha = alpha; 9718 if (onSetAlpha((int) (alpha * 255))) { 9719 mPrivateFlags |= PFLAG_ALPHA_SET; 9720 // subclass is handling alpha - don't optimize rendering cache invalidation 9721 invalidateParentCaches(); 9722 invalidate(true); 9723 } else { 9724 mPrivateFlags &= ~PFLAG_ALPHA_SET; 9725 invalidateViewProperty(true, false); 9726 if (mDisplayList != null) { 9727 mDisplayList.setAlpha(alpha); 9728 } 9729 } 9730 } 9731 } 9732 9733 /** 9734 * Faster version of setAlpha() which performs the same steps except there are 9735 * no calls to invalidate(). The caller of this function should perform proper invalidation 9736 * on the parent and this object. The return value indicates whether the subclass handles 9737 * alpha (the return value for onSetAlpha()). 9738 * 9739 * @param alpha The new value for the alpha property 9740 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 9741 * the new value for the alpha property is different from the old value 9742 */ 9743 boolean setAlphaNoInvalidation(float alpha) { 9744 ensureTransformationInfo(); 9745 if (mTransformationInfo.mAlpha != alpha) { 9746 mTransformationInfo.mAlpha = alpha; 9747 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 9748 if (subclassHandlesAlpha) { 9749 mPrivateFlags |= PFLAG_ALPHA_SET; 9750 return true; 9751 } else { 9752 mPrivateFlags &= ~PFLAG_ALPHA_SET; 9753 if (mDisplayList != null) { 9754 mDisplayList.setAlpha(alpha); 9755 } 9756 } 9757 } 9758 return false; 9759 } 9760 9761 /** 9762 * Top position of this view relative to its parent. 9763 * 9764 * @return The top of this view, in pixels. 9765 */ 9766 @ViewDebug.CapturedViewProperty 9767 public final int getTop() { 9768 return mTop; 9769 } 9770 9771 /** 9772 * Sets the top position of this view relative to its parent. This method is meant to be called 9773 * by the layout system and should not generally be called otherwise, because the property 9774 * may be changed at any time by the layout. 9775 * 9776 * @param top The top of this view, in pixels. 9777 */ 9778 public final void setTop(int top) { 9779 if (top != mTop) { 9780 updateMatrix(); 9781 final boolean matrixIsIdentity = mTransformationInfo == null 9782 || mTransformationInfo.mMatrixIsIdentity; 9783 if (matrixIsIdentity) { 9784 if (mAttachInfo != null) { 9785 int minTop; 9786 int yLoc; 9787 if (top < mTop) { 9788 minTop = top; 9789 yLoc = top - mTop; 9790 } else { 9791 minTop = mTop; 9792 yLoc = 0; 9793 } 9794 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 9795 } 9796 } else { 9797 // Double-invalidation is necessary to capture view's old and new areas 9798 invalidate(true); 9799 } 9800 9801 int width = mRight - mLeft; 9802 int oldHeight = mBottom - mTop; 9803 9804 mTop = top; 9805 if (mDisplayList != null) { 9806 mDisplayList.setTop(mTop); 9807 } 9808 9809 sizeChange(width, mBottom - mTop, width, oldHeight); 9810 9811 if (!matrixIsIdentity) { 9812 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 9813 // A change in dimension means an auto-centered pivot point changes, too 9814 mTransformationInfo.mMatrixDirty = true; 9815 } 9816 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 9817 invalidate(true); 9818 } 9819 mBackgroundSizeChanged = true; 9820 invalidateParentIfNeeded(); 9821 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9822 // View was rejected last time it was drawn by its parent; this may have changed 9823 invalidateParentIfNeeded(); 9824 } 9825 } 9826 } 9827 9828 /** 9829 * Bottom position of this view relative to its parent. 9830 * 9831 * @return The bottom of this view, in pixels. 9832 */ 9833 @ViewDebug.CapturedViewProperty 9834 public final int getBottom() { 9835 return mBottom; 9836 } 9837 9838 /** 9839 * True if this view has changed since the last time being drawn. 9840 * 9841 * @return The dirty state of this view. 9842 */ 9843 public boolean isDirty() { 9844 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 9845 } 9846 9847 /** 9848 * Sets the bottom position of this view relative to its parent. This method is meant to be 9849 * called by the layout system and should not generally be called otherwise, because the 9850 * property may be changed at any time by the layout. 9851 * 9852 * @param bottom The bottom of this view, in pixels. 9853 */ 9854 public final void setBottom(int bottom) { 9855 if (bottom != mBottom) { 9856 updateMatrix(); 9857 final boolean matrixIsIdentity = mTransformationInfo == null 9858 || mTransformationInfo.mMatrixIsIdentity; 9859 if (matrixIsIdentity) { 9860 if (mAttachInfo != null) { 9861 int maxBottom; 9862 if (bottom < mBottom) { 9863 maxBottom = mBottom; 9864 } else { 9865 maxBottom = bottom; 9866 } 9867 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 9868 } 9869 } else { 9870 // Double-invalidation is necessary to capture view's old and new areas 9871 invalidate(true); 9872 } 9873 9874 int width = mRight - mLeft; 9875 int oldHeight = mBottom - mTop; 9876 9877 mBottom = bottom; 9878 if (mDisplayList != null) { 9879 mDisplayList.setBottom(mBottom); 9880 } 9881 9882 sizeChange(width, mBottom - mTop, width, oldHeight); 9883 9884 if (!matrixIsIdentity) { 9885 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 9886 // A change in dimension means an auto-centered pivot point changes, too 9887 mTransformationInfo.mMatrixDirty = true; 9888 } 9889 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 9890 invalidate(true); 9891 } 9892 mBackgroundSizeChanged = true; 9893 invalidateParentIfNeeded(); 9894 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9895 // View was rejected last time it was drawn by its parent; this may have changed 9896 invalidateParentIfNeeded(); 9897 } 9898 } 9899 } 9900 9901 /** 9902 * Left position of this view relative to its parent. 9903 * 9904 * @return The left edge of this view, in pixels. 9905 */ 9906 @ViewDebug.CapturedViewProperty 9907 public final int getLeft() { 9908 return mLeft; 9909 } 9910 9911 /** 9912 * Sets the left position of this view relative to its parent. This method is meant to be called 9913 * by the layout system and should not generally be called otherwise, because the property 9914 * may be changed at any time by the layout. 9915 * 9916 * @param left The bottom of this view, in pixels. 9917 */ 9918 public final void setLeft(int left) { 9919 if (left != mLeft) { 9920 updateMatrix(); 9921 final boolean matrixIsIdentity = mTransformationInfo == null 9922 || mTransformationInfo.mMatrixIsIdentity; 9923 if (matrixIsIdentity) { 9924 if (mAttachInfo != null) { 9925 int minLeft; 9926 int xLoc; 9927 if (left < mLeft) { 9928 minLeft = left; 9929 xLoc = left - mLeft; 9930 } else { 9931 minLeft = mLeft; 9932 xLoc = 0; 9933 } 9934 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 9935 } 9936 } else { 9937 // Double-invalidation is necessary to capture view's old and new areas 9938 invalidate(true); 9939 } 9940 9941 int oldWidth = mRight - mLeft; 9942 int height = mBottom - mTop; 9943 9944 mLeft = left; 9945 if (mDisplayList != null) { 9946 mDisplayList.setLeft(left); 9947 } 9948 9949 sizeChange(mRight - mLeft, height, oldWidth, height); 9950 9951 if (!matrixIsIdentity) { 9952 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 9953 // A change in dimension means an auto-centered pivot point changes, too 9954 mTransformationInfo.mMatrixDirty = true; 9955 } 9956 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 9957 invalidate(true); 9958 } 9959 mBackgroundSizeChanged = true; 9960 invalidateParentIfNeeded(); 9961 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9962 // View was rejected last time it was drawn by its parent; this may have changed 9963 invalidateParentIfNeeded(); 9964 } 9965 } 9966 } 9967 9968 /** 9969 * Right position of this view relative to its parent. 9970 * 9971 * @return The right edge of this view, in pixels. 9972 */ 9973 @ViewDebug.CapturedViewProperty 9974 public final int getRight() { 9975 return mRight; 9976 } 9977 9978 /** 9979 * Sets the right position of this view relative to its parent. This method is meant to be called 9980 * by the layout system and should not generally be called otherwise, because the property 9981 * may be changed at any time by the layout. 9982 * 9983 * @param right The bottom of this view, in pixels. 9984 */ 9985 public final void setRight(int right) { 9986 if (right != mRight) { 9987 updateMatrix(); 9988 final boolean matrixIsIdentity = mTransformationInfo == null 9989 || mTransformationInfo.mMatrixIsIdentity; 9990 if (matrixIsIdentity) { 9991 if (mAttachInfo != null) { 9992 int maxRight; 9993 if (right < mRight) { 9994 maxRight = mRight; 9995 } else { 9996 maxRight = right; 9997 } 9998 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 9999 } 10000 } else { 10001 // Double-invalidation is necessary to capture view's old and new areas 10002 invalidate(true); 10003 } 10004 10005 int oldWidth = mRight - mLeft; 10006 int height = mBottom - mTop; 10007 10008 mRight = right; 10009 if (mDisplayList != null) { 10010 mDisplayList.setRight(mRight); 10011 } 10012 10013 sizeChange(mRight - mLeft, height, oldWidth, height); 10014 10015 if (!matrixIsIdentity) { 10016 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 10017 // A change in dimension means an auto-centered pivot point changes, too 10018 mTransformationInfo.mMatrixDirty = true; 10019 } 10020 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10021 invalidate(true); 10022 } 10023 mBackgroundSizeChanged = true; 10024 invalidateParentIfNeeded(); 10025 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10026 // View was rejected last time it was drawn by its parent; this may have changed 10027 invalidateParentIfNeeded(); 10028 } 10029 } 10030 } 10031 10032 /** 10033 * The visual x position of this view, in pixels. This is equivalent to the 10034 * {@link #setTranslationX(float) translationX} property plus the current 10035 * {@link #getLeft() left} property. 10036 * 10037 * @return The visual x position of this view, in pixels. 10038 */ 10039 @ViewDebug.ExportedProperty(category = "drawing") 10040 public float getX() { 10041 return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0); 10042 } 10043 10044 /** 10045 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 10046 * {@link #setTranslationX(float) translationX} property to be the difference between 10047 * the x value passed in and the current {@link #getLeft() left} property. 10048 * 10049 * @param x The visual x position of this view, in pixels. 10050 */ 10051 public void setX(float x) { 10052 setTranslationX(x - mLeft); 10053 } 10054 10055 /** 10056 * The visual y position of this view, in pixels. This is equivalent to the 10057 * {@link #setTranslationY(float) translationY} property plus the current 10058 * {@link #getTop() top} property. 10059 * 10060 * @return The visual y position of this view, in pixels. 10061 */ 10062 @ViewDebug.ExportedProperty(category = "drawing") 10063 public float getY() { 10064 return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0); 10065 } 10066 10067 /** 10068 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 10069 * {@link #setTranslationY(float) translationY} property to be the difference between 10070 * the y value passed in and the current {@link #getTop() top} property. 10071 * 10072 * @param y The visual y position of this view, in pixels. 10073 */ 10074 public void setY(float y) { 10075 setTranslationY(y - mTop); 10076 } 10077 10078 10079 /** 10080 * The horizontal location of this view relative to its {@link #getLeft() left} position. 10081 * This position is post-layout, in addition to wherever the object's 10082 * layout placed it. 10083 * 10084 * @return The horizontal position of this view relative to its left position, in pixels. 10085 */ 10086 @ViewDebug.ExportedProperty(category = "drawing") 10087 public float getTranslationX() { 10088 return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0; 10089 } 10090 10091 /** 10092 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 10093 * This effectively positions the object post-layout, in addition to wherever the object's 10094 * layout placed it. 10095 * 10096 * @param translationX The horizontal position of this view relative to its left position, 10097 * in pixels. 10098 * 10099 * @attr ref android.R.styleable#View_translationX 10100 */ 10101 public void setTranslationX(float translationX) { 10102 ensureTransformationInfo(); 10103 final TransformationInfo info = mTransformationInfo; 10104 if (info.mTranslationX != translationX) { 10105 // Double-invalidation is necessary to capture view's old and new areas 10106 invalidateViewProperty(true, false); 10107 info.mTranslationX = translationX; 10108 info.mMatrixDirty = true; 10109 invalidateViewProperty(false, true); 10110 if (mDisplayList != null) { 10111 mDisplayList.setTranslationX(translationX); 10112 } 10113 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10114 // View was rejected last time it was drawn by its parent; this may have changed 10115 invalidateParentIfNeeded(); 10116 } 10117 } 10118 } 10119 10120 /** 10121 * The horizontal location of this view relative to its {@link #getTop() top} position. 10122 * This position is post-layout, in addition to wherever the object's 10123 * layout placed it. 10124 * 10125 * @return The vertical position of this view relative to its top position, 10126 * in pixels. 10127 */ 10128 @ViewDebug.ExportedProperty(category = "drawing") 10129 public float getTranslationY() { 10130 return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0; 10131 } 10132 10133 /** 10134 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 10135 * This effectively positions the object post-layout, in addition to wherever the object's 10136 * layout placed it. 10137 * 10138 * @param translationY The vertical position of this view relative to its top position, 10139 * in pixels. 10140 * 10141 * @attr ref android.R.styleable#View_translationY 10142 */ 10143 public void setTranslationY(float translationY) { 10144 ensureTransformationInfo(); 10145 final TransformationInfo info = mTransformationInfo; 10146 if (info.mTranslationY != translationY) { 10147 invalidateViewProperty(true, false); 10148 info.mTranslationY = translationY; 10149 info.mMatrixDirty = true; 10150 invalidateViewProperty(false, true); 10151 if (mDisplayList != null) { 10152 mDisplayList.setTranslationY(translationY); 10153 } 10154 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10155 // View was rejected last time it was drawn by its parent; this may have changed 10156 invalidateParentIfNeeded(); 10157 } 10158 } 10159 } 10160 10161 /** 10162 * Hit rectangle in parent's coordinates 10163 * 10164 * @param outRect The hit rectangle of the view. 10165 */ 10166 public void getHitRect(Rect outRect) { 10167 updateMatrix(); 10168 final TransformationInfo info = mTransformationInfo; 10169 if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) { 10170 outRect.set(mLeft, mTop, mRight, mBottom); 10171 } else { 10172 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 10173 tmpRect.set(0, 0, getWidth(), getHeight()); 10174 info.mMatrix.mapRect(tmpRect); 10175 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 10176 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 10177 } 10178 } 10179 10180 /** 10181 * Determines whether the given point, in local coordinates is inside the view. 10182 */ 10183 /*package*/ final boolean pointInView(float localX, float localY) { 10184 return localX >= 0 && localX < (mRight - mLeft) 10185 && localY >= 0 && localY < (mBottom - mTop); 10186 } 10187 10188 /** 10189 * Utility method to determine whether the given point, in local coordinates, 10190 * is inside the view, where the area of the view is expanded by the slop factor. 10191 * This method is called while processing touch-move events to determine if the event 10192 * is still within the view. 10193 * 10194 * @hide 10195 */ 10196 public boolean pointInView(float localX, float localY, float slop) { 10197 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 10198 localY < ((mBottom - mTop) + slop); 10199 } 10200 10201 /** 10202 * When a view has focus and the user navigates away from it, the next view is searched for 10203 * starting from the rectangle filled in by this method. 10204 * 10205 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 10206 * of the view. However, if your view maintains some idea of internal selection, 10207 * such as a cursor, or a selected row or column, you should override this method and 10208 * fill in a more specific rectangle. 10209 * 10210 * @param r The rectangle to fill in, in this view's coordinates. 10211 */ 10212 public void getFocusedRect(Rect r) { 10213 getDrawingRect(r); 10214 } 10215 10216 /** 10217 * If some part of this view is not clipped by any of its parents, then 10218 * return that area in r in global (root) coordinates. To convert r to local 10219 * coordinates (without taking possible View rotations into account), offset 10220 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 10221 * If the view is completely clipped or translated out, return false. 10222 * 10223 * @param r If true is returned, r holds the global coordinates of the 10224 * visible portion of this view. 10225 * @param globalOffset If true is returned, globalOffset holds the dx,dy 10226 * between this view and its root. globalOffet may be null. 10227 * @return true if r is non-empty (i.e. part of the view is visible at the 10228 * root level. 10229 */ 10230 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 10231 int width = mRight - mLeft; 10232 int height = mBottom - mTop; 10233 if (width > 0 && height > 0) { 10234 r.set(0, 0, width, height); 10235 if (globalOffset != null) { 10236 globalOffset.set(-mScrollX, -mScrollY); 10237 } 10238 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 10239 } 10240 return false; 10241 } 10242 10243 public final boolean getGlobalVisibleRect(Rect r) { 10244 return getGlobalVisibleRect(r, null); 10245 } 10246 10247 public final boolean getLocalVisibleRect(Rect r) { 10248 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 10249 if (getGlobalVisibleRect(r, offset)) { 10250 r.offset(-offset.x, -offset.y); // make r local 10251 return true; 10252 } 10253 return false; 10254 } 10255 10256 /** 10257 * Offset this view's vertical location by the specified number of pixels. 10258 * 10259 * @param offset the number of pixels to offset the view by 10260 */ 10261 public void offsetTopAndBottom(int offset) { 10262 if (offset != 0) { 10263 updateMatrix(); 10264 final boolean matrixIsIdentity = mTransformationInfo == null 10265 || mTransformationInfo.mMatrixIsIdentity; 10266 if (matrixIsIdentity) { 10267 if (mDisplayList != null) { 10268 invalidateViewProperty(false, false); 10269 } else { 10270 final ViewParent p = mParent; 10271 if (p != null && mAttachInfo != null) { 10272 final Rect r = mAttachInfo.mTmpInvalRect; 10273 int minTop; 10274 int maxBottom; 10275 int yLoc; 10276 if (offset < 0) { 10277 minTop = mTop + offset; 10278 maxBottom = mBottom; 10279 yLoc = offset; 10280 } else { 10281 minTop = mTop; 10282 maxBottom = mBottom + offset; 10283 yLoc = 0; 10284 } 10285 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 10286 p.invalidateChild(this, r); 10287 } 10288 } 10289 } else { 10290 invalidateViewProperty(false, false); 10291 } 10292 10293 mTop += offset; 10294 mBottom += offset; 10295 if (mDisplayList != null) { 10296 mDisplayList.offsetTopAndBottom(offset); 10297 invalidateViewProperty(false, false); 10298 } else { 10299 if (!matrixIsIdentity) { 10300 invalidateViewProperty(false, true); 10301 } 10302 invalidateParentIfNeeded(); 10303 } 10304 } 10305 } 10306 10307 /** 10308 * Offset this view's horizontal location by the specified amount of pixels. 10309 * 10310 * @param offset the number of pixels to offset the view by 10311 */ 10312 public void offsetLeftAndRight(int offset) { 10313 if (offset != 0) { 10314 updateMatrix(); 10315 final boolean matrixIsIdentity = mTransformationInfo == null 10316 || mTransformationInfo.mMatrixIsIdentity; 10317 if (matrixIsIdentity) { 10318 if (mDisplayList != null) { 10319 invalidateViewProperty(false, false); 10320 } else { 10321 final ViewParent p = mParent; 10322 if (p != null && mAttachInfo != null) { 10323 final Rect r = mAttachInfo.mTmpInvalRect; 10324 int minLeft; 10325 int maxRight; 10326 if (offset < 0) { 10327 minLeft = mLeft + offset; 10328 maxRight = mRight; 10329 } else { 10330 minLeft = mLeft; 10331 maxRight = mRight + offset; 10332 } 10333 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 10334 p.invalidateChild(this, r); 10335 } 10336 } 10337 } else { 10338 invalidateViewProperty(false, false); 10339 } 10340 10341 mLeft += offset; 10342 mRight += offset; 10343 if (mDisplayList != null) { 10344 mDisplayList.offsetLeftAndRight(offset); 10345 invalidateViewProperty(false, false); 10346 } else { 10347 if (!matrixIsIdentity) { 10348 invalidateViewProperty(false, true); 10349 } 10350 invalidateParentIfNeeded(); 10351 } 10352 } 10353 } 10354 10355 /** 10356 * Get the LayoutParams associated with this view. All views should have 10357 * layout parameters. These supply parameters to the <i>parent</i> of this 10358 * view specifying how it should be arranged. There are many subclasses of 10359 * ViewGroup.LayoutParams, and these correspond to the different subclasses 10360 * of ViewGroup that are responsible for arranging their children. 10361 * 10362 * This method may return null if this View is not attached to a parent 10363 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 10364 * was not invoked successfully. When a View is attached to a parent 10365 * ViewGroup, this method must not return null. 10366 * 10367 * @return The LayoutParams associated with this view, or null if no 10368 * parameters have been set yet 10369 */ 10370 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 10371 public ViewGroup.LayoutParams getLayoutParams() { 10372 return mLayoutParams; 10373 } 10374 10375 /** 10376 * Set the layout parameters associated with this view. These supply 10377 * parameters to the <i>parent</i> of this view specifying how it should be 10378 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 10379 * correspond to the different subclasses of ViewGroup that are responsible 10380 * for arranging their children. 10381 * 10382 * @param params The layout parameters for this view, cannot be null 10383 */ 10384 public void setLayoutParams(ViewGroup.LayoutParams params) { 10385 if (params == null) { 10386 throw new NullPointerException("Layout parameters cannot be null"); 10387 } 10388 mLayoutParams = params; 10389 resolveLayoutParams(); 10390 if (mParent instanceof ViewGroup) { 10391 ((ViewGroup) mParent).onSetLayoutParams(this, params); 10392 } 10393 requestLayout(); 10394 } 10395 10396 /** 10397 * Resolve the layout parameters depending on the resolved layout direction 10398 * 10399 * @hide 10400 */ 10401 public void resolveLayoutParams() { 10402 if (mLayoutParams != null) { 10403 mLayoutParams.resolveLayoutDirection(getLayoutDirection()); 10404 } 10405 } 10406 10407 /** 10408 * Set the scrolled position of your view. This will cause a call to 10409 * {@link #onScrollChanged(int, int, int, int)} and the view will be 10410 * invalidated. 10411 * @param x the x position to scroll to 10412 * @param y the y position to scroll to 10413 */ 10414 public void scrollTo(int x, int y) { 10415 if (mScrollX != x || mScrollY != y) { 10416 int oldX = mScrollX; 10417 int oldY = mScrollY; 10418 mScrollX = x; 10419 mScrollY = y; 10420 invalidateParentCaches(); 10421 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 10422 if (!awakenScrollBars()) { 10423 postInvalidateOnAnimation(); 10424 } 10425 } 10426 } 10427 10428 /** 10429 * Move the scrolled position of your view. This will cause a call to 10430 * {@link #onScrollChanged(int, int, int, int)} and the view will be 10431 * invalidated. 10432 * @param x the amount of pixels to scroll by horizontally 10433 * @param y the amount of pixels to scroll by vertically 10434 */ 10435 public void scrollBy(int x, int y) { 10436 scrollTo(mScrollX + x, mScrollY + y); 10437 } 10438 10439 /** 10440 * <p>Trigger the scrollbars to draw. When invoked this method starts an 10441 * animation to fade the scrollbars out after a default delay. If a subclass 10442 * provides animated scrolling, the start delay should equal the duration 10443 * of the scrolling animation.</p> 10444 * 10445 * <p>The animation starts only if at least one of the scrollbars is 10446 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 10447 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 10448 * this method returns true, and false otherwise. If the animation is 10449 * started, this method calls {@link #invalidate()}; in that case the 10450 * caller should not call {@link #invalidate()}.</p> 10451 * 10452 * <p>This method should be invoked every time a subclass directly updates 10453 * the scroll parameters.</p> 10454 * 10455 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 10456 * and {@link #scrollTo(int, int)}.</p> 10457 * 10458 * @return true if the animation is played, false otherwise 10459 * 10460 * @see #awakenScrollBars(int) 10461 * @see #scrollBy(int, int) 10462 * @see #scrollTo(int, int) 10463 * @see #isHorizontalScrollBarEnabled() 10464 * @see #isVerticalScrollBarEnabled() 10465 * @see #setHorizontalScrollBarEnabled(boolean) 10466 * @see #setVerticalScrollBarEnabled(boolean) 10467 */ 10468 protected boolean awakenScrollBars() { 10469 return mScrollCache != null && 10470 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 10471 } 10472 10473 /** 10474 * Trigger the scrollbars to draw. 10475 * This method differs from awakenScrollBars() only in its default duration. 10476 * initialAwakenScrollBars() will show the scroll bars for longer than 10477 * usual to give the user more of a chance to notice them. 10478 * 10479 * @return true if the animation is played, false otherwise. 10480 */ 10481 private boolean initialAwakenScrollBars() { 10482 return mScrollCache != null && 10483 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 10484 } 10485 10486 /** 10487 * <p> 10488 * Trigger the scrollbars to draw. When invoked this method starts an 10489 * animation to fade the scrollbars out after a fixed delay. If a subclass 10490 * provides animated scrolling, the start delay should equal the duration of 10491 * the scrolling animation. 10492 * </p> 10493 * 10494 * <p> 10495 * The animation starts only if at least one of the scrollbars is enabled, 10496 * as specified by {@link #isHorizontalScrollBarEnabled()} and 10497 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 10498 * this method returns true, and false otherwise. If the animation is 10499 * started, this method calls {@link #invalidate()}; in that case the caller 10500 * should not call {@link #invalidate()}. 10501 * </p> 10502 * 10503 * <p> 10504 * This method should be invoked everytime a subclass directly updates the 10505 * scroll parameters. 10506 * </p> 10507 * 10508 * @param startDelay the delay, in milliseconds, after which the animation 10509 * should start; when the delay is 0, the animation starts 10510 * immediately 10511 * @return true if the animation is played, false otherwise 10512 * 10513 * @see #scrollBy(int, int) 10514 * @see #scrollTo(int, int) 10515 * @see #isHorizontalScrollBarEnabled() 10516 * @see #isVerticalScrollBarEnabled() 10517 * @see #setHorizontalScrollBarEnabled(boolean) 10518 * @see #setVerticalScrollBarEnabled(boolean) 10519 */ 10520 protected boolean awakenScrollBars(int startDelay) { 10521 return awakenScrollBars(startDelay, true); 10522 } 10523 10524 /** 10525 * <p> 10526 * Trigger the scrollbars to draw. When invoked this method starts an 10527 * animation to fade the scrollbars out after a fixed delay. If a subclass 10528 * provides animated scrolling, the start delay should equal the duration of 10529 * the scrolling animation. 10530 * </p> 10531 * 10532 * <p> 10533 * The animation starts only if at least one of the scrollbars is enabled, 10534 * as specified by {@link #isHorizontalScrollBarEnabled()} and 10535 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 10536 * this method returns true, and false otherwise. If the animation is 10537 * started, this method calls {@link #invalidate()} if the invalidate parameter 10538 * is set to true; in that case the caller 10539 * should not call {@link #invalidate()}. 10540 * </p> 10541 * 10542 * <p> 10543 * This method should be invoked everytime a subclass directly updates the 10544 * scroll parameters. 10545 * </p> 10546 * 10547 * @param startDelay the delay, in milliseconds, after which the animation 10548 * should start; when the delay is 0, the animation starts 10549 * immediately 10550 * 10551 * @param invalidate Wheter this method should call invalidate 10552 * 10553 * @return true if the animation is played, false otherwise 10554 * 10555 * @see #scrollBy(int, int) 10556 * @see #scrollTo(int, int) 10557 * @see #isHorizontalScrollBarEnabled() 10558 * @see #isVerticalScrollBarEnabled() 10559 * @see #setHorizontalScrollBarEnabled(boolean) 10560 * @see #setVerticalScrollBarEnabled(boolean) 10561 */ 10562 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 10563 final ScrollabilityCache scrollCache = mScrollCache; 10564 10565 if (scrollCache == null || !scrollCache.fadeScrollBars) { 10566 return false; 10567 } 10568 10569 if (scrollCache.scrollBar == null) { 10570 scrollCache.scrollBar = new ScrollBarDrawable(); 10571 } 10572 10573 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 10574 10575 if (invalidate) { 10576 // Invalidate to show the scrollbars 10577 postInvalidateOnAnimation(); 10578 } 10579 10580 if (scrollCache.state == ScrollabilityCache.OFF) { 10581 // FIXME: this is copied from WindowManagerService. 10582 // We should get this value from the system when it 10583 // is possible to do so. 10584 final int KEY_REPEAT_FIRST_DELAY = 750; 10585 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 10586 } 10587 10588 // Tell mScrollCache when we should start fading. This may 10589 // extend the fade start time if one was already scheduled 10590 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 10591 scrollCache.fadeStartTime = fadeStartTime; 10592 scrollCache.state = ScrollabilityCache.ON; 10593 10594 // Schedule our fader to run, unscheduling any old ones first 10595 if (mAttachInfo != null) { 10596 mAttachInfo.mHandler.removeCallbacks(scrollCache); 10597 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 10598 } 10599 10600 return true; 10601 } 10602 10603 return false; 10604 } 10605 10606 /** 10607 * Do not invalidate views which are not visible and which are not running an animation. They 10608 * will not get drawn and they should not set dirty flags as if they will be drawn 10609 */ 10610 private boolean skipInvalidate() { 10611 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 10612 (!(mParent instanceof ViewGroup) || 10613 !((ViewGroup) mParent).isViewTransitioning(this)); 10614 } 10615 /** 10616 * Mark the area defined by dirty as needing to be drawn. If the view is 10617 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point 10618 * in the future. This must be called from a UI thread. To call from a non-UI 10619 * thread, call {@link #postInvalidate()}. 10620 * 10621 * WARNING: This method is destructive to dirty. 10622 * @param dirty the rectangle representing the bounds of the dirty region 10623 */ 10624 public void invalidate(Rect dirty) { 10625 if (skipInvalidate()) { 10626 return; 10627 } 10628 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) || 10629 (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID || 10630 (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) { 10631 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 10632 mPrivateFlags |= PFLAG_INVALIDATED; 10633 mPrivateFlags |= PFLAG_DIRTY; 10634 final ViewParent p = mParent; 10635 final AttachInfo ai = mAttachInfo; 10636 //noinspection PointlessBooleanExpression,ConstantConditions 10637 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 10638 if (p != null && ai != null && ai.mHardwareAccelerated) { 10639 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 10640 // with a null dirty rect, which tells the ViewAncestor to redraw everything 10641 p.invalidateChild(this, null); 10642 return; 10643 } 10644 } 10645 if (p != null && ai != null) { 10646 final int scrollX = mScrollX; 10647 final int scrollY = mScrollY; 10648 final Rect r = ai.mTmpInvalRect; 10649 r.set(dirty.left - scrollX, dirty.top - scrollY, 10650 dirty.right - scrollX, dirty.bottom - scrollY); 10651 mParent.invalidateChild(this, r); 10652 } 10653 } 10654 } 10655 10656 /** 10657 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. 10658 * The coordinates of the dirty rect are relative to the view. 10659 * If the view is visible, {@link #onDraw(android.graphics.Canvas)} 10660 * will be called at some point in the future. This must be called from 10661 * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}. 10662 * @param l the left position of the dirty region 10663 * @param t the top position of the dirty region 10664 * @param r the right position of the dirty region 10665 * @param b the bottom position of the dirty region 10666 */ 10667 public void invalidate(int l, int t, int r, int b) { 10668 if (skipInvalidate()) { 10669 return; 10670 } 10671 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) || 10672 (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID || 10673 (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) { 10674 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 10675 mPrivateFlags |= PFLAG_INVALIDATED; 10676 mPrivateFlags |= PFLAG_DIRTY; 10677 final ViewParent p = mParent; 10678 final AttachInfo ai = mAttachInfo; 10679 //noinspection PointlessBooleanExpression,ConstantConditions 10680 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 10681 if (p != null && ai != null && ai.mHardwareAccelerated) { 10682 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 10683 // with a null dirty rect, which tells the ViewAncestor to redraw everything 10684 p.invalidateChild(this, null); 10685 return; 10686 } 10687 } 10688 if (p != null && ai != null && l < r && t < b) { 10689 final int scrollX = mScrollX; 10690 final int scrollY = mScrollY; 10691 final Rect tmpr = ai.mTmpInvalRect; 10692 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY); 10693 p.invalidateChild(this, tmpr); 10694 } 10695 } 10696 } 10697 10698 /** 10699 * Invalidate the whole view. If the view is visible, 10700 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 10701 * the future. This must be called from a UI thread. To call from a non-UI thread, 10702 * call {@link #postInvalidate()}. 10703 */ 10704 public void invalidate() { 10705 invalidate(true); 10706 } 10707 10708 /** 10709 * This is where the invalidate() work actually happens. A full invalidate() 10710 * causes the drawing cache to be invalidated, but this function can be called with 10711 * invalidateCache set to false to skip that invalidation step for cases that do not 10712 * need it (for example, a component that remains at the same dimensions with the same 10713 * content). 10714 * 10715 * @param invalidateCache Whether the drawing cache for this view should be invalidated as 10716 * well. This is usually true for a full invalidate, but may be set to false if the 10717 * View's contents or dimensions have not changed. 10718 */ 10719 void invalidate(boolean invalidateCache) { 10720 if (skipInvalidate()) { 10721 return; 10722 } 10723 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) || 10724 (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) || 10725 (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED || isOpaque() != mLastIsOpaque) { 10726 mLastIsOpaque = isOpaque(); 10727 mPrivateFlags &= ~PFLAG_DRAWN; 10728 mPrivateFlags |= PFLAG_DIRTY; 10729 if (invalidateCache) { 10730 mPrivateFlags |= PFLAG_INVALIDATED; 10731 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 10732 } 10733 final AttachInfo ai = mAttachInfo; 10734 final ViewParent p = mParent; 10735 //noinspection PointlessBooleanExpression,ConstantConditions 10736 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 10737 if (p != null && ai != null && ai.mHardwareAccelerated) { 10738 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 10739 // with a null dirty rect, which tells the ViewAncestor to redraw everything 10740 p.invalidateChild(this, null); 10741 return; 10742 } 10743 } 10744 10745 if (p != null && ai != null) { 10746 final Rect r = ai.mTmpInvalRect; 10747 r.set(0, 0, mRight - mLeft, mBottom - mTop); 10748 // Don't call invalidate -- we don't want to internally scroll 10749 // our own bounds 10750 p.invalidateChild(this, r); 10751 } 10752 } 10753 } 10754 10755 /** 10756 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 10757 * set any flags or handle all of the cases handled by the default invalidation methods. 10758 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 10759 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 10760 * walk up the hierarchy, transforming the dirty rect as necessary. 10761 * 10762 * The method also handles normal invalidation logic if display list properties are not 10763 * being used in this view. The invalidateParent and forceRedraw flags are used by that 10764 * backup approach, to handle these cases used in the various property-setting methods. 10765 * 10766 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 10767 * are not being used in this view 10768 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 10769 * list properties are not being used in this view 10770 */ 10771 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 10772 if (mDisplayList == null || (mPrivateFlags & PFLAG_DRAW_ANIMATION) == PFLAG_DRAW_ANIMATION) { 10773 if (invalidateParent) { 10774 invalidateParentCaches(); 10775 } 10776 if (forceRedraw) { 10777 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10778 } 10779 invalidate(false); 10780 } else { 10781 final AttachInfo ai = mAttachInfo; 10782 final ViewParent p = mParent; 10783 if (p != null && ai != null) { 10784 final Rect r = ai.mTmpInvalRect; 10785 r.set(0, 0, mRight - mLeft, mBottom - mTop); 10786 if (mParent instanceof ViewGroup) { 10787 ((ViewGroup) mParent).invalidateChildFast(this, r); 10788 } else { 10789 mParent.invalidateChild(this, r); 10790 } 10791 } 10792 } 10793 } 10794 10795 /** 10796 * Utility method to transform a given Rect by the current matrix of this view. 10797 */ 10798 void transformRect(final Rect rect) { 10799 if (!getMatrix().isIdentity()) { 10800 RectF boundingRect = mAttachInfo.mTmpTransformRect; 10801 boundingRect.set(rect); 10802 getMatrix().mapRect(boundingRect); 10803 rect.set((int) Math.floor(boundingRect.left), 10804 (int) Math.floor(boundingRect.top), 10805 (int) Math.ceil(boundingRect.right), 10806 (int) Math.ceil(boundingRect.bottom)); 10807 } 10808 } 10809 10810 /** 10811 * Used to indicate that the parent of this view should clear its caches. This functionality 10812 * is used to force the parent to rebuild its display list (when hardware-accelerated), 10813 * which is necessary when various parent-managed properties of the view change, such as 10814 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 10815 * clears the parent caches and does not causes an invalidate event. 10816 * 10817 * @hide 10818 */ 10819 protected void invalidateParentCaches() { 10820 if (mParent instanceof View) { 10821 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 10822 } 10823 } 10824 10825 /** 10826 * Used to indicate that the parent of this view should be invalidated. This functionality 10827 * is used to force the parent to rebuild its display list (when hardware-accelerated), 10828 * which is necessary when various parent-managed properties of the view change, such as 10829 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 10830 * an invalidation event to the parent. 10831 * 10832 * @hide 10833 */ 10834 protected void invalidateParentIfNeeded() { 10835 if (isHardwareAccelerated() && mParent instanceof View) { 10836 ((View) mParent).invalidate(true); 10837 } 10838 } 10839 10840 /** 10841 * Indicates whether this View is opaque. An opaque View guarantees that it will 10842 * draw all the pixels overlapping its bounds using a fully opaque color. 10843 * 10844 * Subclasses of View should override this method whenever possible to indicate 10845 * whether an instance is opaque. Opaque Views are treated in a special way by 10846 * the View hierarchy, possibly allowing it to perform optimizations during 10847 * invalidate/draw passes. 10848 * 10849 * @return True if this View is guaranteed to be fully opaque, false otherwise. 10850 */ 10851 @ViewDebug.ExportedProperty(category = "drawing") 10852 public boolean isOpaque() { 10853 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 10854 ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1.0f) >= 1.0f); 10855 } 10856 10857 /** 10858 * @hide 10859 */ 10860 protected void computeOpaqueFlags() { 10861 // Opaque if: 10862 // - Has a background 10863 // - Background is opaque 10864 // - Doesn't have scrollbars or scrollbars overlay 10865 10866 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 10867 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 10868 } else { 10869 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 10870 } 10871 10872 final int flags = mViewFlags; 10873 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 10874 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY || 10875 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) { 10876 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 10877 } else { 10878 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 10879 } 10880 } 10881 10882 /** 10883 * @hide 10884 */ 10885 protected boolean hasOpaqueScrollbars() { 10886 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 10887 } 10888 10889 /** 10890 * @return A handler associated with the thread running the View. This 10891 * handler can be used to pump events in the UI events queue. 10892 */ 10893 public Handler getHandler() { 10894 final AttachInfo attachInfo = mAttachInfo; 10895 if (attachInfo != null) { 10896 return attachInfo.mHandler; 10897 } 10898 return null; 10899 } 10900 10901 /** 10902 * Gets the view root associated with the View. 10903 * @return The view root, or null if none. 10904 * @hide 10905 */ 10906 public ViewRootImpl getViewRootImpl() { 10907 if (mAttachInfo != null) { 10908 return mAttachInfo.mViewRootImpl; 10909 } 10910 return null; 10911 } 10912 10913 /** 10914 * <p>Causes the Runnable to be added to the message queue. 10915 * The runnable will be run on the user interface thread.</p> 10916 * 10917 * @param action The Runnable that will be executed. 10918 * 10919 * @return Returns true if the Runnable was successfully placed in to the 10920 * message queue. Returns false on failure, usually because the 10921 * looper processing the message queue is exiting. 10922 * 10923 * @see #postDelayed 10924 * @see #removeCallbacks 10925 */ 10926 public boolean post(Runnable action) { 10927 final AttachInfo attachInfo = mAttachInfo; 10928 if (attachInfo != null) { 10929 return attachInfo.mHandler.post(action); 10930 } 10931 // Assume that post will succeed later 10932 ViewRootImpl.getRunQueue().post(action); 10933 return true; 10934 } 10935 10936 /** 10937 * <p>Causes the Runnable to be added to the message queue, to be run 10938 * after the specified amount of time elapses. 10939 * The runnable will be run on the user interface thread.</p> 10940 * 10941 * @param action The Runnable that will be executed. 10942 * @param delayMillis The delay (in milliseconds) until the Runnable 10943 * will be executed. 10944 * 10945 * @return true if the Runnable was successfully placed in to the 10946 * message queue. Returns false on failure, usually because the 10947 * looper processing the message queue is exiting. Note that a 10948 * result of true does not mean the Runnable will be processed -- 10949 * if the looper is quit before the delivery time of the message 10950 * occurs then the message will be dropped. 10951 * 10952 * @see #post 10953 * @see #removeCallbacks 10954 */ 10955 public boolean postDelayed(Runnable action, long delayMillis) { 10956 final AttachInfo attachInfo = mAttachInfo; 10957 if (attachInfo != null) { 10958 return attachInfo.mHandler.postDelayed(action, delayMillis); 10959 } 10960 // Assume that post will succeed later 10961 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 10962 return true; 10963 } 10964 10965 /** 10966 * <p>Causes the Runnable to execute on the next animation time step. 10967 * The runnable will be run on the user interface thread.</p> 10968 * 10969 * @param action The Runnable that will be executed. 10970 * 10971 * @see #postOnAnimationDelayed 10972 * @see #removeCallbacks 10973 */ 10974 public void postOnAnimation(Runnable action) { 10975 final AttachInfo attachInfo = mAttachInfo; 10976 if (attachInfo != null) { 10977 attachInfo.mViewRootImpl.mChoreographer.postCallback( 10978 Choreographer.CALLBACK_ANIMATION, action, null); 10979 } else { 10980 // Assume that post will succeed later 10981 ViewRootImpl.getRunQueue().post(action); 10982 } 10983 } 10984 10985 /** 10986 * <p>Causes the Runnable to execute on the next animation time step, 10987 * after the specified amount of time elapses. 10988 * The runnable will be run on the user interface thread.</p> 10989 * 10990 * @param action The Runnable that will be executed. 10991 * @param delayMillis The delay (in milliseconds) until the Runnable 10992 * will be executed. 10993 * 10994 * @see #postOnAnimation 10995 * @see #removeCallbacks 10996 */ 10997 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 10998 final AttachInfo attachInfo = mAttachInfo; 10999 if (attachInfo != null) { 11000 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 11001 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 11002 } else { 11003 // Assume that post will succeed later 11004 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 11005 } 11006 } 11007 11008 /** 11009 * <p>Removes the specified Runnable from the message queue.</p> 11010 * 11011 * @param action The Runnable to remove from the message handling queue 11012 * 11013 * @return true if this view could ask the Handler to remove the Runnable, 11014 * false otherwise. When the returned value is true, the Runnable 11015 * may or may not have been actually removed from the message queue 11016 * (for instance, if the Runnable was not in the queue already.) 11017 * 11018 * @see #post 11019 * @see #postDelayed 11020 * @see #postOnAnimation 11021 * @see #postOnAnimationDelayed 11022 */ 11023 public boolean removeCallbacks(Runnable action) { 11024 if (action != null) { 11025 final AttachInfo attachInfo = mAttachInfo; 11026 if (attachInfo != null) { 11027 attachInfo.mHandler.removeCallbacks(action); 11028 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 11029 Choreographer.CALLBACK_ANIMATION, action, null); 11030 } else { 11031 // Assume that post will succeed later 11032 ViewRootImpl.getRunQueue().removeCallbacks(action); 11033 } 11034 } 11035 return true; 11036 } 11037 11038 /** 11039 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 11040 * Use this to invalidate the View from a non-UI thread.</p> 11041 * 11042 * <p>This method can be invoked from outside of the UI thread 11043 * only when this View is attached to a window.</p> 11044 * 11045 * @see #invalidate() 11046 * @see #postInvalidateDelayed(long) 11047 */ 11048 public void postInvalidate() { 11049 postInvalidateDelayed(0); 11050 } 11051 11052 /** 11053 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 11054 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 11055 * 11056 * <p>This method can be invoked from outside of the UI thread 11057 * only when this View is attached to a window.</p> 11058 * 11059 * @param left The left coordinate of the rectangle to invalidate. 11060 * @param top The top coordinate of the rectangle to invalidate. 11061 * @param right The right coordinate of the rectangle to invalidate. 11062 * @param bottom The bottom coordinate of the rectangle to invalidate. 11063 * 11064 * @see #invalidate(int, int, int, int) 11065 * @see #invalidate(Rect) 11066 * @see #postInvalidateDelayed(long, int, int, int, int) 11067 */ 11068 public void postInvalidate(int left, int top, int right, int bottom) { 11069 postInvalidateDelayed(0, left, top, right, bottom); 11070 } 11071 11072 /** 11073 * <p>Cause an invalidate to happen on a subsequent cycle through the event 11074 * loop. Waits for the specified amount of time.</p> 11075 * 11076 * <p>This method can be invoked from outside of the UI thread 11077 * only when this View is attached to a window.</p> 11078 * 11079 * @param delayMilliseconds the duration in milliseconds to delay the 11080 * invalidation by 11081 * 11082 * @see #invalidate() 11083 * @see #postInvalidate() 11084 */ 11085 public void postInvalidateDelayed(long delayMilliseconds) { 11086 // We try only with the AttachInfo because there's no point in invalidating 11087 // if we are not attached to our window 11088 final AttachInfo attachInfo = mAttachInfo; 11089 if (attachInfo != null) { 11090 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 11091 } 11092 } 11093 11094 /** 11095 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 11096 * through the event loop. Waits for the specified amount of time.</p> 11097 * 11098 * <p>This method can be invoked from outside of the UI thread 11099 * only when this View is attached to a window.</p> 11100 * 11101 * @param delayMilliseconds the duration in milliseconds to delay the 11102 * invalidation by 11103 * @param left The left coordinate of the rectangle to invalidate. 11104 * @param top The top coordinate of the rectangle to invalidate. 11105 * @param right The right coordinate of the rectangle to invalidate. 11106 * @param bottom The bottom coordinate of the rectangle to invalidate. 11107 * 11108 * @see #invalidate(int, int, int, int) 11109 * @see #invalidate(Rect) 11110 * @see #postInvalidate(int, int, int, int) 11111 */ 11112 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 11113 int right, int bottom) { 11114 11115 // We try only with the AttachInfo because there's no point in invalidating 11116 // if we are not attached to our window 11117 final AttachInfo attachInfo = mAttachInfo; 11118 if (attachInfo != null) { 11119 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 11120 info.target = this; 11121 info.left = left; 11122 info.top = top; 11123 info.right = right; 11124 info.bottom = bottom; 11125 11126 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 11127 } 11128 } 11129 11130 /** 11131 * <p>Cause an invalidate to happen on the next animation time step, typically the 11132 * next display frame.</p> 11133 * 11134 * <p>This method can be invoked from outside of the UI thread 11135 * only when this View is attached to a window.</p> 11136 * 11137 * @see #invalidate() 11138 */ 11139 public void postInvalidateOnAnimation() { 11140 // We try only with the AttachInfo because there's no point in invalidating 11141 // if we are not attached to our window 11142 final AttachInfo attachInfo = mAttachInfo; 11143 if (attachInfo != null) { 11144 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 11145 } 11146 } 11147 11148 /** 11149 * <p>Cause an invalidate of the specified area to happen on the next animation 11150 * time step, typically the next display frame.</p> 11151 * 11152 * <p>This method can be invoked from outside of the UI thread 11153 * only when this View is attached to a window.</p> 11154 * 11155 * @param left The left coordinate of the rectangle to invalidate. 11156 * @param top The top coordinate of the rectangle to invalidate. 11157 * @param right The right coordinate of the rectangle to invalidate. 11158 * @param bottom The bottom coordinate of the rectangle to invalidate. 11159 * 11160 * @see #invalidate(int, int, int, int) 11161 * @see #invalidate(Rect) 11162 */ 11163 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 11164 // We try only with the AttachInfo because there's no point in invalidating 11165 // if we are not attached to our window 11166 final AttachInfo attachInfo = mAttachInfo; 11167 if (attachInfo != null) { 11168 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 11169 info.target = this; 11170 info.left = left; 11171 info.top = top; 11172 info.right = right; 11173 info.bottom = bottom; 11174 11175 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 11176 } 11177 } 11178 11179 /** 11180 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 11181 * This event is sent at most once every 11182 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 11183 */ 11184 private void postSendViewScrolledAccessibilityEventCallback() { 11185 if (mSendViewScrolledAccessibilityEvent == null) { 11186 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 11187 } 11188 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 11189 mSendViewScrolledAccessibilityEvent.mIsPending = true; 11190 postDelayed(mSendViewScrolledAccessibilityEvent, 11191 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 11192 } 11193 } 11194 11195 /** 11196 * Called by a parent to request that a child update its values for mScrollX 11197 * and mScrollY if necessary. This will typically be done if the child is 11198 * animating a scroll using a {@link android.widget.Scroller Scroller} 11199 * object. 11200 */ 11201 public void computeScroll() { 11202 } 11203 11204 /** 11205 * <p>Indicate whether the horizontal edges are faded when the view is 11206 * scrolled horizontally.</p> 11207 * 11208 * @return true if the horizontal edges should are faded on scroll, false 11209 * otherwise 11210 * 11211 * @see #setHorizontalFadingEdgeEnabled(boolean) 11212 * 11213 * @attr ref android.R.styleable#View_requiresFadingEdge 11214 */ 11215 public boolean isHorizontalFadingEdgeEnabled() { 11216 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 11217 } 11218 11219 /** 11220 * <p>Define whether the horizontal edges should be faded when this view 11221 * is scrolled horizontally.</p> 11222 * 11223 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 11224 * be faded when the view is scrolled 11225 * horizontally 11226 * 11227 * @see #isHorizontalFadingEdgeEnabled() 11228 * 11229 * @attr ref android.R.styleable#View_requiresFadingEdge 11230 */ 11231 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 11232 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 11233 if (horizontalFadingEdgeEnabled) { 11234 initScrollCache(); 11235 } 11236 11237 mViewFlags ^= FADING_EDGE_HORIZONTAL; 11238 } 11239 } 11240 11241 /** 11242 * <p>Indicate whether the vertical edges are faded when the view is 11243 * scrolled horizontally.</p> 11244 * 11245 * @return true if the vertical edges should are faded on scroll, false 11246 * otherwise 11247 * 11248 * @see #setVerticalFadingEdgeEnabled(boolean) 11249 * 11250 * @attr ref android.R.styleable#View_requiresFadingEdge 11251 */ 11252 public boolean isVerticalFadingEdgeEnabled() { 11253 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 11254 } 11255 11256 /** 11257 * <p>Define whether the vertical edges should be faded when this view 11258 * is scrolled vertically.</p> 11259 * 11260 * @param verticalFadingEdgeEnabled true if the vertical edges should 11261 * be faded when the view is scrolled 11262 * vertically 11263 * 11264 * @see #isVerticalFadingEdgeEnabled() 11265 * 11266 * @attr ref android.R.styleable#View_requiresFadingEdge 11267 */ 11268 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 11269 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 11270 if (verticalFadingEdgeEnabled) { 11271 initScrollCache(); 11272 } 11273 11274 mViewFlags ^= FADING_EDGE_VERTICAL; 11275 } 11276 } 11277 11278 /** 11279 * Returns the strength, or intensity, of the top faded edge. The strength is 11280 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11281 * returns 0.0 or 1.0 but no value in between. 11282 * 11283 * Subclasses should override this method to provide a smoother fade transition 11284 * when scrolling occurs. 11285 * 11286 * @return the intensity of the top fade as a float between 0.0f and 1.0f 11287 */ 11288 protected float getTopFadingEdgeStrength() { 11289 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 11290 } 11291 11292 /** 11293 * Returns the strength, or intensity, of the bottom faded edge. The strength is 11294 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11295 * returns 0.0 or 1.0 but no value in between. 11296 * 11297 * Subclasses should override this method to provide a smoother fade transition 11298 * when scrolling occurs. 11299 * 11300 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 11301 */ 11302 protected float getBottomFadingEdgeStrength() { 11303 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 11304 computeVerticalScrollRange() ? 1.0f : 0.0f; 11305 } 11306 11307 /** 11308 * Returns the strength, or intensity, of the left faded edge. The strength is 11309 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11310 * returns 0.0 or 1.0 but no value in between. 11311 * 11312 * Subclasses should override this method to provide a smoother fade transition 11313 * when scrolling occurs. 11314 * 11315 * @return the intensity of the left fade as a float between 0.0f and 1.0f 11316 */ 11317 protected float getLeftFadingEdgeStrength() { 11318 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 11319 } 11320 11321 /** 11322 * Returns the strength, or intensity, of the right faded edge. The strength is 11323 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11324 * returns 0.0 or 1.0 but no value in between. 11325 * 11326 * Subclasses should override this method to provide a smoother fade transition 11327 * when scrolling occurs. 11328 * 11329 * @return the intensity of the right fade as a float between 0.0f and 1.0f 11330 */ 11331 protected float getRightFadingEdgeStrength() { 11332 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 11333 computeHorizontalScrollRange() ? 1.0f : 0.0f; 11334 } 11335 11336 /** 11337 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 11338 * scrollbar is not drawn by default.</p> 11339 * 11340 * @return true if the horizontal scrollbar should be painted, false 11341 * otherwise 11342 * 11343 * @see #setHorizontalScrollBarEnabled(boolean) 11344 */ 11345 public boolean isHorizontalScrollBarEnabled() { 11346 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 11347 } 11348 11349 /** 11350 * <p>Define whether the horizontal scrollbar should be drawn or not. The 11351 * scrollbar is not drawn by default.</p> 11352 * 11353 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 11354 * be painted 11355 * 11356 * @see #isHorizontalScrollBarEnabled() 11357 */ 11358 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 11359 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 11360 mViewFlags ^= SCROLLBARS_HORIZONTAL; 11361 computeOpaqueFlags(); 11362 resolvePadding(); 11363 } 11364 } 11365 11366 /** 11367 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 11368 * scrollbar is not drawn by default.</p> 11369 * 11370 * @return true if the vertical scrollbar should be painted, false 11371 * otherwise 11372 * 11373 * @see #setVerticalScrollBarEnabled(boolean) 11374 */ 11375 public boolean isVerticalScrollBarEnabled() { 11376 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 11377 } 11378 11379 /** 11380 * <p>Define whether the vertical scrollbar should be drawn or not. The 11381 * scrollbar is not drawn by default.</p> 11382 * 11383 * @param verticalScrollBarEnabled true if the vertical scrollbar should 11384 * be painted 11385 * 11386 * @see #isVerticalScrollBarEnabled() 11387 */ 11388 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 11389 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 11390 mViewFlags ^= SCROLLBARS_VERTICAL; 11391 computeOpaqueFlags(); 11392 resolvePadding(); 11393 } 11394 } 11395 11396 /** 11397 * @hide 11398 */ 11399 protected void recomputePadding() { 11400 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 11401 } 11402 11403 /** 11404 * Define whether scrollbars will fade when the view is not scrolling. 11405 * 11406 * @param fadeScrollbars wheter to enable fading 11407 * 11408 * @attr ref android.R.styleable#View_fadeScrollbars 11409 */ 11410 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 11411 initScrollCache(); 11412 final ScrollabilityCache scrollabilityCache = mScrollCache; 11413 scrollabilityCache.fadeScrollBars = fadeScrollbars; 11414 if (fadeScrollbars) { 11415 scrollabilityCache.state = ScrollabilityCache.OFF; 11416 } else { 11417 scrollabilityCache.state = ScrollabilityCache.ON; 11418 } 11419 } 11420 11421 /** 11422 * 11423 * Returns true if scrollbars will fade when this view is not scrolling 11424 * 11425 * @return true if scrollbar fading is enabled 11426 * 11427 * @attr ref android.R.styleable#View_fadeScrollbars 11428 */ 11429 public boolean isScrollbarFadingEnabled() { 11430 return mScrollCache != null && mScrollCache.fadeScrollBars; 11431 } 11432 11433 /** 11434 * 11435 * Returns the delay before scrollbars fade. 11436 * 11437 * @return the delay before scrollbars fade 11438 * 11439 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 11440 */ 11441 public int getScrollBarDefaultDelayBeforeFade() { 11442 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 11443 mScrollCache.scrollBarDefaultDelayBeforeFade; 11444 } 11445 11446 /** 11447 * Define the delay before scrollbars fade. 11448 * 11449 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 11450 * 11451 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 11452 */ 11453 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 11454 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 11455 } 11456 11457 /** 11458 * 11459 * Returns the scrollbar fade duration. 11460 * 11461 * @return the scrollbar fade duration 11462 * 11463 * @attr ref android.R.styleable#View_scrollbarFadeDuration 11464 */ 11465 public int getScrollBarFadeDuration() { 11466 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 11467 mScrollCache.scrollBarFadeDuration; 11468 } 11469 11470 /** 11471 * Define the scrollbar fade duration. 11472 * 11473 * @param scrollBarFadeDuration - the scrollbar fade duration 11474 * 11475 * @attr ref android.R.styleable#View_scrollbarFadeDuration 11476 */ 11477 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 11478 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 11479 } 11480 11481 /** 11482 * 11483 * Returns the scrollbar size. 11484 * 11485 * @return the scrollbar size 11486 * 11487 * @attr ref android.R.styleable#View_scrollbarSize 11488 */ 11489 public int getScrollBarSize() { 11490 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 11491 mScrollCache.scrollBarSize; 11492 } 11493 11494 /** 11495 * Define the scrollbar size. 11496 * 11497 * @param scrollBarSize - the scrollbar size 11498 * 11499 * @attr ref android.R.styleable#View_scrollbarSize 11500 */ 11501 public void setScrollBarSize(int scrollBarSize) { 11502 getScrollCache().scrollBarSize = scrollBarSize; 11503 } 11504 11505 /** 11506 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 11507 * inset. When inset, they add to the padding of the view. And the scrollbars 11508 * can be drawn inside the padding area or on the edge of the view. For example, 11509 * if a view has a background drawable and you want to draw the scrollbars 11510 * inside the padding specified by the drawable, you can use 11511 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 11512 * appear at the edge of the view, ignoring the padding, then you can use 11513 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 11514 * @param style the style of the scrollbars. Should be one of 11515 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 11516 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 11517 * @see #SCROLLBARS_INSIDE_OVERLAY 11518 * @see #SCROLLBARS_INSIDE_INSET 11519 * @see #SCROLLBARS_OUTSIDE_OVERLAY 11520 * @see #SCROLLBARS_OUTSIDE_INSET 11521 * 11522 * @attr ref android.R.styleable#View_scrollbarStyle 11523 */ 11524 public void setScrollBarStyle(int style) { 11525 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 11526 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 11527 computeOpaqueFlags(); 11528 resolvePadding(); 11529 } 11530 } 11531 11532 /** 11533 * <p>Returns the current scrollbar style.</p> 11534 * @return the current scrollbar style 11535 * @see #SCROLLBARS_INSIDE_OVERLAY 11536 * @see #SCROLLBARS_INSIDE_INSET 11537 * @see #SCROLLBARS_OUTSIDE_OVERLAY 11538 * @see #SCROLLBARS_OUTSIDE_INSET 11539 * 11540 * @attr ref android.R.styleable#View_scrollbarStyle 11541 */ 11542 @ViewDebug.ExportedProperty(mapping = { 11543 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 11544 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 11545 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 11546 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 11547 }) 11548 public int getScrollBarStyle() { 11549 return mViewFlags & SCROLLBARS_STYLE_MASK; 11550 } 11551 11552 /** 11553 * <p>Compute the horizontal range that the horizontal scrollbar 11554 * represents.</p> 11555 * 11556 * <p>The range is expressed in arbitrary units that must be the same as the 11557 * units used by {@link #computeHorizontalScrollExtent()} and 11558 * {@link #computeHorizontalScrollOffset()}.</p> 11559 * 11560 * <p>The default range is the drawing width of this view.</p> 11561 * 11562 * @return the total horizontal range represented by the horizontal 11563 * scrollbar 11564 * 11565 * @see #computeHorizontalScrollExtent() 11566 * @see #computeHorizontalScrollOffset() 11567 * @see android.widget.ScrollBarDrawable 11568 */ 11569 protected int computeHorizontalScrollRange() { 11570 return getWidth(); 11571 } 11572 11573 /** 11574 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 11575 * within the horizontal range. This value is used to compute the position 11576 * of the thumb within the scrollbar's track.</p> 11577 * 11578 * <p>The range is expressed in arbitrary units that must be the same as the 11579 * units used by {@link #computeHorizontalScrollRange()} and 11580 * {@link #computeHorizontalScrollExtent()}.</p> 11581 * 11582 * <p>The default offset is the scroll offset of this view.</p> 11583 * 11584 * @return the horizontal offset of the scrollbar's thumb 11585 * 11586 * @see #computeHorizontalScrollRange() 11587 * @see #computeHorizontalScrollExtent() 11588 * @see android.widget.ScrollBarDrawable 11589 */ 11590 protected int computeHorizontalScrollOffset() { 11591 return mScrollX; 11592 } 11593 11594 /** 11595 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 11596 * within the horizontal range. This value is used to compute the length 11597 * of the thumb within the scrollbar's track.</p> 11598 * 11599 * <p>The range is expressed in arbitrary units that must be the same as the 11600 * units used by {@link #computeHorizontalScrollRange()} and 11601 * {@link #computeHorizontalScrollOffset()}.</p> 11602 * 11603 * <p>The default extent is the drawing width of this view.</p> 11604 * 11605 * @return the horizontal extent of the scrollbar's thumb 11606 * 11607 * @see #computeHorizontalScrollRange() 11608 * @see #computeHorizontalScrollOffset() 11609 * @see android.widget.ScrollBarDrawable 11610 */ 11611 protected int computeHorizontalScrollExtent() { 11612 return getWidth(); 11613 } 11614 11615 /** 11616 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 11617 * 11618 * <p>The range is expressed in arbitrary units that must be the same as the 11619 * units used by {@link #computeVerticalScrollExtent()} and 11620 * {@link #computeVerticalScrollOffset()}.</p> 11621 * 11622 * @return the total vertical range represented by the vertical scrollbar 11623 * 11624 * <p>The default range is the drawing height of this view.</p> 11625 * 11626 * @see #computeVerticalScrollExtent() 11627 * @see #computeVerticalScrollOffset() 11628 * @see android.widget.ScrollBarDrawable 11629 */ 11630 protected int computeVerticalScrollRange() { 11631 return getHeight(); 11632 } 11633 11634 /** 11635 * <p>Compute the vertical offset of the vertical scrollbar's thumb 11636 * within the horizontal range. This value is used to compute the position 11637 * of the thumb within the scrollbar's track.</p> 11638 * 11639 * <p>The range is expressed in arbitrary units that must be the same as the 11640 * units used by {@link #computeVerticalScrollRange()} and 11641 * {@link #computeVerticalScrollExtent()}.</p> 11642 * 11643 * <p>The default offset is the scroll offset of this view.</p> 11644 * 11645 * @return the vertical offset of the scrollbar's thumb 11646 * 11647 * @see #computeVerticalScrollRange() 11648 * @see #computeVerticalScrollExtent() 11649 * @see android.widget.ScrollBarDrawable 11650 */ 11651 protected int computeVerticalScrollOffset() { 11652 return mScrollY; 11653 } 11654 11655 /** 11656 * <p>Compute the vertical extent of the horizontal scrollbar's thumb 11657 * within the vertical range. This value is used to compute the length 11658 * of the thumb within the scrollbar's track.</p> 11659 * 11660 * <p>The range is expressed in arbitrary units that must be the same as the 11661 * units used by {@link #computeVerticalScrollRange()} and 11662 * {@link #computeVerticalScrollOffset()}.</p> 11663 * 11664 * <p>The default extent is the drawing height of this view.</p> 11665 * 11666 * @return the vertical extent of the scrollbar's thumb 11667 * 11668 * @see #computeVerticalScrollRange() 11669 * @see #computeVerticalScrollOffset() 11670 * @see android.widget.ScrollBarDrawable 11671 */ 11672 protected int computeVerticalScrollExtent() { 11673 return getHeight(); 11674 } 11675 11676 /** 11677 * Check if this view can be scrolled horizontally in a certain direction. 11678 * 11679 * @param direction Negative to check scrolling left, positive to check scrolling right. 11680 * @return true if this view can be scrolled in the specified direction, false otherwise. 11681 */ 11682 public boolean canScrollHorizontally(int direction) { 11683 final int offset = computeHorizontalScrollOffset(); 11684 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 11685 if (range == 0) return false; 11686 if (direction < 0) { 11687 return offset > 0; 11688 } else { 11689 return offset < range - 1; 11690 } 11691 } 11692 11693 /** 11694 * Check if this view can be scrolled vertically in a certain direction. 11695 * 11696 * @param direction Negative to check scrolling up, positive to check scrolling down. 11697 * @return true if this view can be scrolled in the specified direction, false otherwise. 11698 */ 11699 public boolean canScrollVertically(int direction) { 11700 final int offset = computeVerticalScrollOffset(); 11701 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 11702 if (range == 0) return false; 11703 if (direction < 0) { 11704 return offset > 0; 11705 } else { 11706 return offset < range - 1; 11707 } 11708 } 11709 11710 /** 11711 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 11712 * scrollbars are painted only if they have been awakened first.</p> 11713 * 11714 * @param canvas the canvas on which to draw the scrollbars 11715 * 11716 * @see #awakenScrollBars(int) 11717 */ 11718 protected final void onDrawScrollBars(Canvas canvas) { 11719 // scrollbars are drawn only when the animation is running 11720 final ScrollabilityCache cache = mScrollCache; 11721 if (cache != null) { 11722 11723 int state = cache.state; 11724 11725 if (state == ScrollabilityCache.OFF) { 11726 return; 11727 } 11728 11729 boolean invalidate = false; 11730 11731 if (state == ScrollabilityCache.FADING) { 11732 // We're fading -- get our fade interpolation 11733 if (cache.interpolatorValues == null) { 11734 cache.interpolatorValues = new float[1]; 11735 } 11736 11737 float[] values = cache.interpolatorValues; 11738 11739 // Stops the animation if we're done 11740 if (cache.scrollBarInterpolator.timeToValues(values) == 11741 Interpolator.Result.FREEZE_END) { 11742 cache.state = ScrollabilityCache.OFF; 11743 } else { 11744 cache.scrollBar.setAlpha(Math.round(values[0])); 11745 } 11746 11747 // This will make the scroll bars inval themselves after 11748 // drawing. We only want this when we're fading so that 11749 // we prevent excessive redraws 11750 invalidate = true; 11751 } else { 11752 // We're just on -- but we may have been fading before so 11753 // reset alpha 11754 cache.scrollBar.setAlpha(255); 11755 } 11756 11757 11758 final int viewFlags = mViewFlags; 11759 11760 final boolean drawHorizontalScrollBar = 11761 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 11762 final boolean drawVerticalScrollBar = 11763 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 11764 && !isVerticalScrollBarHidden(); 11765 11766 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 11767 final int width = mRight - mLeft; 11768 final int height = mBottom - mTop; 11769 11770 final ScrollBarDrawable scrollBar = cache.scrollBar; 11771 11772 final int scrollX = mScrollX; 11773 final int scrollY = mScrollY; 11774 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 11775 11776 int left; 11777 int top; 11778 int right; 11779 int bottom; 11780 11781 if (drawHorizontalScrollBar) { 11782 int size = scrollBar.getSize(false); 11783 if (size <= 0) { 11784 size = cache.scrollBarSize; 11785 } 11786 11787 scrollBar.setParameters(computeHorizontalScrollRange(), 11788 computeHorizontalScrollOffset(), 11789 computeHorizontalScrollExtent(), false); 11790 final int verticalScrollBarGap = drawVerticalScrollBar ? 11791 getVerticalScrollbarWidth() : 0; 11792 top = scrollY + height - size - (mUserPaddingBottom & inside); 11793 left = scrollX + (mPaddingLeft & inside); 11794 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 11795 bottom = top + size; 11796 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 11797 if (invalidate) { 11798 invalidate(left, top, right, bottom); 11799 } 11800 } 11801 11802 if (drawVerticalScrollBar) { 11803 int size = scrollBar.getSize(true); 11804 if (size <= 0) { 11805 size = cache.scrollBarSize; 11806 } 11807 11808 scrollBar.setParameters(computeVerticalScrollRange(), 11809 computeVerticalScrollOffset(), 11810 computeVerticalScrollExtent(), true); 11811 int verticalScrollbarPosition = mVerticalScrollbarPosition; 11812 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 11813 verticalScrollbarPosition = isLayoutRtl() ? 11814 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 11815 } 11816 switch (verticalScrollbarPosition) { 11817 default: 11818 case SCROLLBAR_POSITION_RIGHT: 11819 left = scrollX + width - size - (mUserPaddingRight & inside); 11820 break; 11821 case SCROLLBAR_POSITION_LEFT: 11822 left = scrollX + (mUserPaddingLeft & inside); 11823 break; 11824 } 11825 top = scrollY + (mPaddingTop & inside); 11826 right = left + size; 11827 bottom = scrollY + height - (mUserPaddingBottom & inside); 11828 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 11829 if (invalidate) { 11830 invalidate(left, top, right, bottom); 11831 } 11832 } 11833 } 11834 } 11835 } 11836 11837 /** 11838 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 11839 * FastScroller is visible. 11840 * @return whether to temporarily hide the vertical scrollbar 11841 * @hide 11842 */ 11843 protected boolean isVerticalScrollBarHidden() { 11844 return false; 11845 } 11846 11847 /** 11848 * <p>Draw the horizontal scrollbar if 11849 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 11850 * 11851 * @param canvas the canvas on which to draw the scrollbar 11852 * @param scrollBar the scrollbar's drawable 11853 * 11854 * @see #isHorizontalScrollBarEnabled() 11855 * @see #computeHorizontalScrollRange() 11856 * @see #computeHorizontalScrollExtent() 11857 * @see #computeHorizontalScrollOffset() 11858 * @see android.widget.ScrollBarDrawable 11859 * @hide 11860 */ 11861 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 11862 int l, int t, int r, int b) { 11863 scrollBar.setBounds(l, t, r, b); 11864 scrollBar.draw(canvas); 11865 } 11866 11867 /** 11868 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 11869 * returns true.</p> 11870 * 11871 * @param canvas the canvas on which to draw the scrollbar 11872 * @param scrollBar the scrollbar's drawable 11873 * 11874 * @see #isVerticalScrollBarEnabled() 11875 * @see #computeVerticalScrollRange() 11876 * @see #computeVerticalScrollExtent() 11877 * @see #computeVerticalScrollOffset() 11878 * @see android.widget.ScrollBarDrawable 11879 * @hide 11880 */ 11881 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 11882 int l, int t, int r, int b) { 11883 scrollBar.setBounds(l, t, r, b); 11884 scrollBar.draw(canvas); 11885 } 11886 11887 /** 11888 * Implement this to do your drawing. 11889 * 11890 * @param canvas the canvas on which the background will be drawn 11891 */ 11892 protected void onDraw(Canvas canvas) { 11893 } 11894 11895 /* 11896 * Caller is responsible for calling requestLayout if necessary. 11897 * (This allows addViewInLayout to not request a new layout.) 11898 */ 11899 void assignParent(ViewParent parent) { 11900 if (mParent == null) { 11901 mParent = parent; 11902 } else if (parent == null) { 11903 mParent = null; 11904 } else { 11905 throw new RuntimeException("view " + this + " being added, but" 11906 + " it already has a parent"); 11907 } 11908 } 11909 11910 /** 11911 * This is called when the view is attached to a window. At this point it 11912 * has a Surface and will start drawing. Note that this function is 11913 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 11914 * however it may be called any time before the first onDraw -- including 11915 * before or after {@link #onMeasure(int, int)}. 11916 * 11917 * @see #onDetachedFromWindow() 11918 */ 11919 protected void onAttachedToWindow() { 11920 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 11921 mParent.requestTransparentRegion(this); 11922 } 11923 11924 if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 11925 initialAwakenScrollBars(); 11926 mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 11927 } 11928 11929 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 11930 11931 jumpDrawablesToCurrentState(); 11932 11933 resetSubtreeAccessibilityStateChanged(); 11934 11935 if (isFocused()) { 11936 InputMethodManager imm = InputMethodManager.peekInstance(); 11937 imm.focusIn(this); 11938 } 11939 11940 if (mDisplayList != null) { 11941 mDisplayList.clearDirty(); 11942 } 11943 } 11944 11945 /** 11946 * Resolve all RTL related properties. 11947 * 11948 * @return true if resolution of RTL properties has been done 11949 * 11950 * @hide 11951 */ 11952 public boolean resolveRtlPropertiesIfNeeded() { 11953 if (!needRtlPropertiesResolution()) return false; 11954 11955 // Order is important here: LayoutDirection MUST be resolved first 11956 if (!isLayoutDirectionResolved()) { 11957 resolveLayoutDirection(); 11958 resolveLayoutParams(); 11959 } 11960 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 11961 if (!isTextDirectionResolved()) { 11962 resolveTextDirection(); 11963 } 11964 if (!isTextAlignmentResolved()) { 11965 resolveTextAlignment(); 11966 } 11967 if (!isPaddingResolved()) { 11968 resolvePadding(); 11969 } 11970 if (!isDrawablesResolved()) { 11971 resolveDrawables(); 11972 } 11973 onRtlPropertiesChanged(getLayoutDirection()); 11974 return true; 11975 } 11976 11977 /** 11978 * Reset resolution of all RTL related properties. 11979 * 11980 * @hide 11981 */ 11982 public void resetRtlProperties() { 11983 resetResolvedLayoutDirection(); 11984 resetResolvedTextDirection(); 11985 resetResolvedTextAlignment(); 11986 resetResolvedPadding(); 11987 resetResolvedDrawables(); 11988 } 11989 11990 /** 11991 * @see #onScreenStateChanged(int) 11992 */ 11993 void dispatchScreenStateChanged(int screenState) { 11994 onScreenStateChanged(screenState); 11995 } 11996 11997 /** 11998 * This method is called whenever the state of the screen this view is 11999 * attached to changes. A state change will usually occurs when the screen 12000 * turns on or off (whether it happens automatically or the user does it 12001 * manually.) 12002 * 12003 * @param screenState The new state of the screen. Can be either 12004 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 12005 */ 12006 public void onScreenStateChanged(int screenState) { 12007 } 12008 12009 /** 12010 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 12011 */ 12012 private boolean hasRtlSupport() { 12013 return mContext.getApplicationInfo().hasRtlSupport(); 12014 } 12015 12016 /** 12017 * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or 12018 * RTL not supported) 12019 */ 12020 private boolean isRtlCompatibilityMode() { 12021 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 12022 return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport(); 12023 } 12024 12025 /** 12026 * @return true if RTL properties need resolution. 12027 * 12028 */ 12029 private boolean needRtlPropertiesResolution() { 12030 return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED; 12031 } 12032 12033 /** 12034 * Called when any RTL property (layout direction or text direction or text alignment) has 12035 * been changed. 12036 * 12037 * Subclasses need to override this method to take care of cached information that depends on the 12038 * resolved layout direction, or to inform child views that inherit their layout direction. 12039 * 12040 * The default implementation does nothing. 12041 * 12042 * @param layoutDirection the direction of the layout 12043 * 12044 * @see #LAYOUT_DIRECTION_LTR 12045 * @see #LAYOUT_DIRECTION_RTL 12046 */ 12047 public void onRtlPropertiesChanged(int layoutDirection) { 12048 } 12049 12050 /** 12051 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 12052 * that the parent directionality can and will be resolved before its children. 12053 * 12054 * @return true if resolution has been done, false otherwise. 12055 * 12056 * @hide 12057 */ 12058 public boolean resolveLayoutDirection() { 12059 // Clear any previous layout direction resolution 12060 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 12061 12062 if (hasRtlSupport()) { 12063 // Set resolved depending on layout direction 12064 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 12065 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 12066 case LAYOUT_DIRECTION_INHERIT: 12067 // We cannot resolve yet. LTR is by default and let the resolution happen again 12068 // later to get the correct resolved value 12069 if (!canResolveLayoutDirection()) return false; 12070 12071 // Parent has not yet resolved, LTR is still the default 12072 try { 12073 if (!mParent.isLayoutDirectionResolved()) return false; 12074 12075 if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 12076 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12077 } 12078 } catch (AbstractMethodError e) { 12079 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 12080 " does not fully implement ViewParent", e); 12081 } 12082 break; 12083 case LAYOUT_DIRECTION_RTL: 12084 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12085 break; 12086 case LAYOUT_DIRECTION_LOCALE: 12087 if((LAYOUT_DIRECTION_RTL == 12088 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) { 12089 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12090 } 12091 break; 12092 default: 12093 // Nothing to do, LTR by default 12094 } 12095 } 12096 12097 // Set to resolved 12098 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 12099 return true; 12100 } 12101 12102 /** 12103 * Check if layout direction resolution can be done. 12104 * 12105 * @return true if layout direction resolution can be done otherwise return false. 12106 */ 12107 public boolean canResolveLayoutDirection() { 12108 switch (getRawLayoutDirection()) { 12109 case LAYOUT_DIRECTION_INHERIT: 12110 if (mParent != null) { 12111 try { 12112 return mParent.canResolveLayoutDirection(); 12113 } catch (AbstractMethodError e) { 12114 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 12115 " does not fully implement ViewParent", e); 12116 } 12117 } 12118 return false; 12119 12120 default: 12121 return true; 12122 } 12123 } 12124 12125 /** 12126 * Reset the resolved layout direction. Layout direction will be resolved during a call to 12127 * {@link #onMeasure(int, int)}. 12128 * 12129 * @hide 12130 */ 12131 public void resetResolvedLayoutDirection() { 12132 // Reset the current resolved bits 12133 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 12134 } 12135 12136 /** 12137 * @return true if the layout direction is inherited. 12138 * 12139 * @hide 12140 */ 12141 public boolean isLayoutDirectionInherited() { 12142 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT); 12143 } 12144 12145 /** 12146 * @return true if layout direction has been resolved. 12147 */ 12148 public boolean isLayoutDirectionResolved() { 12149 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED; 12150 } 12151 12152 /** 12153 * Return if padding has been resolved 12154 * 12155 * @hide 12156 */ 12157 boolean isPaddingResolved() { 12158 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED; 12159 } 12160 12161 /** 12162 * Resolves padding depending on layout direction, if applicable, and 12163 * recomputes internal padding values to adjust for scroll bars. 12164 * 12165 * @hide 12166 */ 12167 public void resolvePadding() { 12168 final int resolvedLayoutDirection = getLayoutDirection(); 12169 12170 if (!isRtlCompatibilityMode()) { 12171 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 12172 // If start / end padding are defined, they will be resolved (hence overriding) to 12173 // left / right or right / left depending on the resolved layout direction. 12174 // If start / end padding are not defined, use the left / right ones. 12175 switch (resolvedLayoutDirection) { 12176 case LAYOUT_DIRECTION_RTL: 12177 if (mUserPaddingStart != UNDEFINED_PADDING) { 12178 mUserPaddingRight = mUserPaddingStart; 12179 } else { 12180 mUserPaddingRight = mUserPaddingRightInitial; 12181 } 12182 if (mUserPaddingEnd != UNDEFINED_PADDING) { 12183 mUserPaddingLeft = mUserPaddingEnd; 12184 } else { 12185 mUserPaddingLeft = mUserPaddingLeftInitial; 12186 } 12187 break; 12188 case LAYOUT_DIRECTION_LTR: 12189 default: 12190 if (mUserPaddingStart != UNDEFINED_PADDING) { 12191 mUserPaddingLeft = mUserPaddingStart; 12192 } else { 12193 mUserPaddingLeft = mUserPaddingLeftInitial; 12194 } 12195 if (mUserPaddingEnd != UNDEFINED_PADDING) { 12196 mUserPaddingRight = mUserPaddingEnd; 12197 } else { 12198 mUserPaddingRight = mUserPaddingRightInitial; 12199 } 12200 } 12201 12202 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 12203 } 12204 12205 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 12206 onRtlPropertiesChanged(resolvedLayoutDirection); 12207 12208 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 12209 } 12210 12211 /** 12212 * Reset the resolved layout direction. 12213 * 12214 * @hide 12215 */ 12216 public void resetResolvedPadding() { 12217 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 12218 } 12219 12220 /** 12221 * This is called when the view is detached from a window. At this point it 12222 * no longer has a surface for drawing. 12223 * 12224 * @see #onAttachedToWindow() 12225 */ 12226 protected void onDetachedFromWindow() { 12227 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 12228 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 12229 12230 removeUnsetPressCallback(); 12231 removeLongPressCallback(); 12232 removePerformClickCallback(); 12233 removeSendViewScrolledAccessibilityEventCallback(); 12234 12235 destroyDrawingCache(); 12236 destroyLayer(false); 12237 12238 cleanupDraw(); 12239 12240 mCurrentAnimation = null; 12241 } 12242 12243 private void cleanupDraw() { 12244 if (mAttachInfo != null) { 12245 if (mDisplayList != null) { 12246 mDisplayList.markDirty(); 12247 mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList); 12248 } 12249 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 12250 } else { 12251 // Should never happen 12252 resetDisplayList(); 12253 } 12254 } 12255 12256 void invalidateInheritedLayoutMode(int layoutModeOfRoot) { 12257 } 12258 12259 /** 12260 * @return The number of times this view has been attached to a window 12261 */ 12262 protected int getWindowAttachCount() { 12263 return mWindowAttachCount; 12264 } 12265 12266 /** 12267 * Retrieve a unique token identifying the window this view is attached to. 12268 * @return Return the window's token for use in 12269 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 12270 */ 12271 public IBinder getWindowToken() { 12272 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 12273 } 12274 12275 /** 12276 * Retrieve the {@link WindowId} for the window this view is 12277 * currently attached to. 12278 */ 12279 public WindowId getWindowId() { 12280 if (mAttachInfo == null) { 12281 return null; 12282 } 12283 if (mAttachInfo.mWindowId == null) { 12284 try { 12285 mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId( 12286 mAttachInfo.mWindowToken); 12287 mAttachInfo.mWindowId = new WindowId( 12288 mAttachInfo.mIWindowId); 12289 } catch (RemoteException e) { 12290 } 12291 } 12292 return mAttachInfo.mWindowId; 12293 } 12294 12295 /** 12296 * Retrieve a unique token identifying the top-level "real" window of 12297 * the window that this view is attached to. That is, this is like 12298 * {@link #getWindowToken}, except if the window this view in is a panel 12299 * window (attached to another containing window), then the token of 12300 * the containing window is returned instead. 12301 * 12302 * @return Returns the associated window token, either 12303 * {@link #getWindowToken()} or the containing window's token. 12304 */ 12305 public IBinder getApplicationWindowToken() { 12306 AttachInfo ai = mAttachInfo; 12307 if (ai != null) { 12308 IBinder appWindowToken = ai.mPanelParentWindowToken; 12309 if (appWindowToken == null) { 12310 appWindowToken = ai.mWindowToken; 12311 } 12312 return appWindowToken; 12313 } 12314 return null; 12315 } 12316 12317 /** 12318 * Gets the logical display to which the view's window has been attached. 12319 * 12320 * @return The logical display, or null if the view is not currently attached to a window. 12321 */ 12322 public Display getDisplay() { 12323 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 12324 } 12325 12326 /** 12327 * Retrieve private session object this view hierarchy is using to 12328 * communicate with the window manager. 12329 * @return the session object to communicate with the window manager 12330 */ 12331 /*package*/ IWindowSession getWindowSession() { 12332 return mAttachInfo != null ? mAttachInfo.mSession : null; 12333 } 12334 12335 /** 12336 * @param info the {@link android.view.View.AttachInfo} to associated with 12337 * this view 12338 */ 12339 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 12340 //System.out.println("Attached! " + this); 12341 mAttachInfo = info; 12342 if (mOverlay != null) { 12343 mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility); 12344 } 12345 mWindowAttachCount++; 12346 // We will need to evaluate the drawable state at least once. 12347 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 12348 if (mFloatingTreeObserver != null) { 12349 info.mTreeObserver.merge(mFloatingTreeObserver); 12350 mFloatingTreeObserver = null; 12351 } 12352 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 12353 mAttachInfo.mScrollContainers.add(this); 12354 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 12355 } 12356 performCollectViewAttributes(mAttachInfo, visibility); 12357 onAttachedToWindow(); 12358 12359 ListenerInfo li = mListenerInfo; 12360 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 12361 li != null ? li.mOnAttachStateChangeListeners : null; 12362 if (listeners != null && listeners.size() > 0) { 12363 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 12364 // perform the dispatching. The iterator is a safe guard against listeners that 12365 // could mutate the list by calling the various add/remove methods. This prevents 12366 // the array from being modified while we iterate it. 12367 for (OnAttachStateChangeListener listener : listeners) { 12368 listener.onViewAttachedToWindow(this); 12369 } 12370 } 12371 12372 int vis = info.mWindowVisibility; 12373 if (vis != GONE) { 12374 onWindowVisibilityChanged(vis); 12375 } 12376 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 12377 // If nobody has evaluated the drawable state yet, then do it now. 12378 refreshDrawableState(); 12379 } 12380 needGlobalAttributesUpdate(false); 12381 } 12382 12383 void dispatchDetachedFromWindow() { 12384 AttachInfo info = mAttachInfo; 12385 if (info != null) { 12386 int vis = info.mWindowVisibility; 12387 if (vis != GONE) { 12388 onWindowVisibilityChanged(GONE); 12389 } 12390 } 12391 12392 onDetachedFromWindow(); 12393 12394 ListenerInfo li = mListenerInfo; 12395 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 12396 li != null ? li.mOnAttachStateChangeListeners : null; 12397 if (listeners != null && listeners.size() > 0) { 12398 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 12399 // perform the dispatching. The iterator is a safe guard against listeners that 12400 // could mutate the list by calling the various add/remove methods. This prevents 12401 // the array from being modified while we iterate it. 12402 for (OnAttachStateChangeListener listener : listeners) { 12403 listener.onViewDetachedFromWindow(this); 12404 } 12405 } 12406 12407 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 12408 mAttachInfo.mScrollContainers.remove(this); 12409 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 12410 } 12411 12412 mAttachInfo = null; 12413 if (mOverlay != null) { 12414 mOverlay.getOverlayView().dispatchDetachedFromWindow(); 12415 } 12416 } 12417 12418 /** 12419 * Cancel any deferred high-level input events that were previously posted to the event queue. 12420 * 12421 * <p>Many views post high-level events such as click handlers to the event queue 12422 * to run deferred in order to preserve a desired user experience - clearing visible 12423 * pressed states before executing, etc. This method will abort any events of this nature 12424 * that are currently in flight.</p> 12425 * 12426 * <p>Custom views that generate their own high-level deferred input events should override 12427 * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p> 12428 * 12429 * <p>This will also cancel pending input events for any child views.</p> 12430 * 12431 * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases. 12432 * This will not impact newer events posted after this call that may occur as a result of 12433 * lower-level input events still waiting in the queue. If you are trying to prevent 12434 * double-submitted events for the duration of some sort of asynchronous transaction 12435 * you should also take other steps to protect against unexpected double inputs e.g. calling 12436 * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when 12437 * the transaction completes, tracking already submitted transaction IDs, etc.</p> 12438 */ 12439 public final void cancelPendingInputEvents() { 12440 dispatchCancelPendingInputEvents(); 12441 } 12442 12443 /** 12444 * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight. 12445 * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling. 12446 */ 12447 void dispatchCancelPendingInputEvents() { 12448 mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER; 12449 onCancelPendingInputEvents(); 12450 if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) { 12451 throw new SuperNotCalledException("View " + getClass().getSimpleName() + 12452 " did not call through to super.onCancelPendingInputEvents()"); 12453 } 12454 } 12455 12456 /** 12457 * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or 12458 * a parent view. 12459 * 12460 * <p>This method is responsible for removing any pending high-level input events that were 12461 * posted to the event queue to run later. Custom view classes that post their own deferred 12462 * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or 12463 * {@link android.os.Handler} should override this method, call 12464 * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate. 12465 * </p> 12466 */ 12467 public void onCancelPendingInputEvents() { 12468 removePerformClickCallback(); 12469 cancelLongPress(); 12470 mPrivateFlags3 |= PFLAG3_CALLED_SUPER; 12471 } 12472 12473 /** 12474 * Store this view hierarchy's frozen state into the given container. 12475 * 12476 * @param container The SparseArray in which to save the view's state. 12477 * 12478 * @see #restoreHierarchyState(android.util.SparseArray) 12479 * @see #dispatchSaveInstanceState(android.util.SparseArray) 12480 * @see #onSaveInstanceState() 12481 */ 12482 public void saveHierarchyState(SparseArray<Parcelable> container) { 12483 dispatchSaveInstanceState(container); 12484 } 12485 12486 /** 12487 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 12488 * this view and its children. May be overridden to modify how freezing happens to a 12489 * view's children; for example, some views may want to not store state for their children. 12490 * 12491 * @param container The SparseArray in which to save the view's state. 12492 * 12493 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 12494 * @see #saveHierarchyState(android.util.SparseArray) 12495 * @see #onSaveInstanceState() 12496 */ 12497 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 12498 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 12499 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 12500 Parcelable state = onSaveInstanceState(); 12501 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 12502 throw new IllegalStateException( 12503 "Derived class did not call super.onSaveInstanceState()"); 12504 } 12505 if (state != null) { 12506 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 12507 // + ": " + state); 12508 container.put(mID, state); 12509 } 12510 } 12511 } 12512 12513 /** 12514 * Hook allowing a view to generate a representation of its internal state 12515 * that can later be used to create a new instance with that same state. 12516 * This state should only contain information that is not persistent or can 12517 * not be reconstructed later. For example, you will never store your 12518 * current position on screen because that will be computed again when a 12519 * new instance of the view is placed in its view hierarchy. 12520 * <p> 12521 * Some examples of things you may store here: the current cursor position 12522 * in a text view (but usually not the text itself since that is stored in a 12523 * content provider or other persistent storage), the currently selected 12524 * item in a list view. 12525 * 12526 * @return Returns a Parcelable object containing the view's current dynamic 12527 * state, or null if there is nothing interesting to save. The 12528 * default implementation returns null. 12529 * @see #onRestoreInstanceState(android.os.Parcelable) 12530 * @see #saveHierarchyState(android.util.SparseArray) 12531 * @see #dispatchSaveInstanceState(android.util.SparseArray) 12532 * @see #setSaveEnabled(boolean) 12533 */ 12534 protected Parcelable onSaveInstanceState() { 12535 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 12536 return BaseSavedState.EMPTY_STATE; 12537 } 12538 12539 /** 12540 * Restore this view hierarchy's frozen state from the given container. 12541 * 12542 * @param container The SparseArray which holds previously frozen states. 12543 * 12544 * @see #saveHierarchyState(android.util.SparseArray) 12545 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 12546 * @see #onRestoreInstanceState(android.os.Parcelable) 12547 */ 12548 public void restoreHierarchyState(SparseArray<Parcelable> container) { 12549 dispatchRestoreInstanceState(container); 12550 } 12551 12552 /** 12553 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 12554 * state for this view and its children. May be overridden to modify how restoring 12555 * happens to a view's children; for example, some views may want to not store state 12556 * for their children. 12557 * 12558 * @param container The SparseArray which holds previously saved state. 12559 * 12560 * @see #dispatchSaveInstanceState(android.util.SparseArray) 12561 * @see #restoreHierarchyState(android.util.SparseArray) 12562 * @see #onRestoreInstanceState(android.os.Parcelable) 12563 */ 12564 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 12565 if (mID != NO_ID) { 12566 Parcelable state = container.get(mID); 12567 if (state != null) { 12568 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 12569 // + ": " + state); 12570 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 12571 onRestoreInstanceState(state); 12572 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 12573 throw new IllegalStateException( 12574 "Derived class did not call super.onRestoreInstanceState()"); 12575 } 12576 } 12577 } 12578 } 12579 12580 /** 12581 * Hook allowing a view to re-apply a representation of its internal state that had previously 12582 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 12583 * null state. 12584 * 12585 * @param state The frozen state that had previously been returned by 12586 * {@link #onSaveInstanceState}. 12587 * 12588 * @see #onSaveInstanceState() 12589 * @see #restoreHierarchyState(android.util.SparseArray) 12590 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 12591 */ 12592 protected void onRestoreInstanceState(Parcelable state) { 12593 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 12594 if (state != BaseSavedState.EMPTY_STATE && state != null) { 12595 throw new IllegalArgumentException("Wrong state class, expecting View State but " 12596 + "received " + state.getClass().toString() + " instead. This usually happens " 12597 + "when two views of different type have the same id in the same hierarchy. " 12598 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 12599 + "other views do not use the same id."); 12600 } 12601 } 12602 12603 /** 12604 * <p>Return the time at which the drawing of the view hierarchy started.</p> 12605 * 12606 * @return the drawing start time in milliseconds 12607 */ 12608 public long getDrawingTime() { 12609 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 12610 } 12611 12612 /** 12613 * <p>Enables or disables the duplication of the parent's state into this view. When 12614 * duplication is enabled, this view gets its drawable state from its parent rather 12615 * than from its own internal properties.</p> 12616 * 12617 * <p>Note: in the current implementation, setting this property to true after the 12618 * view was added to a ViewGroup might have no effect at all. This property should 12619 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 12620 * 12621 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 12622 * property is enabled, an exception will be thrown.</p> 12623 * 12624 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 12625 * parent, these states should not be affected by this method.</p> 12626 * 12627 * @param enabled True to enable duplication of the parent's drawable state, false 12628 * to disable it. 12629 * 12630 * @see #getDrawableState() 12631 * @see #isDuplicateParentStateEnabled() 12632 */ 12633 public void setDuplicateParentStateEnabled(boolean enabled) { 12634 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 12635 } 12636 12637 /** 12638 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 12639 * 12640 * @return True if this view's drawable state is duplicated from the parent, 12641 * false otherwise 12642 * 12643 * @see #getDrawableState() 12644 * @see #setDuplicateParentStateEnabled(boolean) 12645 */ 12646 public boolean isDuplicateParentStateEnabled() { 12647 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 12648 } 12649 12650 /** 12651 * <p>Specifies the type of layer backing this view. The layer can be 12652 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 12653 * {@link #LAYER_TYPE_HARDWARE}.</p> 12654 * 12655 * <p>A layer is associated with an optional {@link android.graphics.Paint} 12656 * instance that controls how the layer is composed on screen. The following 12657 * properties of the paint are taken into account when composing the layer:</p> 12658 * <ul> 12659 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 12660 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 12661 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 12662 * </ul> 12663 * 12664 * <p>If this view has an alpha value set to < 1.0 by calling 12665 * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded 12666 * by this view's alpha value.</p> 12667 * 12668 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE}, 12669 * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE} 12670 * for more information on when and how to use layers.</p> 12671 * 12672 * @param layerType The type of layer to use with this view, must be one of 12673 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 12674 * {@link #LAYER_TYPE_HARDWARE} 12675 * @param paint The paint used to compose the layer. This argument is optional 12676 * and can be null. It is ignored when the layer type is 12677 * {@link #LAYER_TYPE_NONE} 12678 * 12679 * @see #getLayerType() 12680 * @see #LAYER_TYPE_NONE 12681 * @see #LAYER_TYPE_SOFTWARE 12682 * @see #LAYER_TYPE_HARDWARE 12683 * @see #setAlpha(float) 12684 * 12685 * @attr ref android.R.styleable#View_layerType 12686 */ 12687 public void setLayerType(int layerType, Paint paint) { 12688 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 12689 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 12690 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 12691 } 12692 12693 if (layerType == mLayerType) { 12694 if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) { 12695 mLayerPaint = paint == null ? new Paint() : paint; 12696 invalidateParentCaches(); 12697 invalidate(true); 12698 } 12699 return; 12700 } 12701 12702 // Destroy any previous software drawing cache if needed 12703 switch (mLayerType) { 12704 case LAYER_TYPE_HARDWARE: 12705 destroyLayer(false); 12706 // fall through - non-accelerated views may use software layer mechanism instead 12707 case LAYER_TYPE_SOFTWARE: 12708 destroyDrawingCache(); 12709 break; 12710 default: 12711 break; 12712 } 12713 12714 mLayerType = layerType; 12715 final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE; 12716 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 12717 mLocalDirtyRect = layerDisabled ? null : new Rect(); 12718 12719 invalidateParentCaches(); 12720 invalidate(true); 12721 } 12722 12723 /** 12724 * Updates the {@link Paint} object used with the current layer (used only if the current 12725 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 12726 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 12727 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 12728 * ensure that the view gets redrawn immediately. 12729 * 12730 * <p>A layer is associated with an optional {@link android.graphics.Paint} 12731 * instance that controls how the layer is composed on screen. The following 12732 * properties of the paint are taken into account when composing the layer:</p> 12733 * <ul> 12734 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 12735 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 12736 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 12737 * </ul> 12738 * 12739 * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the 12740 * alpha value of the layer's paint is superceded by this view's alpha value.</p> 12741 * 12742 * @param paint The paint used to compose the layer. This argument is optional 12743 * and can be null. It is ignored when the layer type is 12744 * {@link #LAYER_TYPE_NONE} 12745 * 12746 * @see #setLayerType(int, android.graphics.Paint) 12747 */ 12748 public void setLayerPaint(Paint paint) { 12749 int layerType = getLayerType(); 12750 if (layerType != LAYER_TYPE_NONE) { 12751 mLayerPaint = paint == null ? new Paint() : paint; 12752 if (layerType == LAYER_TYPE_HARDWARE) { 12753 HardwareLayer layer = getHardwareLayer(); 12754 if (layer != null) { 12755 layer.setLayerPaint(paint); 12756 } 12757 invalidateViewProperty(false, false); 12758 } else { 12759 invalidate(); 12760 } 12761 } 12762 } 12763 12764 /** 12765 * Indicates whether this view has a static layer. A view with layer type 12766 * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are 12767 * dynamic. 12768 */ 12769 boolean hasStaticLayer() { 12770 return true; 12771 } 12772 12773 /** 12774 * Indicates what type of layer is currently associated with this view. By default 12775 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 12776 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 12777 * for more information on the different types of layers. 12778 * 12779 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 12780 * {@link #LAYER_TYPE_HARDWARE} 12781 * 12782 * @see #setLayerType(int, android.graphics.Paint) 12783 * @see #buildLayer() 12784 * @see #LAYER_TYPE_NONE 12785 * @see #LAYER_TYPE_SOFTWARE 12786 * @see #LAYER_TYPE_HARDWARE 12787 */ 12788 public int getLayerType() { 12789 return mLayerType; 12790 } 12791 12792 /** 12793 * Forces this view's layer to be created and this view to be rendered 12794 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 12795 * invoking this method will have no effect. 12796 * 12797 * This method can for instance be used to render a view into its layer before 12798 * starting an animation. If this view is complex, rendering into the layer 12799 * before starting the animation will avoid skipping frames. 12800 * 12801 * @throws IllegalStateException If this view is not attached to a window 12802 * 12803 * @see #setLayerType(int, android.graphics.Paint) 12804 */ 12805 public void buildLayer() { 12806 if (mLayerType == LAYER_TYPE_NONE) return; 12807 12808 final AttachInfo attachInfo = mAttachInfo; 12809 if (attachInfo == null) { 12810 throw new IllegalStateException("This view must be attached to a window first"); 12811 } 12812 12813 switch (mLayerType) { 12814 case LAYER_TYPE_HARDWARE: 12815 if (attachInfo.mHardwareRenderer != null && 12816 attachInfo.mHardwareRenderer.isEnabled() && 12817 attachInfo.mHardwareRenderer.validate()) { 12818 getHardwareLayer(); 12819 // TODO: We need a better way to handle this case 12820 // If views have registered pre-draw listeners they need 12821 // to be notified before we build the layer. Those listeners 12822 // may however rely on other events to happen first so we 12823 // cannot just invoke them here until they don't cancel the 12824 // current frame 12825 if (!attachInfo.mTreeObserver.hasOnPreDrawListeners()) { 12826 attachInfo.mViewRootImpl.dispatchFlushHardwareLayerUpdates(); 12827 } 12828 } 12829 break; 12830 case LAYER_TYPE_SOFTWARE: 12831 buildDrawingCache(true); 12832 break; 12833 } 12834 } 12835 12836 /** 12837 * <p>Returns a hardware layer that can be used to draw this view again 12838 * without executing its draw method.</p> 12839 * 12840 * @return A HardwareLayer ready to render, or null if an error occurred. 12841 */ 12842 HardwareLayer getHardwareLayer() { 12843 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null || 12844 !mAttachInfo.mHardwareRenderer.isEnabled()) { 12845 return null; 12846 } 12847 12848 if (!mAttachInfo.mHardwareRenderer.validate()) return null; 12849 12850 final int width = mRight - mLeft; 12851 final int height = mBottom - mTop; 12852 12853 if (width == 0 || height == 0) { 12854 return null; 12855 } 12856 12857 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) { 12858 if (mHardwareLayer == null) { 12859 mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer( 12860 width, height, isOpaque()); 12861 mLocalDirtyRect.set(0, 0, width, height); 12862 } else { 12863 if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) { 12864 if (mHardwareLayer.resize(width, height)) { 12865 mLocalDirtyRect.set(0, 0, width, height); 12866 } 12867 } 12868 12869 // This should not be necessary but applications that change 12870 // the parameters of their background drawable without calling 12871 // this.setBackground(Drawable) can leave the view in a bad state 12872 // (for instance isOpaque() returns true, but the background is 12873 // not opaque.) 12874 computeOpaqueFlags(); 12875 12876 final boolean opaque = isOpaque(); 12877 if (mHardwareLayer.isValid() && mHardwareLayer.isOpaque() != opaque) { 12878 mHardwareLayer.setOpaque(opaque); 12879 mLocalDirtyRect.set(0, 0, width, height); 12880 } 12881 } 12882 12883 // The layer is not valid if the underlying GPU resources cannot be allocated 12884 if (!mHardwareLayer.isValid()) { 12885 return null; 12886 } 12887 12888 mHardwareLayer.setLayerPaint(mLayerPaint); 12889 mHardwareLayer.redrawLater(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect); 12890 ViewRootImpl viewRoot = getViewRootImpl(); 12891 if (viewRoot != null) viewRoot.pushHardwareLayerUpdate(mHardwareLayer); 12892 12893 mLocalDirtyRect.setEmpty(); 12894 } 12895 12896 return mHardwareLayer; 12897 } 12898 12899 /** 12900 * Destroys this View's hardware layer if possible. 12901 * 12902 * @return True if the layer was destroyed, false otherwise. 12903 * 12904 * @see #setLayerType(int, android.graphics.Paint) 12905 * @see #LAYER_TYPE_HARDWARE 12906 */ 12907 boolean destroyLayer(boolean valid) { 12908 if (mHardwareLayer != null) { 12909 AttachInfo info = mAttachInfo; 12910 if (info != null && info.mHardwareRenderer != null && 12911 info.mHardwareRenderer.isEnabled() && 12912 (valid || info.mHardwareRenderer.validate())) { 12913 12914 info.mHardwareRenderer.cancelLayerUpdate(mHardwareLayer); 12915 mHardwareLayer.destroy(); 12916 mHardwareLayer = null; 12917 12918 invalidate(true); 12919 invalidateParentCaches(); 12920 } 12921 return true; 12922 } 12923 return false; 12924 } 12925 12926 /** 12927 * Destroys all hardware rendering resources. This method is invoked 12928 * when the system needs to reclaim resources. Upon execution of this 12929 * method, you should free any OpenGL resources created by the view. 12930 * 12931 * Note: you <strong>must</strong> call 12932 * <code>super.destroyHardwareResources()</code> when overriding 12933 * this method. 12934 * 12935 * @hide 12936 */ 12937 protected void destroyHardwareResources() { 12938 resetDisplayList(); 12939 destroyLayer(true); 12940 } 12941 12942 /** 12943 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 12944 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 12945 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 12946 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 12947 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 12948 * null.</p> 12949 * 12950 * <p>Enabling the drawing cache is similar to 12951 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 12952 * acceleration is turned off. When hardware acceleration is turned on, enabling the 12953 * drawing cache has no effect on rendering because the system uses a different mechanism 12954 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 12955 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 12956 * for information on how to enable software and hardware layers.</p> 12957 * 12958 * <p>This API can be used to manually generate 12959 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 12960 * {@link #getDrawingCache()}.</p> 12961 * 12962 * @param enabled true to enable the drawing cache, false otherwise 12963 * 12964 * @see #isDrawingCacheEnabled() 12965 * @see #getDrawingCache() 12966 * @see #buildDrawingCache() 12967 * @see #setLayerType(int, android.graphics.Paint) 12968 */ 12969 public void setDrawingCacheEnabled(boolean enabled) { 12970 mCachingFailed = false; 12971 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 12972 } 12973 12974 /** 12975 * <p>Indicates whether the drawing cache is enabled for this view.</p> 12976 * 12977 * @return true if the drawing cache is enabled 12978 * 12979 * @see #setDrawingCacheEnabled(boolean) 12980 * @see #getDrawingCache() 12981 */ 12982 @ViewDebug.ExportedProperty(category = "drawing") 12983 public boolean isDrawingCacheEnabled() { 12984 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 12985 } 12986 12987 /** 12988 * Debugging utility which recursively outputs the dirty state of a view and its 12989 * descendants. 12990 * 12991 * @hide 12992 */ 12993 @SuppressWarnings({"UnusedDeclaration"}) 12994 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 12995 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 12996 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 12997 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 12998 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 12999 if (clear) { 13000 mPrivateFlags &= clearMask; 13001 } 13002 if (this instanceof ViewGroup) { 13003 ViewGroup parent = (ViewGroup) this; 13004 final int count = parent.getChildCount(); 13005 for (int i = 0; i < count; i++) { 13006 final View child = parent.getChildAt(i); 13007 child.outputDirtyFlags(indent + " ", clear, clearMask); 13008 } 13009 } 13010 } 13011 13012 /** 13013 * This method is used by ViewGroup to cause its children to restore or recreate their 13014 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 13015 * to recreate its own display list, which would happen if it went through the normal 13016 * draw/dispatchDraw mechanisms. 13017 * 13018 * @hide 13019 */ 13020 protected void dispatchGetDisplayList() {} 13021 13022 /** 13023 * A view that is not attached or hardware accelerated cannot create a display list. 13024 * This method checks these conditions and returns the appropriate result. 13025 * 13026 * @return true if view has the ability to create a display list, false otherwise. 13027 * 13028 * @hide 13029 */ 13030 public boolean canHaveDisplayList() { 13031 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 13032 } 13033 13034 /** 13035 * @return The {@link HardwareRenderer} associated with that view or null if 13036 * hardware rendering is not supported or this view is not attached 13037 * to a window. 13038 * 13039 * @hide 13040 */ 13041 public HardwareRenderer getHardwareRenderer() { 13042 if (mAttachInfo != null) { 13043 return mAttachInfo.mHardwareRenderer; 13044 } 13045 return null; 13046 } 13047 13048 /** 13049 * Returns a DisplayList. If the incoming displayList is null, one will be created. 13050 * Otherwise, the same display list will be returned (after having been rendered into 13051 * along the way, depending on the invalidation state of the view). 13052 * 13053 * @param displayList The previous version of this displayList, could be null. 13054 * @param isLayer Whether the requester of the display list is a layer. If so, 13055 * the view will avoid creating a layer inside the resulting display list. 13056 * @return A new or reused DisplayList object. 13057 */ 13058 private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) { 13059 if (!canHaveDisplayList()) { 13060 return null; 13061 } 13062 13063 if (((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || 13064 displayList == null || !displayList.isValid() || 13065 (!isLayer && mRecreateDisplayList))) { 13066 // Don't need to recreate the display list, just need to tell our 13067 // children to restore/recreate theirs 13068 if (displayList != null && displayList.isValid() && 13069 !isLayer && !mRecreateDisplayList) { 13070 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13071 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13072 dispatchGetDisplayList(); 13073 13074 return displayList; 13075 } 13076 13077 if (!isLayer) { 13078 // If we got here, we're recreating it. Mark it as such to ensure that 13079 // we copy in child display lists into ours in drawChild() 13080 mRecreateDisplayList = true; 13081 } 13082 if (displayList == null) { 13083 displayList = mAttachInfo.mHardwareRenderer.createDisplayList(getClass().getName()); 13084 // If we're creating a new display list, make sure our parent gets invalidated 13085 // since they will need to recreate their display list to account for this 13086 // new child display list. 13087 invalidateParentCaches(); 13088 } 13089 13090 boolean caching = false; 13091 int width = mRight - mLeft; 13092 int height = mBottom - mTop; 13093 int layerType = getLayerType(); 13094 13095 final HardwareCanvas canvas = displayList.start(width, height); 13096 13097 try { 13098 if (!isLayer && layerType != LAYER_TYPE_NONE) { 13099 if (layerType == LAYER_TYPE_HARDWARE) { 13100 final HardwareLayer layer = getHardwareLayer(); 13101 if (layer != null && layer.isValid()) { 13102 canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint); 13103 } else { 13104 canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint, 13105 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | 13106 Canvas.CLIP_TO_LAYER_SAVE_FLAG); 13107 } 13108 caching = true; 13109 } else { 13110 buildDrawingCache(true); 13111 Bitmap cache = getDrawingCache(true); 13112 if (cache != null) { 13113 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 13114 caching = true; 13115 } 13116 } 13117 } else { 13118 13119 computeScroll(); 13120 13121 canvas.translate(-mScrollX, -mScrollY); 13122 if (!isLayer) { 13123 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13124 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13125 } 13126 13127 // Fast path for layouts with no backgrounds 13128 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 13129 dispatchDraw(canvas); 13130 if (mOverlay != null && !mOverlay.isEmpty()) { 13131 mOverlay.getOverlayView().draw(canvas); 13132 } 13133 } else { 13134 draw(canvas); 13135 } 13136 } 13137 } finally { 13138 displayList.end(); 13139 displayList.setCaching(caching); 13140 if (isLayer) { 13141 displayList.setLeftTopRightBottom(0, 0, width, height); 13142 } else { 13143 setDisplayListProperties(displayList); 13144 } 13145 } 13146 } else if (!isLayer) { 13147 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13148 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13149 } 13150 13151 return displayList; 13152 } 13153 13154 /** 13155 * Get the DisplayList for the HardwareLayer 13156 * 13157 * @param layer The HardwareLayer whose DisplayList we want 13158 * @return A DisplayList fopr the specified HardwareLayer 13159 */ 13160 private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) { 13161 DisplayList displayList = getDisplayList(layer.getDisplayList(), true); 13162 layer.setDisplayList(displayList); 13163 return displayList; 13164 } 13165 13166 13167 /** 13168 * <p>Returns a display list that can be used to draw this view again 13169 * without executing its draw method.</p> 13170 * 13171 * @return A DisplayList ready to replay, or null if caching is not enabled. 13172 * 13173 * @hide 13174 */ 13175 public DisplayList getDisplayList() { 13176 mDisplayList = getDisplayList(mDisplayList, false); 13177 return mDisplayList; 13178 } 13179 13180 private void clearDisplayList() { 13181 if (mDisplayList != null) { 13182 mDisplayList.clear(); 13183 } 13184 } 13185 13186 private void resetDisplayList() { 13187 if (mDisplayList != null) { 13188 mDisplayList.reset(); 13189 } 13190 } 13191 13192 /** 13193 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 13194 * 13195 * @return A non-scaled bitmap representing this view or null if cache is disabled. 13196 * 13197 * @see #getDrawingCache(boolean) 13198 */ 13199 public Bitmap getDrawingCache() { 13200 return getDrawingCache(false); 13201 } 13202 13203 /** 13204 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 13205 * is null when caching is disabled. If caching is enabled and the cache is not ready, 13206 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 13207 * draw from the cache when the cache is enabled. To benefit from the cache, you must 13208 * request the drawing cache by calling this method and draw it on screen if the 13209 * returned bitmap is not null.</p> 13210 * 13211 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 13212 * this method will create a bitmap of the same size as this view. Because this bitmap 13213 * will be drawn scaled by the parent ViewGroup, the result on screen might show 13214 * scaling artifacts. To avoid such artifacts, you should call this method by setting 13215 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 13216 * size than the view. This implies that your application must be able to handle this 13217 * size.</p> 13218 * 13219 * @param autoScale Indicates whether the generated bitmap should be scaled based on 13220 * the current density of the screen when the application is in compatibility 13221 * mode. 13222 * 13223 * @return A bitmap representing this view or null if cache is disabled. 13224 * 13225 * @see #setDrawingCacheEnabled(boolean) 13226 * @see #isDrawingCacheEnabled() 13227 * @see #buildDrawingCache(boolean) 13228 * @see #destroyDrawingCache() 13229 */ 13230 public Bitmap getDrawingCache(boolean autoScale) { 13231 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 13232 return null; 13233 } 13234 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 13235 buildDrawingCache(autoScale); 13236 } 13237 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 13238 } 13239 13240 /** 13241 * <p>Frees the resources used by the drawing cache. If you call 13242 * {@link #buildDrawingCache()} manually without calling 13243 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 13244 * should cleanup the cache with this method afterwards.</p> 13245 * 13246 * @see #setDrawingCacheEnabled(boolean) 13247 * @see #buildDrawingCache() 13248 * @see #getDrawingCache() 13249 */ 13250 public void destroyDrawingCache() { 13251 if (mDrawingCache != null) { 13252 mDrawingCache.recycle(); 13253 mDrawingCache = null; 13254 } 13255 if (mUnscaledDrawingCache != null) { 13256 mUnscaledDrawingCache.recycle(); 13257 mUnscaledDrawingCache = null; 13258 } 13259 } 13260 13261 /** 13262 * Setting a solid background color for the drawing cache's bitmaps will improve 13263 * performance and memory usage. Note, though that this should only be used if this 13264 * view will always be drawn on top of a solid color. 13265 * 13266 * @param color The background color to use for the drawing cache's bitmap 13267 * 13268 * @see #setDrawingCacheEnabled(boolean) 13269 * @see #buildDrawingCache() 13270 * @see #getDrawingCache() 13271 */ 13272 public void setDrawingCacheBackgroundColor(int color) { 13273 if (color != mDrawingCacheBackgroundColor) { 13274 mDrawingCacheBackgroundColor = color; 13275 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 13276 } 13277 } 13278 13279 /** 13280 * @see #setDrawingCacheBackgroundColor(int) 13281 * 13282 * @return The background color to used for the drawing cache's bitmap 13283 */ 13284 public int getDrawingCacheBackgroundColor() { 13285 return mDrawingCacheBackgroundColor; 13286 } 13287 13288 /** 13289 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 13290 * 13291 * @see #buildDrawingCache(boolean) 13292 */ 13293 public void buildDrawingCache() { 13294 buildDrawingCache(false); 13295 } 13296 13297 /** 13298 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 13299 * 13300 * <p>If you call {@link #buildDrawingCache()} manually without calling 13301 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 13302 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 13303 * 13304 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 13305 * this method will create a bitmap of the same size as this view. Because this bitmap 13306 * will be drawn scaled by the parent ViewGroup, the result on screen might show 13307 * scaling artifacts. To avoid such artifacts, you should call this method by setting 13308 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 13309 * size than the view. This implies that your application must be able to handle this 13310 * size.</p> 13311 * 13312 * <p>You should avoid calling this method when hardware acceleration is enabled. If 13313 * you do not need the drawing cache bitmap, calling this method will increase memory 13314 * usage and cause the view to be rendered in software once, thus negatively impacting 13315 * performance.</p> 13316 * 13317 * @see #getDrawingCache() 13318 * @see #destroyDrawingCache() 13319 */ 13320 public void buildDrawingCache(boolean autoScale) { 13321 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 13322 mDrawingCache == null : mUnscaledDrawingCache == null)) { 13323 mCachingFailed = false; 13324 13325 int width = mRight - mLeft; 13326 int height = mBottom - mTop; 13327 13328 final AttachInfo attachInfo = mAttachInfo; 13329 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 13330 13331 if (autoScale && scalingRequired) { 13332 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 13333 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 13334 } 13335 13336 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 13337 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 13338 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 13339 13340 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 13341 final long drawingCacheSize = 13342 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 13343 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 13344 if (width > 0 && height > 0) { 13345 Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs " 13346 + projectedBitmapSize + " bytes, only " 13347 + drawingCacheSize + " available"); 13348 } 13349 destroyDrawingCache(); 13350 mCachingFailed = true; 13351 return; 13352 } 13353 13354 boolean clear = true; 13355 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 13356 13357 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 13358 Bitmap.Config quality; 13359 if (!opaque) { 13360 // Never pick ARGB_4444 because it looks awful 13361 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 13362 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 13363 case DRAWING_CACHE_QUALITY_AUTO: 13364 case DRAWING_CACHE_QUALITY_LOW: 13365 case DRAWING_CACHE_QUALITY_HIGH: 13366 default: 13367 quality = Bitmap.Config.ARGB_8888; 13368 break; 13369 } 13370 } else { 13371 // Optimization for translucent windows 13372 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 13373 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 13374 } 13375 13376 // Try to cleanup memory 13377 if (bitmap != null) bitmap.recycle(); 13378 13379 try { 13380 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 13381 width, height, quality); 13382 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 13383 if (autoScale) { 13384 mDrawingCache = bitmap; 13385 } else { 13386 mUnscaledDrawingCache = bitmap; 13387 } 13388 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 13389 } catch (OutOfMemoryError e) { 13390 // If there is not enough memory to create the bitmap cache, just 13391 // ignore the issue as bitmap caches are not required to draw the 13392 // view hierarchy 13393 if (autoScale) { 13394 mDrawingCache = null; 13395 } else { 13396 mUnscaledDrawingCache = null; 13397 } 13398 mCachingFailed = true; 13399 return; 13400 } 13401 13402 clear = drawingCacheBackgroundColor != 0; 13403 } 13404 13405 Canvas canvas; 13406 if (attachInfo != null) { 13407 canvas = attachInfo.mCanvas; 13408 if (canvas == null) { 13409 canvas = new Canvas(); 13410 } 13411 canvas.setBitmap(bitmap); 13412 // Temporarily clobber the cached Canvas in case one of our children 13413 // is also using a drawing cache. Without this, the children would 13414 // steal the canvas by attaching their own bitmap to it and bad, bad 13415 // thing would happen (invisible views, corrupted drawings, etc.) 13416 attachInfo.mCanvas = null; 13417 } else { 13418 // This case should hopefully never or seldom happen 13419 canvas = new Canvas(bitmap); 13420 } 13421 13422 if (clear) { 13423 bitmap.eraseColor(drawingCacheBackgroundColor); 13424 } 13425 13426 computeScroll(); 13427 final int restoreCount = canvas.save(); 13428 13429 if (autoScale && scalingRequired) { 13430 final float scale = attachInfo.mApplicationScale; 13431 canvas.scale(scale, scale); 13432 } 13433 13434 canvas.translate(-mScrollX, -mScrollY); 13435 13436 mPrivateFlags |= PFLAG_DRAWN; 13437 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 13438 mLayerType != LAYER_TYPE_NONE) { 13439 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 13440 } 13441 13442 // Fast path for layouts with no backgrounds 13443 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 13444 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13445 dispatchDraw(canvas); 13446 if (mOverlay != null && !mOverlay.isEmpty()) { 13447 mOverlay.getOverlayView().draw(canvas); 13448 } 13449 } else { 13450 draw(canvas); 13451 } 13452 13453 canvas.restoreToCount(restoreCount); 13454 canvas.setBitmap(null); 13455 13456 if (attachInfo != null) { 13457 // Restore the cached Canvas for our siblings 13458 attachInfo.mCanvas = canvas; 13459 } 13460 } 13461 } 13462 13463 /** 13464 * Create a snapshot of the view into a bitmap. We should probably make 13465 * some form of this public, but should think about the API. 13466 */ 13467 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 13468 int width = mRight - mLeft; 13469 int height = mBottom - mTop; 13470 13471 final AttachInfo attachInfo = mAttachInfo; 13472 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 13473 width = (int) ((width * scale) + 0.5f); 13474 height = (int) ((height * scale) + 0.5f); 13475 13476 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 13477 width > 0 ? width : 1, height > 0 ? height : 1, quality); 13478 if (bitmap == null) { 13479 throw new OutOfMemoryError(); 13480 } 13481 13482 Resources resources = getResources(); 13483 if (resources != null) { 13484 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 13485 } 13486 13487 Canvas canvas; 13488 if (attachInfo != null) { 13489 canvas = attachInfo.mCanvas; 13490 if (canvas == null) { 13491 canvas = new Canvas(); 13492 } 13493 canvas.setBitmap(bitmap); 13494 // Temporarily clobber the cached Canvas in case one of our children 13495 // is also using a drawing cache. Without this, the children would 13496 // steal the canvas by attaching their own bitmap to it and bad, bad 13497 // things would happen (invisible views, corrupted drawings, etc.) 13498 attachInfo.mCanvas = null; 13499 } else { 13500 // This case should hopefully never or seldom happen 13501 canvas = new Canvas(bitmap); 13502 } 13503 13504 if ((backgroundColor & 0xff000000) != 0) { 13505 bitmap.eraseColor(backgroundColor); 13506 } 13507 13508 computeScroll(); 13509 final int restoreCount = canvas.save(); 13510 canvas.scale(scale, scale); 13511 canvas.translate(-mScrollX, -mScrollY); 13512 13513 // Temporarily remove the dirty mask 13514 int flags = mPrivateFlags; 13515 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13516 13517 // Fast path for layouts with no backgrounds 13518 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 13519 dispatchDraw(canvas); 13520 } else { 13521 draw(canvas); 13522 } 13523 13524 mPrivateFlags = flags; 13525 13526 canvas.restoreToCount(restoreCount); 13527 canvas.setBitmap(null); 13528 13529 if (attachInfo != null) { 13530 // Restore the cached Canvas for our siblings 13531 attachInfo.mCanvas = canvas; 13532 } 13533 13534 return bitmap; 13535 } 13536 13537 /** 13538 * Indicates whether this View is currently in edit mode. A View is usually 13539 * in edit mode when displayed within a developer tool. For instance, if 13540 * this View is being drawn by a visual user interface builder, this method 13541 * should return true. 13542 * 13543 * Subclasses should check the return value of this method to provide 13544 * different behaviors if their normal behavior might interfere with the 13545 * host environment. For instance: the class spawns a thread in its 13546 * constructor, the drawing code relies on device-specific features, etc. 13547 * 13548 * This method is usually checked in the drawing code of custom widgets. 13549 * 13550 * @return True if this View is in edit mode, false otherwise. 13551 */ 13552 public boolean isInEditMode() { 13553 return false; 13554 } 13555 13556 /** 13557 * If the View draws content inside its padding and enables fading edges, 13558 * it needs to support padding offsets. Padding offsets are added to the 13559 * fading edges to extend the length of the fade so that it covers pixels 13560 * drawn inside the padding. 13561 * 13562 * Subclasses of this class should override this method if they need 13563 * to draw content inside the padding. 13564 * 13565 * @return True if padding offset must be applied, false otherwise. 13566 * 13567 * @see #getLeftPaddingOffset() 13568 * @see #getRightPaddingOffset() 13569 * @see #getTopPaddingOffset() 13570 * @see #getBottomPaddingOffset() 13571 * 13572 * @since CURRENT 13573 */ 13574 protected boolean isPaddingOffsetRequired() { 13575 return false; 13576 } 13577 13578 /** 13579 * Amount by which to extend the left fading region. Called only when 13580 * {@link #isPaddingOffsetRequired()} returns true. 13581 * 13582 * @return The left padding offset in pixels. 13583 * 13584 * @see #isPaddingOffsetRequired() 13585 * 13586 * @since CURRENT 13587 */ 13588 protected int getLeftPaddingOffset() { 13589 return 0; 13590 } 13591 13592 /** 13593 * Amount by which to extend the right fading region. Called only when 13594 * {@link #isPaddingOffsetRequired()} returns true. 13595 * 13596 * @return The right padding offset in pixels. 13597 * 13598 * @see #isPaddingOffsetRequired() 13599 * 13600 * @since CURRENT 13601 */ 13602 protected int getRightPaddingOffset() { 13603 return 0; 13604 } 13605 13606 /** 13607 * Amount by which to extend the top fading region. Called only when 13608 * {@link #isPaddingOffsetRequired()} returns true. 13609 * 13610 * @return The top padding offset in pixels. 13611 * 13612 * @see #isPaddingOffsetRequired() 13613 * 13614 * @since CURRENT 13615 */ 13616 protected int getTopPaddingOffset() { 13617 return 0; 13618 } 13619 13620 /** 13621 * Amount by which to extend the bottom fading region. Called only when 13622 * {@link #isPaddingOffsetRequired()} returns true. 13623 * 13624 * @return The bottom padding offset in pixels. 13625 * 13626 * @see #isPaddingOffsetRequired() 13627 * 13628 * @since CURRENT 13629 */ 13630 protected int getBottomPaddingOffset() { 13631 return 0; 13632 } 13633 13634 /** 13635 * @hide 13636 * @param offsetRequired 13637 */ 13638 protected int getFadeTop(boolean offsetRequired) { 13639 int top = mPaddingTop; 13640 if (offsetRequired) top += getTopPaddingOffset(); 13641 return top; 13642 } 13643 13644 /** 13645 * @hide 13646 * @param offsetRequired 13647 */ 13648 protected int getFadeHeight(boolean offsetRequired) { 13649 int padding = mPaddingTop; 13650 if (offsetRequired) padding += getTopPaddingOffset(); 13651 return mBottom - mTop - mPaddingBottom - padding; 13652 } 13653 13654 /** 13655 * <p>Indicates whether this view is attached to a hardware accelerated 13656 * window or not.</p> 13657 * 13658 * <p>Even if this method returns true, it does not mean that every call 13659 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 13660 * accelerated {@link android.graphics.Canvas}. For instance, if this view 13661 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 13662 * window is hardware accelerated, 13663 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 13664 * return false, and this method will return true.</p> 13665 * 13666 * @return True if the view is attached to a window and the window is 13667 * hardware accelerated; false in any other case. 13668 */ 13669 public boolean isHardwareAccelerated() { 13670 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 13671 } 13672 13673 /** 13674 * Sets a rectangular area on this view to which the view will be clipped 13675 * when it is drawn. Setting the value to null will remove the clip bounds 13676 * and the view will draw normally, using its full bounds. 13677 * 13678 * @param clipBounds The rectangular area, in the local coordinates of 13679 * this view, to which future drawing operations will be clipped. 13680 */ 13681 public void setClipBounds(Rect clipBounds) { 13682 if (clipBounds != null) { 13683 if (clipBounds.equals(mClipBounds)) { 13684 return; 13685 } 13686 if (mClipBounds == null) { 13687 invalidate(); 13688 mClipBounds = new Rect(clipBounds); 13689 } else { 13690 invalidate(Math.min(mClipBounds.left, clipBounds.left), 13691 Math.min(mClipBounds.top, clipBounds.top), 13692 Math.max(mClipBounds.right, clipBounds.right), 13693 Math.max(mClipBounds.bottom, clipBounds.bottom)); 13694 mClipBounds.set(clipBounds); 13695 } 13696 } else { 13697 if (mClipBounds != null) { 13698 invalidate(); 13699 mClipBounds = null; 13700 } 13701 } 13702 } 13703 13704 /** 13705 * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}. 13706 * 13707 * @return A copy of the current clip bounds if clip bounds are set, 13708 * otherwise null. 13709 */ 13710 public Rect getClipBounds() { 13711 return (mClipBounds != null) ? new Rect(mClipBounds) : null; 13712 } 13713 13714 /** 13715 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 13716 * case of an active Animation being run on the view. 13717 */ 13718 private boolean drawAnimation(ViewGroup parent, long drawingTime, 13719 Animation a, boolean scalingRequired) { 13720 Transformation invalidationTransform; 13721 final int flags = parent.mGroupFlags; 13722 final boolean initialized = a.isInitialized(); 13723 if (!initialized) { 13724 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 13725 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 13726 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 13727 onAnimationStart(); 13728 } 13729 13730 final Transformation t = parent.getChildTransformation(); 13731 boolean more = a.getTransformation(drawingTime, t, 1f); 13732 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 13733 if (parent.mInvalidationTransformation == null) { 13734 parent.mInvalidationTransformation = new Transformation(); 13735 } 13736 invalidationTransform = parent.mInvalidationTransformation; 13737 a.getTransformation(drawingTime, invalidationTransform, 1f); 13738 } else { 13739 invalidationTransform = t; 13740 } 13741 13742 if (more) { 13743 if (!a.willChangeBounds()) { 13744 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 13745 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 13746 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 13747 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 13748 // The child need to draw an animation, potentially offscreen, so 13749 // make sure we do not cancel invalidate requests 13750 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 13751 parent.invalidate(mLeft, mTop, mRight, mBottom); 13752 } 13753 } else { 13754 if (parent.mInvalidateRegion == null) { 13755 parent.mInvalidateRegion = new RectF(); 13756 } 13757 final RectF region = parent.mInvalidateRegion; 13758 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 13759 invalidationTransform); 13760 13761 // The child need to draw an animation, potentially offscreen, so 13762 // make sure we do not cancel invalidate requests 13763 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 13764 13765 final int left = mLeft + (int) region.left; 13766 final int top = mTop + (int) region.top; 13767 parent.invalidate(left, top, left + (int) (region.width() + .5f), 13768 top + (int) (region.height() + .5f)); 13769 } 13770 } 13771 return more; 13772 } 13773 13774 /** 13775 * This method is called by getDisplayList() when a display list is created or re-rendered. 13776 * It sets or resets the current value of all properties on that display list (resetting is 13777 * necessary when a display list is being re-created, because we need to make sure that 13778 * previously-set transform values 13779 */ 13780 void setDisplayListProperties(DisplayList displayList) { 13781 if (displayList != null) { 13782 displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 13783 displayList.setHasOverlappingRendering(hasOverlappingRendering()); 13784 if (mParent instanceof ViewGroup) { 13785 displayList.setClipToBounds( 13786 (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0); 13787 } 13788 float alpha = 1; 13789 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 13790 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 13791 ViewGroup parentVG = (ViewGroup) mParent; 13792 final Transformation t = parentVG.getChildTransformation(); 13793 if (parentVG.getChildStaticTransformation(this, t)) { 13794 final int transformType = t.getTransformationType(); 13795 if (transformType != Transformation.TYPE_IDENTITY) { 13796 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 13797 alpha = t.getAlpha(); 13798 } 13799 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 13800 displayList.setMatrix(t.getMatrix()); 13801 } 13802 } 13803 } 13804 } 13805 if (mTransformationInfo != null) { 13806 alpha *= mTransformationInfo.mAlpha; 13807 if (alpha < 1) { 13808 final int multipliedAlpha = (int) (255 * alpha); 13809 if (onSetAlpha(multipliedAlpha)) { 13810 alpha = 1; 13811 } 13812 } 13813 displayList.setTransformationInfo(alpha, 13814 mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY, 13815 mTransformationInfo.mRotation, mTransformationInfo.mRotationX, 13816 mTransformationInfo.mRotationY, mTransformationInfo.mScaleX, 13817 mTransformationInfo.mScaleY); 13818 if (mTransformationInfo.mCamera == null) { 13819 mTransformationInfo.mCamera = new Camera(); 13820 mTransformationInfo.matrix3D = new Matrix(); 13821 } 13822 displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ()); 13823 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == PFLAG_PIVOT_EXPLICITLY_SET) { 13824 displayList.setPivotX(getPivotX()); 13825 displayList.setPivotY(getPivotY()); 13826 } 13827 } else if (alpha < 1) { 13828 displayList.setAlpha(alpha); 13829 } 13830 } 13831 } 13832 13833 /** 13834 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 13835 * This draw() method is an implementation detail and is not intended to be overridden or 13836 * to be called from anywhere else other than ViewGroup.drawChild(). 13837 */ 13838 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 13839 boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 13840 boolean more = false; 13841 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 13842 final int flags = parent.mGroupFlags; 13843 13844 if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) { 13845 parent.getChildTransformation().clear(); 13846 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 13847 } 13848 13849 Transformation transformToApply = null; 13850 boolean concatMatrix = false; 13851 13852 boolean scalingRequired = false; 13853 boolean caching; 13854 int layerType = getLayerType(); 13855 13856 final boolean hardwareAccelerated = canvas.isHardwareAccelerated(); 13857 if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 || 13858 (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) { 13859 caching = true; 13860 // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList 13861 if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired; 13862 } else { 13863 caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated; 13864 } 13865 13866 final Animation a = getAnimation(); 13867 if (a != null) { 13868 more = drawAnimation(parent, drawingTime, a, scalingRequired); 13869 concatMatrix = a.willChangeTransformationMatrix(); 13870 if (concatMatrix) { 13871 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 13872 } 13873 transformToApply = parent.getChildTransformation(); 13874 } else { 13875 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) == 13876 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM && mDisplayList != null) { 13877 // No longer animating: clear out old animation matrix 13878 mDisplayList.setAnimationMatrix(null); 13879 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 13880 } 13881 if (!useDisplayListProperties && 13882 (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 13883 final Transformation t = parent.getChildTransformation(); 13884 final boolean hasTransform = parent.getChildStaticTransformation(this, t); 13885 if (hasTransform) { 13886 final int transformType = t.getTransformationType(); 13887 transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null; 13888 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 13889 } 13890 } 13891 } 13892 13893 concatMatrix |= !childHasIdentityMatrix; 13894 13895 // Sets the flag as early as possible to allow draw() implementations 13896 // to call invalidate() successfully when doing animations 13897 mPrivateFlags |= PFLAG_DRAWN; 13898 13899 if (!concatMatrix && 13900 (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 13901 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 13902 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 13903 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 13904 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 13905 return more; 13906 } 13907 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 13908 13909 if (hardwareAccelerated) { 13910 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 13911 // retain the flag's value temporarily in the mRecreateDisplayList flag 13912 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED; 13913 mPrivateFlags &= ~PFLAG_INVALIDATED; 13914 } 13915 13916 DisplayList displayList = null; 13917 Bitmap cache = null; 13918 boolean hasDisplayList = false; 13919 if (caching) { 13920 if (!hardwareAccelerated) { 13921 if (layerType != LAYER_TYPE_NONE) { 13922 layerType = LAYER_TYPE_SOFTWARE; 13923 buildDrawingCache(true); 13924 } 13925 cache = getDrawingCache(true); 13926 } else { 13927 switch (layerType) { 13928 case LAYER_TYPE_SOFTWARE: 13929 if (useDisplayListProperties) { 13930 hasDisplayList = canHaveDisplayList(); 13931 } else { 13932 buildDrawingCache(true); 13933 cache = getDrawingCache(true); 13934 } 13935 break; 13936 case LAYER_TYPE_HARDWARE: 13937 if (useDisplayListProperties) { 13938 hasDisplayList = canHaveDisplayList(); 13939 } 13940 break; 13941 case LAYER_TYPE_NONE: 13942 // Delay getting the display list until animation-driven alpha values are 13943 // set up and possibly passed on to the view 13944 hasDisplayList = canHaveDisplayList(); 13945 break; 13946 } 13947 } 13948 } 13949 useDisplayListProperties &= hasDisplayList; 13950 if (useDisplayListProperties) { 13951 displayList = getDisplayList(); 13952 if (!displayList.isValid()) { 13953 // Uncommon, but possible. If a view is removed from the hierarchy during the call 13954 // to getDisplayList(), the display list will be marked invalid and we should not 13955 // try to use it again. 13956 displayList = null; 13957 hasDisplayList = false; 13958 useDisplayListProperties = false; 13959 } 13960 } 13961 13962 int sx = 0; 13963 int sy = 0; 13964 if (!hasDisplayList) { 13965 computeScroll(); 13966 sx = mScrollX; 13967 sy = mScrollY; 13968 } 13969 13970 final boolean hasNoCache = cache == null || hasDisplayList; 13971 final boolean offsetForScroll = cache == null && !hasDisplayList && 13972 layerType != LAYER_TYPE_HARDWARE; 13973 13974 int restoreTo = -1; 13975 if (!useDisplayListProperties || transformToApply != null) { 13976 restoreTo = canvas.save(); 13977 } 13978 if (offsetForScroll) { 13979 canvas.translate(mLeft - sx, mTop - sy); 13980 } else { 13981 if (!useDisplayListProperties) { 13982 canvas.translate(mLeft, mTop); 13983 } 13984 if (scalingRequired) { 13985 if (useDisplayListProperties) { 13986 // TODO: Might not need this if we put everything inside the DL 13987 restoreTo = canvas.save(); 13988 } 13989 // mAttachInfo cannot be null, otherwise scalingRequired == false 13990 final float scale = 1.0f / mAttachInfo.mApplicationScale; 13991 canvas.scale(scale, scale); 13992 } 13993 } 13994 13995 float alpha = useDisplayListProperties ? 1 : getAlpha(); 13996 if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() || 13997 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 13998 if (transformToApply != null || !childHasIdentityMatrix) { 13999 int transX = 0; 14000 int transY = 0; 14001 14002 if (offsetForScroll) { 14003 transX = -sx; 14004 transY = -sy; 14005 } 14006 14007 if (transformToApply != null) { 14008 if (concatMatrix) { 14009 if (useDisplayListProperties) { 14010 displayList.setAnimationMatrix(transformToApply.getMatrix()); 14011 } else { 14012 // Undo the scroll translation, apply the transformation matrix, 14013 // then redo the scroll translate to get the correct result. 14014 canvas.translate(-transX, -transY); 14015 canvas.concat(transformToApply.getMatrix()); 14016 canvas.translate(transX, transY); 14017 } 14018 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14019 } 14020 14021 float transformAlpha = transformToApply.getAlpha(); 14022 if (transformAlpha < 1) { 14023 alpha *= transformAlpha; 14024 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14025 } 14026 } 14027 14028 if (!childHasIdentityMatrix && !useDisplayListProperties) { 14029 canvas.translate(-transX, -transY); 14030 canvas.concat(getMatrix()); 14031 canvas.translate(transX, transY); 14032 } 14033 } 14034 14035 // Deal with alpha if it is or used to be <1 14036 if (alpha < 1 || 14037 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 14038 if (alpha < 1) { 14039 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 14040 } else { 14041 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 14042 } 14043 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14044 if (hasNoCache) { 14045 final int multipliedAlpha = (int) (255 * alpha); 14046 if (!onSetAlpha(multipliedAlpha)) { 14047 int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 14048 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 || 14049 layerType != LAYER_TYPE_NONE) { 14050 layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG; 14051 } 14052 if (useDisplayListProperties) { 14053 displayList.setAlpha(alpha * getAlpha()); 14054 } else if (layerType == LAYER_TYPE_NONE) { 14055 final int scrollX = hasDisplayList ? 0 : sx; 14056 final int scrollY = hasDisplayList ? 0 : sy; 14057 canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft, 14058 scrollY + mBottom - mTop, multipliedAlpha, layerFlags); 14059 } 14060 } else { 14061 // Alpha is handled by the child directly, clobber the layer's alpha 14062 mPrivateFlags |= PFLAG_ALPHA_SET; 14063 } 14064 } 14065 } 14066 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 14067 onSetAlpha(255); 14068 mPrivateFlags &= ~PFLAG_ALPHA_SET; 14069 } 14070 14071 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN && 14072 !useDisplayListProperties && cache == null) { 14073 if (offsetForScroll) { 14074 canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop)); 14075 } else { 14076 if (!scalingRequired || cache == null) { 14077 canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop); 14078 } else { 14079 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 14080 } 14081 } 14082 } 14083 14084 if (!useDisplayListProperties && hasDisplayList) { 14085 displayList = getDisplayList(); 14086 if (!displayList.isValid()) { 14087 // Uncommon, but possible. If a view is removed from the hierarchy during the call 14088 // to getDisplayList(), the display list will be marked invalid and we should not 14089 // try to use it again. 14090 displayList = null; 14091 hasDisplayList = false; 14092 } 14093 } 14094 14095 if (hasNoCache) { 14096 boolean layerRendered = false; 14097 if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) { 14098 final HardwareLayer layer = getHardwareLayer(); 14099 if (layer != null && layer.isValid()) { 14100 mLayerPaint.setAlpha((int) (alpha * 255)); 14101 ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint); 14102 layerRendered = true; 14103 } else { 14104 final int scrollX = hasDisplayList ? 0 : sx; 14105 final int scrollY = hasDisplayList ? 0 : sy; 14106 canvas.saveLayer(scrollX, scrollY, 14107 scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint, 14108 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG); 14109 } 14110 } 14111 14112 if (!layerRendered) { 14113 if (!hasDisplayList) { 14114 // Fast path for layouts with no backgrounds 14115 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14116 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14117 dispatchDraw(canvas); 14118 } else { 14119 draw(canvas); 14120 } 14121 } else { 14122 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14123 ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags); 14124 } 14125 } 14126 } else if (cache != null) { 14127 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14128 Paint cachePaint; 14129 14130 if (layerType == LAYER_TYPE_NONE) { 14131 cachePaint = parent.mCachePaint; 14132 if (cachePaint == null) { 14133 cachePaint = new Paint(); 14134 cachePaint.setDither(false); 14135 parent.mCachePaint = cachePaint; 14136 } 14137 if (alpha < 1) { 14138 cachePaint.setAlpha((int) (alpha * 255)); 14139 parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 14140 } else if ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) { 14141 cachePaint.setAlpha(255); 14142 parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 14143 } 14144 } else { 14145 cachePaint = mLayerPaint; 14146 cachePaint.setAlpha((int) (alpha * 255)); 14147 } 14148 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 14149 } 14150 14151 if (restoreTo >= 0) { 14152 canvas.restoreToCount(restoreTo); 14153 } 14154 14155 if (a != null && !more) { 14156 if (!hardwareAccelerated && !a.getFillAfter()) { 14157 onSetAlpha(255); 14158 } 14159 parent.finishAnimatingView(this, a); 14160 } 14161 14162 if (more && hardwareAccelerated) { 14163 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 14164 // alpha animations should cause the child to recreate its display list 14165 invalidate(true); 14166 } 14167 } 14168 14169 mRecreateDisplayList = false; 14170 14171 return more; 14172 } 14173 14174 /** 14175 * Manually render this view (and all of its children) to the given Canvas. 14176 * The view must have already done a full layout before this function is 14177 * called. When implementing a view, implement 14178 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 14179 * If you do need to override this method, call the superclass version. 14180 * 14181 * @param canvas The Canvas to which the View is rendered. 14182 */ 14183 public void draw(Canvas canvas) { 14184 if (mClipBounds != null) { 14185 canvas.clipRect(mClipBounds); 14186 } 14187 final int privateFlags = mPrivateFlags; 14188 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 14189 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 14190 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 14191 14192 /* 14193 * Draw traversal performs several drawing steps which must be executed 14194 * in the appropriate order: 14195 * 14196 * 1. Draw the background 14197 * 2. If necessary, save the canvas' layers to prepare for fading 14198 * 3. Draw view's content 14199 * 4. Draw children 14200 * 5. If necessary, draw the fading edges and restore layers 14201 * 6. Draw decorations (scrollbars for instance) 14202 */ 14203 14204 // Step 1, draw the background, if needed 14205 int saveCount; 14206 14207 if (!dirtyOpaque) { 14208 final Drawable background = mBackground; 14209 if (background != null) { 14210 final int scrollX = mScrollX; 14211 final int scrollY = mScrollY; 14212 14213 if (mBackgroundSizeChanged) { 14214 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 14215 mBackgroundSizeChanged = false; 14216 } 14217 14218 if ((scrollX | scrollY) == 0) { 14219 background.draw(canvas); 14220 } else { 14221 canvas.translate(scrollX, scrollY); 14222 background.draw(canvas); 14223 canvas.translate(-scrollX, -scrollY); 14224 } 14225 } 14226 } 14227 14228 // skip step 2 & 5 if possible (common case) 14229 final int viewFlags = mViewFlags; 14230 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 14231 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 14232 if (!verticalEdges && !horizontalEdges) { 14233 // Step 3, draw the content 14234 if (!dirtyOpaque) onDraw(canvas); 14235 14236 // Step 4, draw the children 14237 dispatchDraw(canvas); 14238 14239 // Step 6, draw decorations (scrollbars) 14240 onDrawScrollBars(canvas); 14241 14242 if (mOverlay != null && !mOverlay.isEmpty()) { 14243 mOverlay.getOverlayView().dispatchDraw(canvas); 14244 } 14245 14246 // we're done... 14247 return; 14248 } 14249 14250 /* 14251 * Here we do the full fledged routine... 14252 * (this is an uncommon case where speed matters less, 14253 * this is why we repeat some of the tests that have been 14254 * done above) 14255 */ 14256 14257 boolean drawTop = false; 14258 boolean drawBottom = false; 14259 boolean drawLeft = false; 14260 boolean drawRight = false; 14261 14262 float topFadeStrength = 0.0f; 14263 float bottomFadeStrength = 0.0f; 14264 float leftFadeStrength = 0.0f; 14265 float rightFadeStrength = 0.0f; 14266 14267 // Step 2, save the canvas' layers 14268 int paddingLeft = mPaddingLeft; 14269 14270 final boolean offsetRequired = isPaddingOffsetRequired(); 14271 if (offsetRequired) { 14272 paddingLeft += getLeftPaddingOffset(); 14273 } 14274 14275 int left = mScrollX + paddingLeft; 14276 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 14277 int top = mScrollY + getFadeTop(offsetRequired); 14278 int bottom = top + getFadeHeight(offsetRequired); 14279 14280 if (offsetRequired) { 14281 right += getRightPaddingOffset(); 14282 bottom += getBottomPaddingOffset(); 14283 } 14284 14285 final ScrollabilityCache scrollabilityCache = mScrollCache; 14286 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 14287 int length = (int) fadeHeight; 14288 14289 // clip the fade length if top and bottom fades overlap 14290 // overlapping fades produce odd-looking artifacts 14291 if (verticalEdges && (top + length > bottom - length)) { 14292 length = (bottom - top) / 2; 14293 } 14294 14295 // also clip horizontal fades if necessary 14296 if (horizontalEdges && (left + length > right - length)) { 14297 length = (right - left) / 2; 14298 } 14299 14300 if (verticalEdges) { 14301 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 14302 drawTop = topFadeStrength * fadeHeight > 1.0f; 14303 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 14304 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 14305 } 14306 14307 if (horizontalEdges) { 14308 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 14309 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 14310 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 14311 drawRight = rightFadeStrength * fadeHeight > 1.0f; 14312 } 14313 14314 saveCount = canvas.getSaveCount(); 14315 14316 int solidColor = getSolidColor(); 14317 if (solidColor == 0) { 14318 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 14319 14320 if (drawTop) { 14321 canvas.saveLayer(left, top, right, top + length, null, flags); 14322 } 14323 14324 if (drawBottom) { 14325 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 14326 } 14327 14328 if (drawLeft) { 14329 canvas.saveLayer(left, top, left + length, bottom, null, flags); 14330 } 14331 14332 if (drawRight) { 14333 canvas.saveLayer(right - length, top, right, bottom, null, flags); 14334 } 14335 } else { 14336 scrollabilityCache.setFadeColor(solidColor); 14337 } 14338 14339 // Step 3, draw the content 14340 if (!dirtyOpaque) onDraw(canvas); 14341 14342 // Step 4, draw the children 14343 dispatchDraw(canvas); 14344 14345 // Step 5, draw the fade effect and restore layers 14346 final Paint p = scrollabilityCache.paint; 14347 final Matrix matrix = scrollabilityCache.matrix; 14348 final Shader fade = scrollabilityCache.shader; 14349 14350 if (drawTop) { 14351 matrix.setScale(1, fadeHeight * topFadeStrength); 14352 matrix.postTranslate(left, top); 14353 fade.setLocalMatrix(matrix); 14354 canvas.drawRect(left, top, right, top + length, p); 14355 } 14356 14357 if (drawBottom) { 14358 matrix.setScale(1, fadeHeight * bottomFadeStrength); 14359 matrix.postRotate(180); 14360 matrix.postTranslate(left, bottom); 14361 fade.setLocalMatrix(matrix); 14362 canvas.drawRect(left, bottom - length, right, bottom, p); 14363 } 14364 14365 if (drawLeft) { 14366 matrix.setScale(1, fadeHeight * leftFadeStrength); 14367 matrix.postRotate(-90); 14368 matrix.postTranslate(left, top); 14369 fade.setLocalMatrix(matrix); 14370 canvas.drawRect(left, top, left + length, bottom, p); 14371 } 14372 14373 if (drawRight) { 14374 matrix.setScale(1, fadeHeight * rightFadeStrength); 14375 matrix.postRotate(90); 14376 matrix.postTranslate(right, top); 14377 fade.setLocalMatrix(matrix); 14378 canvas.drawRect(right - length, top, right, bottom, p); 14379 } 14380 14381 canvas.restoreToCount(saveCount); 14382 14383 // Step 6, draw decorations (scrollbars) 14384 onDrawScrollBars(canvas); 14385 14386 if (mOverlay != null && !mOverlay.isEmpty()) { 14387 mOverlay.getOverlayView().dispatchDraw(canvas); 14388 } 14389 } 14390 14391 /** 14392 * Returns the overlay for this view, creating it if it does not yet exist. 14393 * Adding drawables to the overlay will cause them to be displayed whenever 14394 * the view itself is redrawn. Objects in the overlay should be actively 14395 * managed: remove them when they should not be displayed anymore. The 14396 * overlay will always have the same size as its host view. 14397 * 14398 * <p>Note: Overlays do not currently work correctly with {@link 14399 * SurfaceView} or {@link TextureView}; contents in overlays for these 14400 * types of views may not display correctly.</p> 14401 * 14402 * @return The ViewOverlay object for this view. 14403 * @see ViewOverlay 14404 */ 14405 public ViewOverlay getOverlay() { 14406 if (mOverlay == null) { 14407 mOverlay = new ViewOverlay(mContext, this); 14408 } 14409 return mOverlay; 14410 } 14411 14412 /** 14413 * Override this if your view is known to always be drawn on top of a solid color background, 14414 * and needs to draw fading edges. Returning a non-zero color enables the view system to 14415 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 14416 * should be set to 0xFF. 14417 * 14418 * @see #setVerticalFadingEdgeEnabled(boolean) 14419 * @see #setHorizontalFadingEdgeEnabled(boolean) 14420 * 14421 * @return The known solid color background for this view, or 0 if the color may vary 14422 */ 14423 @ViewDebug.ExportedProperty(category = "drawing") 14424 public int getSolidColor() { 14425 return 0; 14426 } 14427 14428 /** 14429 * Build a human readable string representation of the specified view flags. 14430 * 14431 * @param flags the view flags to convert to a string 14432 * @return a String representing the supplied flags 14433 */ 14434 private static String printFlags(int flags) { 14435 String output = ""; 14436 int numFlags = 0; 14437 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 14438 output += "TAKES_FOCUS"; 14439 numFlags++; 14440 } 14441 14442 switch (flags & VISIBILITY_MASK) { 14443 case INVISIBLE: 14444 if (numFlags > 0) { 14445 output += " "; 14446 } 14447 output += "INVISIBLE"; 14448 // USELESS HERE numFlags++; 14449 break; 14450 case GONE: 14451 if (numFlags > 0) { 14452 output += " "; 14453 } 14454 output += "GONE"; 14455 // USELESS HERE numFlags++; 14456 break; 14457 default: 14458 break; 14459 } 14460 return output; 14461 } 14462 14463 /** 14464 * Build a human readable string representation of the specified private 14465 * view flags. 14466 * 14467 * @param privateFlags the private view flags to convert to a string 14468 * @return a String representing the supplied flags 14469 */ 14470 private static String printPrivateFlags(int privateFlags) { 14471 String output = ""; 14472 int numFlags = 0; 14473 14474 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 14475 output += "WANTS_FOCUS"; 14476 numFlags++; 14477 } 14478 14479 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 14480 if (numFlags > 0) { 14481 output += " "; 14482 } 14483 output += "FOCUSED"; 14484 numFlags++; 14485 } 14486 14487 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 14488 if (numFlags > 0) { 14489 output += " "; 14490 } 14491 output += "SELECTED"; 14492 numFlags++; 14493 } 14494 14495 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 14496 if (numFlags > 0) { 14497 output += " "; 14498 } 14499 output += "IS_ROOT_NAMESPACE"; 14500 numFlags++; 14501 } 14502 14503 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 14504 if (numFlags > 0) { 14505 output += " "; 14506 } 14507 output += "HAS_BOUNDS"; 14508 numFlags++; 14509 } 14510 14511 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 14512 if (numFlags > 0) { 14513 output += " "; 14514 } 14515 output += "DRAWN"; 14516 // USELESS HERE numFlags++; 14517 } 14518 return output; 14519 } 14520 14521 /** 14522 * <p>Indicates whether or not this view's layout will be requested during 14523 * the next hierarchy layout pass.</p> 14524 * 14525 * @return true if the layout will be forced during next layout pass 14526 */ 14527 public boolean isLayoutRequested() { 14528 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 14529 } 14530 14531 /** 14532 * Return true if o is a ViewGroup that is laying out using optical bounds. 14533 * @hide 14534 */ 14535 public static boolean isLayoutModeOptical(Object o) { 14536 return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical(); 14537 } 14538 14539 private boolean setOpticalFrame(int left, int top, int right, int bottom) { 14540 Insets parentInsets = mParent instanceof View ? 14541 ((View) mParent).getOpticalInsets() : Insets.NONE; 14542 Insets childInsets = getOpticalInsets(); 14543 return setFrame( 14544 left + parentInsets.left - childInsets.left, 14545 top + parentInsets.top - childInsets.top, 14546 right + parentInsets.left + childInsets.right, 14547 bottom + parentInsets.top + childInsets.bottom); 14548 } 14549 14550 /** 14551 * Assign a size and position to a view and all of its 14552 * descendants 14553 * 14554 * <p>This is the second phase of the layout mechanism. 14555 * (The first is measuring). In this phase, each parent calls 14556 * layout on all of its children to position them. 14557 * This is typically done using the child measurements 14558 * that were stored in the measure pass().</p> 14559 * 14560 * <p>Derived classes should not override this method. 14561 * Derived classes with children should override 14562 * onLayout. In that method, they should 14563 * call layout on each of their children.</p> 14564 * 14565 * @param l Left position, relative to parent 14566 * @param t Top position, relative to parent 14567 * @param r Right position, relative to parent 14568 * @param b Bottom position, relative to parent 14569 */ 14570 @SuppressWarnings({"unchecked"}) 14571 public void layout(int l, int t, int r, int b) { 14572 if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) { 14573 onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec); 14574 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 14575 } 14576 14577 int oldL = mLeft; 14578 int oldT = mTop; 14579 int oldB = mBottom; 14580 int oldR = mRight; 14581 14582 boolean changed = isLayoutModeOptical(mParent) ? 14583 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); 14584 14585 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 14586 onLayout(changed, l, t, r, b); 14587 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 14588 14589 ListenerInfo li = mListenerInfo; 14590 if (li != null && li.mOnLayoutChangeListeners != null) { 14591 ArrayList<OnLayoutChangeListener> listenersCopy = 14592 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 14593 int numListeners = listenersCopy.size(); 14594 for (int i = 0; i < numListeners; ++i) { 14595 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 14596 } 14597 } 14598 } 14599 14600 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 14601 mPrivateFlags3 |= PFLAG3_IS_LAID_OUT; 14602 } 14603 14604 /** 14605 * Called from layout when this view should 14606 * assign a size and position to each of its children. 14607 * 14608 * Derived classes with children should override 14609 * this method and call layout on each of 14610 * their children. 14611 * @param changed This is a new size or position for this view 14612 * @param left Left position, relative to parent 14613 * @param top Top position, relative to parent 14614 * @param right Right position, relative to parent 14615 * @param bottom Bottom position, relative to parent 14616 */ 14617 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 14618 } 14619 14620 /** 14621 * Assign a size and position to this view. 14622 * 14623 * This is called from layout. 14624 * 14625 * @param left Left position, relative to parent 14626 * @param top Top position, relative to parent 14627 * @param right Right position, relative to parent 14628 * @param bottom Bottom position, relative to parent 14629 * @return true if the new size and position are different than the 14630 * previous ones 14631 * {@hide} 14632 */ 14633 protected boolean setFrame(int left, int top, int right, int bottom) { 14634 boolean changed = false; 14635 14636 if (DBG) { 14637 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 14638 + right + "," + bottom + ")"); 14639 } 14640 14641 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 14642 changed = true; 14643 14644 // Remember our drawn bit 14645 int drawn = mPrivateFlags & PFLAG_DRAWN; 14646 14647 int oldWidth = mRight - mLeft; 14648 int oldHeight = mBottom - mTop; 14649 int newWidth = right - left; 14650 int newHeight = bottom - top; 14651 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 14652 14653 // Invalidate our old position 14654 invalidate(sizeChanged); 14655 14656 mLeft = left; 14657 mTop = top; 14658 mRight = right; 14659 mBottom = bottom; 14660 if (mDisplayList != null) { 14661 mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 14662 } 14663 14664 mPrivateFlags |= PFLAG_HAS_BOUNDS; 14665 14666 14667 if (sizeChanged) { 14668 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 14669 // A change in dimension means an auto-centered pivot point changes, too 14670 if (mTransformationInfo != null) { 14671 mTransformationInfo.mMatrixDirty = true; 14672 } 14673 } 14674 sizeChange(newWidth, newHeight, oldWidth, oldHeight); 14675 } 14676 14677 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 14678 // If we are visible, force the DRAWN bit to on so that 14679 // this invalidate will go through (at least to our parent). 14680 // This is because someone may have invalidated this view 14681 // before this call to setFrame came in, thereby clearing 14682 // the DRAWN bit. 14683 mPrivateFlags |= PFLAG_DRAWN; 14684 invalidate(sizeChanged); 14685 // parent display list may need to be recreated based on a change in the bounds 14686 // of any child 14687 invalidateParentCaches(); 14688 } 14689 14690 // Reset drawn bit to original value (invalidate turns it off) 14691 mPrivateFlags |= drawn; 14692 14693 mBackgroundSizeChanged = true; 14694 14695 notifySubtreeAccessibilityStateChangedIfNeeded(); 14696 } 14697 return changed; 14698 } 14699 14700 private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) { 14701 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 14702 if (mOverlay != null) { 14703 mOverlay.getOverlayView().setRight(newWidth); 14704 mOverlay.getOverlayView().setBottom(newHeight); 14705 } 14706 } 14707 14708 /** 14709 * Finalize inflating a view from XML. This is called as the last phase 14710 * of inflation, after all child views have been added. 14711 * 14712 * <p>Even if the subclass overrides onFinishInflate, they should always be 14713 * sure to call the super method, so that we get called. 14714 */ 14715 protected void onFinishInflate() { 14716 } 14717 14718 /** 14719 * Returns the resources associated with this view. 14720 * 14721 * @return Resources object. 14722 */ 14723 public Resources getResources() { 14724 return mResources; 14725 } 14726 14727 /** 14728 * Invalidates the specified Drawable. 14729 * 14730 * @param drawable the drawable to invalidate 14731 */ 14732 public void invalidateDrawable(Drawable drawable) { 14733 if (verifyDrawable(drawable)) { 14734 final Rect dirty = drawable.getBounds(); 14735 final int scrollX = mScrollX; 14736 final int scrollY = mScrollY; 14737 14738 invalidate(dirty.left + scrollX, dirty.top + scrollY, 14739 dirty.right + scrollX, dirty.bottom + scrollY); 14740 } 14741 } 14742 14743 /** 14744 * Schedules an action on a drawable to occur at a specified time. 14745 * 14746 * @param who the recipient of the action 14747 * @param what the action to run on the drawable 14748 * @param when the time at which the action must occur. Uses the 14749 * {@link SystemClock#uptimeMillis} timebase. 14750 */ 14751 public void scheduleDrawable(Drawable who, Runnable what, long when) { 14752 if (verifyDrawable(who) && what != null) { 14753 final long delay = when - SystemClock.uptimeMillis(); 14754 if (mAttachInfo != null) { 14755 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 14756 Choreographer.CALLBACK_ANIMATION, what, who, 14757 Choreographer.subtractFrameDelay(delay)); 14758 } else { 14759 ViewRootImpl.getRunQueue().postDelayed(what, delay); 14760 } 14761 } 14762 } 14763 14764 /** 14765 * Cancels a scheduled action on a drawable. 14766 * 14767 * @param who the recipient of the action 14768 * @param what the action to cancel 14769 */ 14770 public void unscheduleDrawable(Drawable who, Runnable what) { 14771 if (verifyDrawable(who) && what != null) { 14772 if (mAttachInfo != null) { 14773 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 14774 Choreographer.CALLBACK_ANIMATION, what, who); 14775 } else { 14776 ViewRootImpl.getRunQueue().removeCallbacks(what); 14777 } 14778 } 14779 } 14780 14781 /** 14782 * Unschedule any events associated with the given Drawable. This can be 14783 * used when selecting a new Drawable into a view, so that the previous 14784 * one is completely unscheduled. 14785 * 14786 * @param who The Drawable to unschedule. 14787 * 14788 * @see #drawableStateChanged 14789 */ 14790 public void unscheduleDrawable(Drawable who) { 14791 if (mAttachInfo != null && who != null) { 14792 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 14793 Choreographer.CALLBACK_ANIMATION, null, who); 14794 } 14795 } 14796 14797 /** 14798 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 14799 * that the View directionality can and will be resolved before its Drawables. 14800 * 14801 * Will call {@link View#onResolveDrawables} when resolution is done. 14802 * 14803 * @hide 14804 */ 14805 protected void resolveDrawables() { 14806 // Drawables resolution may need to happen before resolving the layout direction (which is 14807 // done only during the measure() call). 14808 // If the layout direction is not resolved yet, we cannot resolve the Drawables except in 14809 // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT. 14810 // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or 14811 // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout 14812 // direction to be resolved as its resolved value will be the same as its raw value. 14813 if (!isLayoutDirectionResolved() && 14814 getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) { 14815 return; 14816 } 14817 14818 final int layoutDirection = isLayoutDirectionResolved() ? 14819 getLayoutDirection() : getRawLayoutDirection(); 14820 14821 if (mBackground != null) { 14822 mBackground.setLayoutDirection(layoutDirection); 14823 } 14824 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED; 14825 onResolveDrawables(layoutDirection); 14826 } 14827 14828 /** 14829 * Called when layout direction has been resolved. 14830 * 14831 * The default implementation does nothing. 14832 * 14833 * @param layoutDirection The resolved layout direction. 14834 * 14835 * @see #LAYOUT_DIRECTION_LTR 14836 * @see #LAYOUT_DIRECTION_RTL 14837 * 14838 * @hide 14839 */ 14840 public void onResolveDrawables(int layoutDirection) { 14841 } 14842 14843 /** 14844 * @hide 14845 */ 14846 protected void resetResolvedDrawables() { 14847 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED; 14848 } 14849 14850 private boolean isDrawablesResolved() { 14851 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED; 14852 } 14853 14854 /** 14855 * If your view subclass is displaying its own Drawable objects, it should 14856 * override this function and return true for any Drawable it is 14857 * displaying. This allows animations for those drawables to be 14858 * scheduled. 14859 * 14860 * <p>Be sure to call through to the super class when overriding this 14861 * function. 14862 * 14863 * @param who The Drawable to verify. Return true if it is one you are 14864 * displaying, else return the result of calling through to the 14865 * super class. 14866 * 14867 * @return boolean If true than the Drawable is being displayed in the 14868 * view; else false and it is not allowed to animate. 14869 * 14870 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 14871 * @see #drawableStateChanged() 14872 */ 14873 protected boolean verifyDrawable(Drawable who) { 14874 return who == mBackground; 14875 } 14876 14877 /** 14878 * This function is called whenever the state of the view changes in such 14879 * a way that it impacts the state of drawables being shown. 14880 * 14881 * <p>Be sure to call through to the superclass when overriding this 14882 * function. 14883 * 14884 * @see Drawable#setState(int[]) 14885 */ 14886 protected void drawableStateChanged() { 14887 Drawable d = mBackground; 14888 if (d != null && d.isStateful()) { 14889 d.setState(getDrawableState()); 14890 } 14891 } 14892 14893 /** 14894 * Call this to force a view to update its drawable state. This will cause 14895 * drawableStateChanged to be called on this view. Views that are interested 14896 * in the new state should call getDrawableState. 14897 * 14898 * @see #drawableStateChanged 14899 * @see #getDrawableState 14900 */ 14901 public void refreshDrawableState() { 14902 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 14903 drawableStateChanged(); 14904 14905 ViewParent parent = mParent; 14906 if (parent != null) { 14907 parent.childDrawableStateChanged(this); 14908 } 14909 } 14910 14911 /** 14912 * Return an array of resource IDs of the drawable states representing the 14913 * current state of the view. 14914 * 14915 * @return The current drawable state 14916 * 14917 * @see Drawable#setState(int[]) 14918 * @see #drawableStateChanged() 14919 * @see #onCreateDrawableState(int) 14920 */ 14921 public final int[] getDrawableState() { 14922 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 14923 return mDrawableState; 14924 } else { 14925 mDrawableState = onCreateDrawableState(0); 14926 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 14927 return mDrawableState; 14928 } 14929 } 14930 14931 /** 14932 * Generate the new {@link android.graphics.drawable.Drawable} state for 14933 * this view. This is called by the view 14934 * system when the cached Drawable state is determined to be invalid. To 14935 * retrieve the current state, you should use {@link #getDrawableState}. 14936 * 14937 * @param extraSpace if non-zero, this is the number of extra entries you 14938 * would like in the returned array in which you can place your own 14939 * states. 14940 * 14941 * @return Returns an array holding the current {@link Drawable} state of 14942 * the view. 14943 * 14944 * @see #mergeDrawableStates(int[], int[]) 14945 */ 14946 protected int[] onCreateDrawableState(int extraSpace) { 14947 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 14948 mParent instanceof View) { 14949 return ((View) mParent).onCreateDrawableState(extraSpace); 14950 } 14951 14952 int[] drawableState; 14953 14954 int privateFlags = mPrivateFlags; 14955 14956 int viewStateIndex = 0; 14957 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 14958 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 14959 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 14960 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 14961 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 14962 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 14963 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 14964 HardwareRenderer.isAvailable()) { 14965 // This is set if HW acceleration is requested, even if the current 14966 // process doesn't allow it. This is just to allow app preview 14967 // windows to better match their app. 14968 viewStateIndex |= VIEW_STATE_ACCELERATED; 14969 } 14970 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 14971 14972 final int privateFlags2 = mPrivateFlags2; 14973 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 14974 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 14975 14976 drawableState = VIEW_STATE_SETS[viewStateIndex]; 14977 14978 //noinspection ConstantIfStatement 14979 if (false) { 14980 Log.i("View", "drawableStateIndex=" + viewStateIndex); 14981 Log.i("View", toString() 14982 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 14983 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 14984 + " fo=" + hasFocus() 14985 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 14986 + " wf=" + hasWindowFocus() 14987 + ": " + Arrays.toString(drawableState)); 14988 } 14989 14990 if (extraSpace == 0) { 14991 return drawableState; 14992 } 14993 14994 final int[] fullState; 14995 if (drawableState != null) { 14996 fullState = new int[drawableState.length + extraSpace]; 14997 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 14998 } else { 14999 fullState = new int[extraSpace]; 15000 } 15001 15002 return fullState; 15003 } 15004 15005 /** 15006 * Merge your own state values in <var>additionalState</var> into the base 15007 * state values <var>baseState</var> that were returned by 15008 * {@link #onCreateDrawableState(int)}. 15009 * 15010 * @param baseState The base state values returned by 15011 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 15012 * own additional state values. 15013 * 15014 * @param additionalState The additional state values you would like 15015 * added to <var>baseState</var>; this array is not modified. 15016 * 15017 * @return As a convenience, the <var>baseState</var> array you originally 15018 * passed into the function is returned. 15019 * 15020 * @see #onCreateDrawableState(int) 15021 */ 15022 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 15023 final int N = baseState.length; 15024 int i = N - 1; 15025 while (i >= 0 && baseState[i] == 0) { 15026 i--; 15027 } 15028 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 15029 return baseState; 15030 } 15031 15032 /** 15033 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 15034 * on all Drawable objects associated with this view. 15035 */ 15036 public void jumpDrawablesToCurrentState() { 15037 if (mBackground != null) { 15038 mBackground.jumpToCurrentState(); 15039 } 15040 } 15041 15042 /** 15043 * Sets the background color for this view. 15044 * @param color the color of the background 15045 */ 15046 @RemotableViewMethod 15047 public void setBackgroundColor(int color) { 15048 if (mBackground instanceof ColorDrawable) { 15049 ((ColorDrawable) mBackground.mutate()).setColor(color); 15050 computeOpaqueFlags(); 15051 mBackgroundResource = 0; 15052 } else { 15053 setBackground(new ColorDrawable(color)); 15054 } 15055 } 15056 15057 /** 15058 * Set the background to a given resource. The resource should refer to 15059 * a Drawable object or 0 to remove the background. 15060 * @param resid The identifier of the resource. 15061 * 15062 * @attr ref android.R.styleable#View_background 15063 */ 15064 @RemotableViewMethod 15065 public void setBackgroundResource(int resid) { 15066 if (resid != 0 && resid == mBackgroundResource) { 15067 return; 15068 } 15069 15070 Drawable d= null; 15071 if (resid != 0) { 15072 d = mResources.getDrawable(resid); 15073 } 15074 setBackground(d); 15075 15076 mBackgroundResource = resid; 15077 } 15078 15079 /** 15080 * Set the background to a given Drawable, or remove the background. If the 15081 * background has padding, this View's padding is set to the background's 15082 * padding. However, when a background is removed, this View's padding isn't 15083 * touched. If setting the padding is desired, please use 15084 * {@link #setPadding(int, int, int, int)}. 15085 * 15086 * @param background The Drawable to use as the background, or null to remove the 15087 * background 15088 */ 15089 public void setBackground(Drawable background) { 15090 //noinspection deprecation 15091 setBackgroundDrawable(background); 15092 } 15093 15094 /** 15095 * @deprecated use {@link #setBackground(Drawable)} instead 15096 */ 15097 @Deprecated 15098 public void setBackgroundDrawable(Drawable background) { 15099 computeOpaqueFlags(); 15100 15101 if (background == mBackground) { 15102 return; 15103 } 15104 15105 boolean requestLayout = false; 15106 15107 mBackgroundResource = 0; 15108 15109 /* 15110 * Regardless of whether we're setting a new background or not, we want 15111 * to clear the previous drawable. 15112 */ 15113 if (mBackground != null) { 15114 mBackground.setCallback(null); 15115 unscheduleDrawable(mBackground); 15116 } 15117 15118 if (background != null) { 15119 Rect padding = sThreadLocal.get(); 15120 if (padding == null) { 15121 padding = new Rect(); 15122 sThreadLocal.set(padding); 15123 } 15124 resetResolvedDrawables(); 15125 background.setLayoutDirection(getLayoutDirection()); 15126 if (background.getPadding(padding)) { 15127 resetResolvedPadding(); 15128 switch (background.getLayoutDirection()) { 15129 case LAYOUT_DIRECTION_RTL: 15130 mUserPaddingLeftInitial = padding.right; 15131 mUserPaddingRightInitial = padding.left; 15132 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 15133 break; 15134 case LAYOUT_DIRECTION_LTR: 15135 default: 15136 mUserPaddingLeftInitial = padding.left; 15137 mUserPaddingRightInitial = padding.right; 15138 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 15139 } 15140 } 15141 15142 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 15143 // if it has a different minimum size, we should layout again 15144 if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() || 15145 mBackground.getMinimumWidth() != background.getMinimumWidth()) { 15146 requestLayout = true; 15147 } 15148 15149 background.setCallback(this); 15150 if (background.isStateful()) { 15151 background.setState(getDrawableState()); 15152 } 15153 background.setVisible(getVisibility() == VISIBLE, false); 15154 mBackground = background; 15155 15156 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 15157 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 15158 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 15159 requestLayout = true; 15160 } 15161 } else { 15162 /* Remove the background */ 15163 mBackground = null; 15164 15165 if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) { 15166 /* 15167 * This view ONLY drew the background before and we're removing 15168 * the background, so now it won't draw anything 15169 * (hence we SKIP_DRAW) 15170 */ 15171 mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND; 15172 mPrivateFlags |= PFLAG_SKIP_DRAW; 15173 } 15174 15175 /* 15176 * When the background is set, we try to apply its padding to this 15177 * View. When the background is removed, we don't touch this View's 15178 * padding. This is noted in the Javadocs. Hence, we don't need to 15179 * requestLayout(), the invalidate() below is sufficient. 15180 */ 15181 15182 // The old background's minimum size could have affected this 15183 // View's layout, so let's requestLayout 15184 requestLayout = true; 15185 } 15186 15187 computeOpaqueFlags(); 15188 15189 if (requestLayout) { 15190 requestLayout(); 15191 } 15192 15193 mBackgroundSizeChanged = true; 15194 invalidate(true); 15195 } 15196 15197 /** 15198 * Gets the background drawable 15199 * 15200 * @return The drawable used as the background for this view, if any. 15201 * 15202 * @see #setBackground(Drawable) 15203 * 15204 * @attr ref android.R.styleable#View_background 15205 */ 15206 public Drawable getBackground() { 15207 return mBackground; 15208 } 15209 15210 /** 15211 * Sets the padding. The view may add on the space required to display 15212 * the scrollbars, depending on the style and visibility of the scrollbars. 15213 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 15214 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 15215 * from the values set in this call. 15216 * 15217 * @attr ref android.R.styleable#View_padding 15218 * @attr ref android.R.styleable#View_paddingBottom 15219 * @attr ref android.R.styleable#View_paddingLeft 15220 * @attr ref android.R.styleable#View_paddingRight 15221 * @attr ref android.R.styleable#View_paddingTop 15222 * @param left the left padding in pixels 15223 * @param top the top padding in pixels 15224 * @param right the right padding in pixels 15225 * @param bottom the bottom padding in pixels 15226 */ 15227 public void setPadding(int left, int top, int right, int bottom) { 15228 resetResolvedPadding(); 15229 15230 mUserPaddingStart = UNDEFINED_PADDING; 15231 mUserPaddingEnd = UNDEFINED_PADDING; 15232 15233 mUserPaddingLeftInitial = left; 15234 mUserPaddingRightInitial = right; 15235 15236 internalSetPadding(left, top, right, bottom); 15237 } 15238 15239 /** 15240 * @hide 15241 */ 15242 protected void internalSetPadding(int left, int top, int right, int bottom) { 15243 mUserPaddingLeft = left; 15244 mUserPaddingRight = right; 15245 mUserPaddingBottom = bottom; 15246 15247 final int viewFlags = mViewFlags; 15248 boolean changed = false; 15249 15250 // Common case is there are no scroll bars. 15251 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 15252 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 15253 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 15254 ? 0 : getVerticalScrollbarWidth(); 15255 switch (mVerticalScrollbarPosition) { 15256 case SCROLLBAR_POSITION_DEFAULT: 15257 if (isLayoutRtl()) { 15258 left += offset; 15259 } else { 15260 right += offset; 15261 } 15262 break; 15263 case SCROLLBAR_POSITION_RIGHT: 15264 right += offset; 15265 break; 15266 case SCROLLBAR_POSITION_LEFT: 15267 left += offset; 15268 break; 15269 } 15270 } 15271 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 15272 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 15273 ? 0 : getHorizontalScrollbarHeight(); 15274 } 15275 } 15276 15277 if (mPaddingLeft != left) { 15278 changed = true; 15279 mPaddingLeft = left; 15280 } 15281 if (mPaddingTop != top) { 15282 changed = true; 15283 mPaddingTop = top; 15284 } 15285 if (mPaddingRight != right) { 15286 changed = true; 15287 mPaddingRight = right; 15288 } 15289 if (mPaddingBottom != bottom) { 15290 changed = true; 15291 mPaddingBottom = bottom; 15292 } 15293 15294 if (changed) { 15295 requestLayout(); 15296 } 15297 } 15298 15299 /** 15300 * Sets the relative padding. The view may add on the space required to display 15301 * the scrollbars, depending on the style and visibility of the scrollbars. 15302 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 15303 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 15304 * from the values set in this call. 15305 * 15306 * @attr ref android.R.styleable#View_padding 15307 * @attr ref android.R.styleable#View_paddingBottom 15308 * @attr ref android.R.styleable#View_paddingStart 15309 * @attr ref android.R.styleable#View_paddingEnd 15310 * @attr ref android.R.styleable#View_paddingTop 15311 * @param start the start padding in pixels 15312 * @param top the top padding in pixels 15313 * @param end the end padding in pixels 15314 * @param bottom the bottom padding in pixels 15315 */ 15316 public void setPaddingRelative(int start, int top, int end, int bottom) { 15317 resetResolvedPadding(); 15318 15319 mUserPaddingStart = start; 15320 mUserPaddingEnd = end; 15321 15322 switch(getLayoutDirection()) { 15323 case LAYOUT_DIRECTION_RTL: 15324 mUserPaddingLeftInitial = end; 15325 mUserPaddingRightInitial = start; 15326 internalSetPadding(end, top, start, bottom); 15327 break; 15328 case LAYOUT_DIRECTION_LTR: 15329 default: 15330 mUserPaddingLeftInitial = start; 15331 mUserPaddingRightInitial = end; 15332 internalSetPadding(start, top, end, bottom); 15333 } 15334 } 15335 15336 /** 15337 * Returns the top padding of this view. 15338 * 15339 * @return the top padding in pixels 15340 */ 15341 public int getPaddingTop() { 15342 return mPaddingTop; 15343 } 15344 15345 /** 15346 * Returns the bottom padding of this view. If there are inset and enabled 15347 * scrollbars, this value may include the space required to display the 15348 * scrollbars as well. 15349 * 15350 * @return the bottom padding in pixels 15351 */ 15352 public int getPaddingBottom() { 15353 return mPaddingBottom; 15354 } 15355 15356 /** 15357 * Returns the left padding of this view. If there are inset and enabled 15358 * scrollbars, this value may include the space required to display the 15359 * scrollbars as well. 15360 * 15361 * @return the left padding in pixels 15362 */ 15363 public int getPaddingLeft() { 15364 if (!isPaddingResolved()) { 15365 resolvePadding(); 15366 } 15367 return mPaddingLeft; 15368 } 15369 15370 /** 15371 * Returns the start padding of this view depending on its resolved layout direction. 15372 * If there are inset and enabled scrollbars, this value may include the space 15373 * required to display the scrollbars as well. 15374 * 15375 * @return the start padding in pixels 15376 */ 15377 public int getPaddingStart() { 15378 if (!isPaddingResolved()) { 15379 resolvePadding(); 15380 } 15381 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 15382 mPaddingRight : mPaddingLeft; 15383 } 15384 15385 /** 15386 * Returns the right padding of this view. If there are inset and enabled 15387 * scrollbars, this value may include the space required to display the 15388 * scrollbars as well. 15389 * 15390 * @return the right padding in pixels 15391 */ 15392 public int getPaddingRight() { 15393 if (!isPaddingResolved()) { 15394 resolvePadding(); 15395 } 15396 return mPaddingRight; 15397 } 15398 15399 /** 15400 * Returns the end padding of this view depending on its resolved layout direction. 15401 * If there are inset and enabled scrollbars, this value may include the space 15402 * required to display the scrollbars as well. 15403 * 15404 * @return the end padding in pixels 15405 */ 15406 public int getPaddingEnd() { 15407 if (!isPaddingResolved()) { 15408 resolvePadding(); 15409 } 15410 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 15411 mPaddingLeft : mPaddingRight; 15412 } 15413 15414 /** 15415 * Return if the padding as been set thru relative values 15416 * {@link #setPaddingRelative(int, int, int, int)} or thru 15417 * @attr ref android.R.styleable#View_paddingStart or 15418 * @attr ref android.R.styleable#View_paddingEnd 15419 * 15420 * @return true if the padding is relative or false if it is not. 15421 */ 15422 public boolean isPaddingRelative() { 15423 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 15424 } 15425 15426 Insets computeOpticalInsets() { 15427 return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets(); 15428 } 15429 15430 /** 15431 * @hide 15432 */ 15433 public void resetPaddingToInitialValues() { 15434 if (isRtlCompatibilityMode()) { 15435 mPaddingLeft = mUserPaddingLeftInitial; 15436 mPaddingRight = mUserPaddingRightInitial; 15437 return; 15438 } 15439 if (isLayoutRtl()) { 15440 mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial; 15441 mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial; 15442 } else { 15443 mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial; 15444 mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial; 15445 } 15446 } 15447 15448 /** 15449 * @hide 15450 */ 15451 public Insets getOpticalInsets() { 15452 if (mLayoutInsets == null) { 15453 mLayoutInsets = computeOpticalInsets(); 15454 } 15455 return mLayoutInsets; 15456 } 15457 15458 /** 15459 * Changes the selection state of this view. A view can be selected or not. 15460 * Note that selection is not the same as focus. Views are typically 15461 * selected in the context of an AdapterView like ListView or GridView; 15462 * the selected view is the view that is highlighted. 15463 * 15464 * @param selected true if the view must be selected, false otherwise 15465 */ 15466 public void setSelected(boolean selected) { 15467 //noinspection DoubleNegation 15468 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 15469 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 15470 if (!selected) resetPressedState(); 15471 invalidate(true); 15472 refreshDrawableState(); 15473 dispatchSetSelected(selected); 15474 notifyViewAccessibilityStateChangedIfNeeded(); 15475 } 15476 } 15477 15478 /** 15479 * Dispatch setSelected to all of this View's children. 15480 * 15481 * @see #setSelected(boolean) 15482 * 15483 * @param selected The new selected state 15484 */ 15485 protected void dispatchSetSelected(boolean selected) { 15486 } 15487 15488 /** 15489 * Indicates the selection state of this view. 15490 * 15491 * @return true if the view is selected, false otherwise 15492 */ 15493 @ViewDebug.ExportedProperty 15494 public boolean isSelected() { 15495 return (mPrivateFlags & PFLAG_SELECTED) != 0; 15496 } 15497 15498 /** 15499 * Changes the activated state of this view. A view can be activated or not. 15500 * Note that activation is not the same as selection. Selection is 15501 * a transient property, representing the view (hierarchy) the user is 15502 * currently interacting with. Activation is a longer-term state that the 15503 * user can move views in and out of. For example, in a list view with 15504 * single or multiple selection enabled, the views in the current selection 15505 * set are activated. (Um, yeah, we are deeply sorry about the terminology 15506 * here.) The activated state is propagated down to children of the view it 15507 * is set on. 15508 * 15509 * @param activated true if the view must be activated, false otherwise 15510 */ 15511 public void setActivated(boolean activated) { 15512 //noinspection DoubleNegation 15513 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 15514 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 15515 invalidate(true); 15516 refreshDrawableState(); 15517 dispatchSetActivated(activated); 15518 } 15519 } 15520 15521 /** 15522 * Dispatch setActivated to all of this View's children. 15523 * 15524 * @see #setActivated(boolean) 15525 * 15526 * @param activated The new activated state 15527 */ 15528 protected void dispatchSetActivated(boolean activated) { 15529 } 15530 15531 /** 15532 * Indicates the activation state of this view. 15533 * 15534 * @return true if the view is activated, false otherwise 15535 */ 15536 @ViewDebug.ExportedProperty 15537 public boolean isActivated() { 15538 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 15539 } 15540 15541 /** 15542 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 15543 * observer can be used to get notifications when global events, like 15544 * layout, happen. 15545 * 15546 * The returned ViewTreeObserver observer is not guaranteed to remain 15547 * valid for the lifetime of this View. If the caller of this method keeps 15548 * a long-lived reference to ViewTreeObserver, it should always check for 15549 * the return value of {@link ViewTreeObserver#isAlive()}. 15550 * 15551 * @return The ViewTreeObserver for this view's hierarchy. 15552 */ 15553 public ViewTreeObserver getViewTreeObserver() { 15554 if (mAttachInfo != null) { 15555 return mAttachInfo.mTreeObserver; 15556 } 15557 if (mFloatingTreeObserver == null) { 15558 mFloatingTreeObserver = new ViewTreeObserver(); 15559 } 15560 return mFloatingTreeObserver; 15561 } 15562 15563 /** 15564 * <p>Finds the topmost view in the current view hierarchy.</p> 15565 * 15566 * @return the topmost view containing this view 15567 */ 15568 public View getRootView() { 15569 if (mAttachInfo != null) { 15570 final View v = mAttachInfo.mRootView; 15571 if (v != null) { 15572 return v; 15573 } 15574 } 15575 15576 View parent = this; 15577 15578 while (parent.mParent != null && parent.mParent instanceof View) { 15579 parent = (View) parent.mParent; 15580 } 15581 15582 return parent; 15583 } 15584 15585 /** 15586 * Transforms a motion event from view-local coordinates to on-screen 15587 * coordinates. 15588 * 15589 * @param ev the view-local motion event 15590 * @return false if the transformation could not be applied 15591 * @hide 15592 */ 15593 public boolean toGlobalMotionEvent(MotionEvent ev) { 15594 final AttachInfo info = mAttachInfo; 15595 if (info == null) { 15596 return false; 15597 } 15598 15599 transformMotionEventToGlobal(ev); 15600 ev.offsetLocation(info.mWindowLeft, info.mWindowTop); 15601 return true; 15602 } 15603 15604 /** 15605 * Transforms a motion event from on-screen coordinates to view-local 15606 * coordinates. 15607 * 15608 * @param ev the on-screen motion event 15609 * @return false if the transformation could not be applied 15610 * @hide 15611 */ 15612 public boolean toLocalMotionEvent(MotionEvent ev) { 15613 final AttachInfo info = mAttachInfo; 15614 if (info == null) { 15615 return false; 15616 } 15617 15618 ev.offsetLocation(-info.mWindowLeft, -info.mWindowTop); 15619 transformMotionEventToLocal(ev); 15620 return true; 15621 } 15622 15623 /** 15624 * Recursive helper method that applies transformations in post-order. 15625 * 15626 * @param ev the on-screen motion event 15627 */ 15628 private void transformMotionEventToLocal(MotionEvent ev) { 15629 final ViewParent parent = mParent; 15630 if (parent instanceof View) { 15631 final View vp = (View) parent; 15632 vp.transformMotionEventToLocal(ev); 15633 ev.offsetLocation(vp.mScrollX, vp.mScrollY); 15634 } else if (parent instanceof ViewRootImpl) { 15635 final ViewRootImpl vr = (ViewRootImpl) parent; 15636 ev.offsetLocation(0, vr.mCurScrollY); 15637 } 15638 15639 ev.offsetLocation(-mLeft, -mTop); 15640 15641 if (!hasIdentityMatrix()) { 15642 ev.transform(getInverseMatrix()); 15643 } 15644 } 15645 15646 /** 15647 * Recursive helper method that applies transformations in pre-order. 15648 * 15649 * @param ev the on-screen motion event 15650 */ 15651 private void transformMotionEventToGlobal(MotionEvent ev) { 15652 if (!hasIdentityMatrix()) { 15653 ev.transform(getMatrix()); 15654 } 15655 15656 ev.offsetLocation(mLeft, mTop); 15657 15658 final ViewParent parent = mParent; 15659 if (parent instanceof View) { 15660 final View vp = (View) parent; 15661 ev.offsetLocation(-vp.mScrollX, -vp.mScrollY); 15662 vp.transformMotionEventToGlobal(ev); 15663 } else if (parent instanceof ViewRootImpl) { 15664 final ViewRootImpl vr = (ViewRootImpl) parent; 15665 ev.offsetLocation(0, -vr.mCurScrollY); 15666 } 15667 } 15668 15669 /** 15670 * <p>Computes the coordinates of this view on the screen. The argument 15671 * must be an array of two integers. After the method returns, the array 15672 * contains the x and y location in that order.</p> 15673 * 15674 * @param location an array of two integers in which to hold the coordinates 15675 */ 15676 public void getLocationOnScreen(int[] location) { 15677 getLocationInWindow(location); 15678 15679 final AttachInfo info = mAttachInfo; 15680 if (info != null) { 15681 location[0] += info.mWindowLeft; 15682 location[1] += info.mWindowTop; 15683 } 15684 } 15685 15686 /** 15687 * <p>Computes the coordinates of this view in its window. The argument 15688 * must be an array of two integers. After the method returns, the array 15689 * contains the x and y location in that order.</p> 15690 * 15691 * @param location an array of two integers in which to hold the coordinates 15692 */ 15693 public void getLocationInWindow(int[] location) { 15694 if (location == null || location.length < 2) { 15695 throw new IllegalArgumentException("location must be an array of two integers"); 15696 } 15697 15698 if (mAttachInfo == null) { 15699 // When the view is not attached to a window, this method does not make sense 15700 location[0] = location[1] = 0; 15701 return; 15702 } 15703 15704 float[] position = mAttachInfo.mTmpTransformLocation; 15705 position[0] = position[1] = 0.0f; 15706 15707 if (!hasIdentityMatrix()) { 15708 getMatrix().mapPoints(position); 15709 } 15710 15711 position[0] += mLeft; 15712 position[1] += mTop; 15713 15714 ViewParent viewParent = mParent; 15715 while (viewParent instanceof View) { 15716 final View view = (View) viewParent; 15717 15718 position[0] -= view.mScrollX; 15719 position[1] -= view.mScrollY; 15720 15721 if (!view.hasIdentityMatrix()) { 15722 view.getMatrix().mapPoints(position); 15723 } 15724 15725 position[0] += view.mLeft; 15726 position[1] += view.mTop; 15727 15728 viewParent = view.mParent; 15729 } 15730 15731 if (viewParent instanceof ViewRootImpl) { 15732 // *cough* 15733 final ViewRootImpl vr = (ViewRootImpl) viewParent; 15734 position[1] -= vr.mCurScrollY; 15735 } 15736 15737 location[0] = (int) (position[0] + 0.5f); 15738 location[1] = (int) (position[1] + 0.5f); 15739 } 15740 15741 /** 15742 * {@hide} 15743 * @param id the id of the view to be found 15744 * @return the view of the specified id, null if cannot be found 15745 */ 15746 protected View findViewTraversal(int id) { 15747 if (id == mID) { 15748 return this; 15749 } 15750 return null; 15751 } 15752 15753 /** 15754 * {@hide} 15755 * @param tag the tag of the view to be found 15756 * @return the view of specified tag, null if cannot be found 15757 */ 15758 protected View findViewWithTagTraversal(Object tag) { 15759 if (tag != null && tag.equals(mTag)) { 15760 return this; 15761 } 15762 return null; 15763 } 15764 15765 /** 15766 * {@hide} 15767 * @param predicate The predicate to evaluate. 15768 * @param childToSkip If not null, ignores this child during the recursive traversal. 15769 * @return The first view that matches the predicate or null. 15770 */ 15771 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 15772 if (predicate.apply(this)) { 15773 return this; 15774 } 15775 return null; 15776 } 15777 15778 /** 15779 * Look for a child view with the given id. If this view has the given 15780 * id, return this view. 15781 * 15782 * @param id The id to search for. 15783 * @return The view that has the given id in the hierarchy or null 15784 */ 15785 public final View findViewById(int id) { 15786 if (id < 0) { 15787 return null; 15788 } 15789 return findViewTraversal(id); 15790 } 15791 15792 /** 15793 * Finds a view by its unuque and stable accessibility id. 15794 * 15795 * @param accessibilityId The searched accessibility id. 15796 * @return The found view. 15797 */ 15798 final View findViewByAccessibilityId(int accessibilityId) { 15799 if (accessibilityId < 0) { 15800 return null; 15801 } 15802 return findViewByAccessibilityIdTraversal(accessibilityId); 15803 } 15804 15805 /** 15806 * Performs the traversal to find a view by its unuque and stable accessibility id. 15807 * 15808 * <strong>Note:</strong>This method does not stop at the root namespace 15809 * boundary since the user can touch the screen at an arbitrary location 15810 * potentially crossing the root namespace bounday which will send an 15811 * accessibility event to accessibility services and they should be able 15812 * to obtain the event source. Also accessibility ids are guaranteed to be 15813 * unique in the window. 15814 * 15815 * @param accessibilityId The accessibility id. 15816 * @return The found view. 15817 * 15818 * @hide 15819 */ 15820 public View findViewByAccessibilityIdTraversal(int accessibilityId) { 15821 if (getAccessibilityViewId() == accessibilityId) { 15822 return this; 15823 } 15824 return null; 15825 } 15826 15827 /** 15828 * Look for a child view with the given tag. If this view has the given 15829 * tag, return this view. 15830 * 15831 * @param tag The tag to search for, using "tag.equals(getTag())". 15832 * @return The View that has the given tag in the hierarchy or null 15833 */ 15834 public final View findViewWithTag(Object tag) { 15835 if (tag == null) { 15836 return null; 15837 } 15838 return findViewWithTagTraversal(tag); 15839 } 15840 15841 /** 15842 * {@hide} 15843 * Look for a child view that matches the specified predicate. 15844 * If this view matches the predicate, return this view. 15845 * 15846 * @param predicate The predicate to evaluate. 15847 * @return The first view that matches the predicate or null. 15848 */ 15849 public final View findViewByPredicate(Predicate<View> predicate) { 15850 return findViewByPredicateTraversal(predicate, null); 15851 } 15852 15853 /** 15854 * {@hide} 15855 * Look for a child view that matches the specified predicate, 15856 * starting with the specified view and its descendents and then 15857 * recusively searching the ancestors and siblings of that view 15858 * until this view is reached. 15859 * 15860 * This method is useful in cases where the predicate does not match 15861 * a single unique view (perhaps multiple views use the same id) 15862 * and we are trying to find the view that is "closest" in scope to the 15863 * starting view. 15864 * 15865 * @param start The view to start from. 15866 * @param predicate The predicate to evaluate. 15867 * @return The first view that matches the predicate or null. 15868 */ 15869 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 15870 View childToSkip = null; 15871 for (;;) { 15872 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 15873 if (view != null || start == this) { 15874 return view; 15875 } 15876 15877 ViewParent parent = start.getParent(); 15878 if (parent == null || !(parent instanceof View)) { 15879 return null; 15880 } 15881 15882 childToSkip = start; 15883 start = (View) parent; 15884 } 15885 } 15886 15887 /** 15888 * Sets the identifier for this view. The identifier does not have to be 15889 * unique in this view's hierarchy. The identifier should be a positive 15890 * number. 15891 * 15892 * @see #NO_ID 15893 * @see #getId() 15894 * @see #findViewById(int) 15895 * 15896 * @param id a number used to identify the view 15897 * 15898 * @attr ref android.R.styleable#View_id 15899 */ 15900 public void setId(int id) { 15901 mID = id; 15902 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 15903 mID = generateViewId(); 15904 } 15905 } 15906 15907 /** 15908 * {@hide} 15909 * 15910 * @param isRoot true if the view belongs to the root namespace, false 15911 * otherwise 15912 */ 15913 public void setIsRootNamespace(boolean isRoot) { 15914 if (isRoot) { 15915 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 15916 } else { 15917 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 15918 } 15919 } 15920 15921 /** 15922 * {@hide} 15923 * 15924 * @return true if the view belongs to the root namespace, false otherwise 15925 */ 15926 public boolean isRootNamespace() { 15927 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 15928 } 15929 15930 /** 15931 * Returns this view's identifier. 15932 * 15933 * @return a positive integer used to identify the view or {@link #NO_ID} 15934 * if the view has no ID 15935 * 15936 * @see #setId(int) 15937 * @see #findViewById(int) 15938 * @attr ref android.R.styleable#View_id 15939 */ 15940 @ViewDebug.CapturedViewProperty 15941 public int getId() { 15942 return mID; 15943 } 15944 15945 /** 15946 * Returns this view's tag. 15947 * 15948 * @return the Object stored in this view as a tag 15949 * 15950 * @see #setTag(Object) 15951 * @see #getTag(int) 15952 */ 15953 @ViewDebug.ExportedProperty 15954 public Object getTag() { 15955 return mTag; 15956 } 15957 15958 /** 15959 * Sets the tag associated with this view. A tag can be used to mark 15960 * a view in its hierarchy and does not have to be unique within the 15961 * hierarchy. Tags can also be used to store data within a view without 15962 * resorting to another data structure. 15963 * 15964 * @param tag an Object to tag the view with 15965 * 15966 * @see #getTag() 15967 * @see #setTag(int, Object) 15968 */ 15969 public void setTag(final Object tag) { 15970 mTag = tag; 15971 } 15972 15973 /** 15974 * Returns the tag associated with this view and the specified key. 15975 * 15976 * @param key The key identifying the tag 15977 * 15978 * @return the Object stored in this view as a tag 15979 * 15980 * @see #setTag(int, Object) 15981 * @see #getTag() 15982 */ 15983 public Object getTag(int key) { 15984 if (mKeyedTags != null) return mKeyedTags.get(key); 15985 return null; 15986 } 15987 15988 /** 15989 * Sets a tag associated with this view and a key. A tag can be used 15990 * to mark a view in its hierarchy and does not have to be unique within 15991 * the hierarchy. Tags can also be used to store data within a view 15992 * without resorting to another data structure. 15993 * 15994 * The specified key should be an id declared in the resources of the 15995 * application to ensure it is unique (see the <a 15996 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 15997 * Keys identified as belonging to 15998 * the Android framework or not associated with any package will cause 15999 * an {@link IllegalArgumentException} to be thrown. 16000 * 16001 * @param key The key identifying the tag 16002 * @param tag An Object to tag the view with 16003 * 16004 * @throws IllegalArgumentException If they specified key is not valid 16005 * 16006 * @see #setTag(Object) 16007 * @see #getTag(int) 16008 */ 16009 public void setTag(int key, final Object tag) { 16010 // If the package id is 0x00 or 0x01, it's either an undefined package 16011 // or a framework id 16012 if ((key >>> 24) < 2) { 16013 throw new IllegalArgumentException("The key must be an application-specific " 16014 + "resource id."); 16015 } 16016 16017 setKeyedTag(key, tag); 16018 } 16019 16020 /** 16021 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 16022 * framework id. 16023 * 16024 * @hide 16025 */ 16026 public void setTagInternal(int key, Object tag) { 16027 if ((key >>> 24) != 0x1) { 16028 throw new IllegalArgumentException("The key must be a framework-specific " 16029 + "resource id."); 16030 } 16031 16032 setKeyedTag(key, tag); 16033 } 16034 16035 private void setKeyedTag(int key, Object tag) { 16036 if (mKeyedTags == null) { 16037 mKeyedTags = new SparseArray<Object>(2); 16038 } 16039 16040 mKeyedTags.put(key, tag); 16041 } 16042 16043 /** 16044 * Prints information about this view in the log output, with the tag 16045 * {@link #VIEW_LOG_TAG}. 16046 * 16047 * @hide 16048 */ 16049 public void debug() { 16050 debug(0); 16051 } 16052 16053 /** 16054 * Prints information about this view in the log output, with the tag 16055 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 16056 * indentation defined by the <code>depth</code>. 16057 * 16058 * @param depth the indentation level 16059 * 16060 * @hide 16061 */ 16062 protected void debug(int depth) { 16063 String output = debugIndent(depth - 1); 16064 16065 output += "+ " + this; 16066 int id = getId(); 16067 if (id != -1) { 16068 output += " (id=" + id + ")"; 16069 } 16070 Object tag = getTag(); 16071 if (tag != null) { 16072 output += " (tag=" + tag + ")"; 16073 } 16074 Log.d(VIEW_LOG_TAG, output); 16075 16076 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 16077 output = debugIndent(depth) + " FOCUSED"; 16078 Log.d(VIEW_LOG_TAG, output); 16079 } 16080 16081 output = debugIndent(depth); 16082 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 16083 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 16084 + "} "; 16085 Log.d(VIEW_LOG_TAG, output); 16086 16087 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 16088 || mPaddingBottom != 0) { 16089 output = debugIndent(depth); 16090 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 16091 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 16092 Log.d(VIEW_LOG_TAG, output); 16093 } 16094 16095 output = debugIndent(depth); 16096 output += "mMeasureWidth=" + mMeasuredWidth + 16097 " mMeasureHeight=" + mMeasuredHeight; 16098 Log.d(VIEW_LOG_TAG, output); 16099 16100 output = debugIndent(depth); 16101 if (mLayoutParams == null) { 16102 output += "BAD! no layout params"; 16103 } else { 16104 output = mLayoutParams.debug(output); 16105 } 16106 Log.d(VIEW_LOG_TAG, output); 16107 16108 output = debugIndent(depth); 16109 output += "flags={"; 16110 output += View.printFlags(mViewFlags); 16111 output += "}"; 16112 Log.d(VIEW_LOG_TAG, output); 16113 16114 output = debugIndent(depth); 16115 output += "privateFlags={"; 16116 output += View.printPrivateFlags(mPrivateFlags); 16117 output += "}"; 16118 Log.d(VIEW_LOG_TAG, output); 16119 } 16120 16121 /** 16122 * Creates a string of whitespaces used for indentation. 16123 * 16124 * @param depth the indentation level 16125 * @return a String containing (depth * 2 + 3) * 2 white spaces 16126 * 16127 * @hide 16128 */ 16129 protected static String debugIndent(int depth) { 16130 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 16131 for (int i = 0; i < (depth * 2) + 3; i++) { 16132 spaces.append(' ').append(' '); 16133 } 16134 return spaces.toString(); 16135 } 16136 16137 /** 16138 * <p>Return the offset of the widget's text baseline from the widget's top 16139 * boundary. If this widget does not support baseline alignment, this 16140 * method returns -1. </p> 16141 * 16142 * @return the offset of the baseline within the widget's bounds or -1 16143 * if baseline alignment is not supported 16144 */ 16145 @ViewDebug.ExportedProperty(category = "layout") 16146 public int getBaseline() { 16147 return -1; 16148 } 16149 16150 /** 16151 * Returns whether the view hierarchy is currently undergoing a layout pass. This 16152 * information is useful to avoid situations such as calling {@link #requestLayout()} during 16153 * a layout pass. 16154 * 16155 * @return whether the view hierarchy is currently undergoing a layout pass 16156 */ 16157 public boolean isInLayout() { 16158 ViewRootImpl viewRoot = getViewRootImpl(); 16159 return (viewRoot != null && viewRoot.isInLayout()); 16160 } 16161 16162 /** 16163 * Call this when something has changed which has invalidated the 16164 * layout of this view. This will schedule a layout pass of the view 16165 * tree. This should not be called while the view hierarchy is currently in a layout 16166 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 16167 * end of the current layout pass (and then layout will run again) or after the current 16168 * frame is drawn and the next layout occurs. 16169 * 16170 * <p>Subclasses which override this method should call the superclass method to 16171 * handle possible request-during-layout errors correctly.</p> 16172 */ 16173 public void requestLayout() { 16174 if (mMeasureCache != null) mMeasureCache.clear(); 16175 16176 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) { 16177 // Only trigger request-during-layout logic if this is the view requesting it, 16178 // not the views in its parent hierarchy 16179 ViewRootImpl viewRoot = getViewRootImpl(); 16180 if (viewRoot != null && viewRoot.isInLayout()) { 16181 if (!viewRoot.requestLayoutDuringLayout(this)) { 16182 return; 16183 } 16184 } 16185 mAttachInfo.mViewRequestingLayout = this; 16186 } 16187 16188 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 16189 mPrivateFlags |= PFLAG_INVALIDATED; 16190 16191 if (mParent != null && !mParent.isLayoutRequested()) { 16192 mParent.requestLayout(); 16193 } 16194 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) { 16195 mAttachInfo.mViewRequestingLayout = null; 16196 } 16197 } 16198 16199 /** 16200 * Forces this view to be laid out during the next layout pass. 16201 * This method does not call requestLayout() or forceLayout() 16202 * on the parent. 16203 */ 16204 public void forceLayout() { 16205 if (mMeasureCache != null) mMeasureCache.clear(); 16206 16207 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 16208 mPrivateFlags |= PFLAG_INVALIDATED; 16209 } 16210 16211 /** 16212 * <p> 16213 * This is called to find out how big a view should be. The parent 16214 * supplies constraint information in the width and height parameters. 16215 * </p> 16216 * 16217 * <p> 16218 * The actual measurement work of a view is performed in 16219 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 16220 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 16221 * </p> 16222 * 16223 * 16224 * @param widthMeasureSpec Horizontal space requirements as imposed by the 16225 * parent 16226 * @param heightMeasureSpec Vertical space requirements as imposed by the 16227 * parent 16228 * 16229 * @see #onMeasure(int, int) 16230 */ 16231 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 16232 boolean optical = isLayoutModeOptical(this); 16233 if (optical != isLayoutModeOptical(mParent)) { 16234 Insets insets = getOpticalInsets(); 16235 int oWidth = insets.left + insets.right; 16236 int oHeight = insets.top + insets.bottom; 16237 widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth); 16238 heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight); 16239 } 16240 16241 // Suppress sign extension for the low bytes 16242 long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL; 16243 if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2); 16244 16245 if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT || 16246 widthMeasureSpec != mOldWidthMeasureSpec || 16247 heightMeasureSpec != mOldHeightMeasureSpec) { 16248 16249 // first clears the measured dimension flag 16250 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 16251 16252 resolveRtlPropertiesIfNeeded(); 16253 16254 int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 : 16255 mMeasureCache.indexOfKey(key); 16256 if (cacheIndex < 0) { 16257 // measure ourselves, this should set the measured dimension flag back 16258 onMeasure(widthMeasureSpec, heightMeasureSpec); 16259 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 16260 } else { 16261 long value = mMeasureCache.valueAt(cacheIndex); 16262 // Casting a long to int drops the high 32 bits, no mask needed 16263 setMeasuredDimension((int) (value >> 32), (int) value); 16264 mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 16265 } 16266 16267 // flag not set, setMeasuredDimension() was not invoked, we raise 16268 // an exception to warn the developer 16269 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 16270 throw new IllegalStateException("onMeasure() did not set the" 16271 + " measured dimension by calling" 16272 + " setMeasuredDimension()"); 16273 } 16274 16275 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 16276 } 16277 16278 mOldWidthMeasureSpec = widthMeasureSpec; 16279 mOldHeightMeasureSpec = heightMeasureSpec; 16280 16281 mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 | 16282 (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension 16283 } 16284 16285 /** 16286 * <p> 16287 * Measure the view and its content to determine the measured width and the 16288 * measured height. This method is invoked by {@link #measure(int, int)} and 16289 * should be overriden by subclasses to provide accurate and efficient 16290 * measurement of their contents. 16291 * </p> 16292 * 16293 * <p> 16294 * <strong>CONTRACT:</strong> When overriding this method, you 16295 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 16296 * measured width and height of this view. Failure to do so will trigger an 16297 * <code>IllegalStateException</code>, thrown by 16298 * {@link #measure(int, int)}. Calling the superclass' 16299 * {@link #onMeasure(int, int)} is a valid use. 16300 * </p> 16301 * 16302 * <p> 16303 * The base class implementation of measure defaults to the background size, 16304 * unless a larger size is allowed by the MeasureSpec. Subclasses should 16305 * override {@link #onMeasure(int, int)} to provide better measurements of 16306 * their content. 16307 * </p> 16308 * 16309 * <p> 16310 * If this method is overridden, it is the subclass's responsibility to make 16311 * sure the measured height and width are at least the view's minimum height 16312 * and width ({@link #getSuggestedMinimumHeight()} and 16313 * {@link #getSuggestedMinimumWidth()}). 16314 * </p> 16315 * 16316 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 16317 * The requirements are encoded with 16318 * {@link android.view.View.MeasureSpec}. 16319 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 16320 * The requirements are encoded with 16321 * {@link android.view.View.MeasureSpec}. 16322 * 16323 * @see #getMeasuredWidth() 16324 * @see #getMeasuredHeight() 16325 * @see #setMeasuredDimension(int, int) 16326 * @see #getSuggestedMinimumHeight() 16327 * @see #getSuggestedMinimumWidth() 16328 * @see android.view.View.MeasureSpec#getMode(int) 16329 * @see android.view.View.MeasureSpec#getSize(int) 16330 */ 16331 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 16332 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 16333 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 16334 } 16335 16336 /** 16337 * <p>This method must be called by {@link #onMeasure(int, int)} to store the 16338 * measured width and measured height. Failing to do so will trigger an 16339 * exception at measurement time.</p> 16340 * 16341 * @param measuredWidth The measured width of this view. May be a complex 16342 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 16343 * {@link #MEASURED_STATE_TOO_SMALL}. 16344 * @param measuredHeight The measured height of this view. May be a complex 16345 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 16346 * {@link #MEASURED_STATE_TOO_SMALL}. 16347 */ 16348 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 16349 boolean optical = isLayoutModeOptical(this); 16350 if (optical != isLayoutModeOptical(mParent)) { 16351 Insets insets = getOpticalInsets(); 16352 int opticalWidth = insets.left + insets.right; 16353 int opticalHeight = insets.top + insets.bottom; 16354 16355 measuredWidth += optical ? opticalWidth : -opticalWidth; 16356 measuredHeight += optical ? opticalHeight : -opticalHeight; 16357 } 16358 mMeasuredWidth = measuredWidth; 16359 mMeasuredHeight = measuredHeight; 16360 16361 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 16362 } 16363 16364 /** 16365 * Merge two states as returned by {@link #getMeasuredState()}. 16366 * @param curState The current state as returned from a view or the result 16367 * of combining multiple views. 16368 * @param newState The new view state to combine. 16369 * @return Returns a new integer reflecting the combination of the two 16370 * states. 16371 */ 16372 public static int combineMeasuredStates(int curState, int newState) { 16373 return curState | newState; 16374 } 16375 16376 /** 16377 * Version of {@link #resolveSizeAndState(int, int, int)} 16378 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 16379 */ 16380 public static int resolveSize(int size, int measureSpec) { 16381 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 16382 } 16383 16384 /** 16385 * Utility to reconcile a desired size and state, with constraints imposed 16386 * by a MeasureSpec. Will take the desired size, unless a different size 16387 * is imposed by the constraints. The returned value is a compound integer, 16388 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 16389 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 16390 * size is smaller than the size the view wants to be. 16391 * 16392 * @param size How big the view wants to be 16393 * @param measureSpec Constraints imposed by the parent 16394 * @return Size information bit mask as defined by 16395 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 16396 */ 16397 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 16398 int result = size; 16399 int specMode = MeasureSpec.getMode(measureSpec); 16400 int specSize = MeasureSpec.getSize(measureSpec); 16401 switch (specMode) { 16402 case MeasureSpec.UNSPECIFIED: 16403 result = size; 16404 break; 16405 case MeasureSpec.AT_MOST: 16406 if (specSize < size) { 16407 result = specSize | MEASURED_STATE_TOO_SMALL; 16408 } else { 16409 result = size; 16410 } 16411 break; 16412 case MeasureSpec.EXACTLY: 16413 result = specSize; 16414 break; 16415 } 16416 return result | (childMeasuredState&MEASURED_STATE_MASK); 16417 } 16418 16419 /** 16420 * Utility to return a default size. Uses the supplied size if the 16421 * MeasureSpec imposed no constraints. Will get larger if allowed 16422 * by the MeasureSpec. 16423 * 16424 * @param size Default size for this view 16425 * @param measureSpec Constraints imposed by the parent 16426 * @return The size this view should be. 16427 */ 16428 public static int getDefaultSize(int size, int measureSpec) { 16429 int result = size; 16430 int specMode = MeasureSpec.getMode(measureSpec); 16431 int specSize = MeasureSpec.getSize(measureSpec); 16432 16433 switch (specMode) { 16434 case MeasureSpec.UNSPECIFIED: 16435 result = size; 16436 break; 16437 case MeasureSpec.AT_MOST: 16438 case MeasureSpec.EXACTLY: 16439 result = specSize; 16440 break; 16441 } 16442 return result; 16443 } 16444 16445 /** 16446 * Returns the suggested minimum height that the view should use. This 16447 * returns the maximum of the view's minimum height 16448 * and the background's minimum height 16449 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 16450 * <p> 16451 * When being used in {@link #onMeasure(int, int)}, the caller should still 16452 * ensure the returned height is within the requirements of the parent. 16453 * 16454 * @return The suggested minimum height of the view. 16455 */ 16456 protected int getSuggestedMinimumHeight() { 16457 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 16458 16459 } 16460 16461 /** 16462 * Returns the suggested minimum width that the view should use. This 16463 * returns the maximum of the view's minimum width) 16464 * and the background's minimum width 16465 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 16466 * <p> 16467 * When being used in {@link #onMeasure(int, int)}, the caller should still 16468 * ensure the returned width is within the requirements of the parent. 16469 * 16470 * @return The suggested minimum width of the view. 16471 */ 16472 protected int getSuggestedMinimumWidth() { 16473 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 16474 } 16475 16476 /** 16477 * Returns the minimum height of the view. 16478 * 16479 * @return the minimum height the view will try to be. 16480 * 16481 * @see #setMinimumHeight(int) 16482 * 16483 * @attr ref android.R.styleable#View_minHeight 16484 */ 16485 public int getMinimumHeight() { 16486 return mMinHeight; 16487 } 16488 16489 /** 16490 * Sets the minimum height of the view. It is not guaranteed the view will 16491 * be able to achieve this minimum height (for example, if its parent layout 16492 * constrains it with less available height). 16493 * 16494 * @param minHeight The minimum height the view will try to be. 16495 * 16496 * @see #getMinimumHeight() 16497 * 16498 * @attr ref android.R.styleable#View_minHeight 16499 */ 16500 public void setMinimumHeight(int minHeight) { 16501 mMinHeight = minHeight; 16502 requestLayout(); 16503 } 16504 16505 /** 16506 * Returns the minimum width of the view. 16507 * 16508 * @return the minimum width the view will try to be. 16509 * 16510 * @see #setMinimumWidth(int) 16511 * 16512 * @attr ref android.R.styleable#View_minWidth 16513 */ 16514 public int getMinimumWidth() { 16515 return mMinWidth; 16516 } 16517 16518 /** 16519 * Sets the minimum width of the view. It is not guaranteed the view will 16520 * be able to achieve this minimum width (for example, if its parent layout 16521 * constrains it with less available width). 16522 * 16523 * @param minWidth The minimum width the view will try to be. 16524 * 16525 * @see #getMinimumWidth() 16526 * 16527 * @attr ref android.R.styleable#View_minWidth 16528 */ 16529 public void setMinimumWidth(int minWidth) { 16530 mMinWidth = minWidth; 16531 requestLayout(); 16532 16533 } 16534 16535 /** 16536 * Get the animation currently associated with this view. 16537 * 16538 * @return The animation that is currently playing or 16539 * scheduled to play for this view. 16540 */ 16541 public Animation getAnimation() { 16542 return mCurrentAnimation; 16543 } 16544 16545 /** 16546 * Start the specified animation now. 16547 * 16548 * @param animation the animation to start now 16549 */ 16550 public void startAnimation(Animation animation) { 16551 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 16552 setAnimation(animation); 16553 invalidateParentCaches(); 16554 invalidate(true); 16555 } 16556 16557 /** 16558 * Cancels any animations for this view. 16559 */ 16560 public void clearAnimation() { 16561 if (mCurrentAnimation != null) { 16562 mCurrentAnimation.detach(); 16563 } 16564 mCurrentAnimation = null; 16565 invalidateParentIfNeeded(); 16566 } 16567 16568 /** 16569 * Sets the next animation to play for this view. 16570 * If you want the animation to play immediately, use 16571 * {@link #startAnimation(android.view.animation.Animation)} instead. 16572 * This method provides allows fine-grained 16573 * control over the start time and invalidation, but you 16574 * must make sure that 1) the animation has a start time set, and 16575 * 2) the view's parent (which controls animations on its children) 16576 * will be invalidated when the animation is supposed to 16577 * start. 16578 * 16579 * @param animation The next animation, or null. 16580 */ 16581 public void setAnimation(Animation animation) { 16582 mCurrentAnimation = animation; 16583 16584 if (animation != null) { 16585 // If the screen is off assume the animation start time is now instead of 16586 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 16587 // would cause the animation to start when the screen turns back on 16588 if (mAttachInfo != null && !mAttachInfo.mScreenOn && 16589 animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 16590 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 16591 } 16592 animation.reset(); 16593 } 16594 } 16595 16596 /** 16597 * Invoked by a parent ViewGroup to notify the start of the animation 16598 * currently associated with this view. If you override this method, 16599 * always call super.onAnimationStart(); 16600 * 16601 * @see #setAnimation(android.view.animation.Animation) 16602 * @see #getAnimation() 16603 */ 16604 protected void onAnimationStart() { 16605 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 16606 } 16607 16608 /** 16609 * Invoked by a parent ViewGroup to notify the end of the animation 16610 * currently associated with this view. If you override this method, 16611 * always call super.onAnimationEnd(); 16612 * 16613 * @see #setAnimation(android.view.animation.Animation) 16614 * @see #getAnimation() 16615 */ 16616 protected void onAnimationEnd() { 16617 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 16618 } 16619 16620 /** 16621 * Invoked if there is a Transform that involves alpha. Subclass that can 16622 * draw themselves with the specified alpha should return true, and then 16623 * respect that alpha when their onDraw() is called. If this returns false 16624 * then the view may be redirected to draw into an offscreen buffer to 16625 * fulfill the request, which will look fine, but may be slower than if the 16626 * subclass handles it internally. The default implementation returns false. 16627 * 16628 * @param alpha The alpha (0..255) to apply to the view's drawing 16629 * @return true if the view can draw with the specified alpha. 16630 */ 16631 protected boolean onSetAlpha(int alpha) { 16632 return false; 16633 } 16634 16635 /** 16636 * This is used by the RootView to perform an optimization when 16637 * the view hierarchy contains one or several SurfaceView. 16638 * SurfaceView is always considered transparent, but its children are not, 16639 * therefore all View objects remove themselves from the global transparent 16640 * region (passed as a parameter to this function). 16641 * 16642 * @param region The transparent region for this ViewAncestor (window). 16643 * 16644 * @return Returns true if the effective visibility of the view at this 16645 * point is opaque, regardless of the transparent region; returns false 16646 * if it is possible for underlying windows to be seen behind the view. 16647 * 16648 * {@hide} 16649 */ 16650 public boolean gatherTransparentRegion(Region region) { 16651 final AttachInfo attachInfo = mAttachInfo; 16652 if (region != null && attachInfo != null) { 16653 final int pflags = mPrivateFlags; 16654 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 16655 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 16656 // remove it from the transparent region. 16657 final int[] location = attachInfo.mTransparentLocation; 16658 getLocationInWindow(location); 16659 region.op(location[0], location[1], location[0] + mRight - mLeft, 16660 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 16661 } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) { 16662 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 16663 // exists, so we remove the background drawable's non-transparent 16664 // parts from this transparent region. 16665 applyDrawableToTransparentRegion(mBackground, region); 16666 } 16667 } 16668 return true; 16669 } 16670 16671 /** 16672 * Play a sound effect for this view. 16673 * 16674 * <p>The framework will play sound effects for some built in actions, such as 16675 * clicking, but you may wish to play these effects in your widget, 16676 * for instance, for internal navigation. 16677 * 16678 * <p>The sound effect will only be played if sound effects are enabled by the user, and 16679 * {@link #isSoundEffectsEnabled()} is true. 16680 * 16681 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 16682 */ 16683 public void playSoundEffect(int soundConstant) { 16684 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 16685 return; 16686 } 16687 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 16688 } 16689 16690 /** 16691 * BZZZTT!!1! 16692 * 16693 * <p>Provide haptic feedback to the user for this view. 16694 * 16695 * <p>The framework will provide haptic feedback for some built in actions, 16696 * such as long presses, but you may wish to provide feedback for your 16697 * own widget. 16698 * 16699 * <p>The feedback will only be performed if 16700 * {@link #isHapticFeedbackEnabled()} is true. 16701 * 16702 * @param feedbackConstant One of the constants defined in 16703 * {@link HapticFeedbackConstants} 16704 */ 16705 public boolean performHapticFeedback(int feedbackConstant) { 16706 return performHapticFeedback(feedbackConstant, 0); 16707 } 16708 16709 /** 16710 * BZZZTT!!1! 16711 * 16712 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 16713 * 16714 * @param feedbackConstant One of the constants defined in 16715 * {@link HapticFeedbackConstants} 16716 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 16717 */ 16718 public boolean performHapticFeedback(int feedbackConstant, int flags) { 16719 if (mAttachInfo == null) { 16720 return false; 16721 } 16722 //noinspection SimplifiableIfStatement 16723 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 16724 && !isHapticFeedbackEnabled()) { 16725 return false; 16726 } 16727 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 16728 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 16729 } 16730 16731 /** 16732 * Request that the visibility of the status bar or other screen/window 16733 * decorations be changed. 16734 * 16735 * <p>This method is used to put the over device UI into temporary modes 16736 * where the user's attention is focused more on the application content, 16737 * by dimming or hiding surrounding system affordances. This is typically 16738 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 16739 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 16740 * to be placed behind the action bar (and with these flags other system 16741 * affordances) so that smooth transitions between hiding and showing them 16742 * can be done. 16743 * 16744 * <p>Two representative examples of the use of system UI visibility is 16745 * implementing a content browsing application (like a magazine reader) 16746 * and a video playing application. 16747 * 16748 * <p>The first code shows a typical implementation of a View in a content 16749 * browsing application. In this implementation, the application goes 16750 * into a content-oriented mode by hiding the status bar and action bar, 16751 * and putting the navigation elements into lights out mode. The user can 16752 * then interact with content while in this mode. Such an application should 16753 * provide an easy way for the user to toggle out of the mode (such as to 16754 * check information in the status bar or access notifications). In the 16755 * implementation here, this is done simply by tapping on the content. 16756 * 16757 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 16758 * content} 16759 * 16760 * <p>This second code sample shows a typical implementation of a View 16761 * in a video playing application. In this situation, while the video is 16762 * playing the application would like to go into a complete full-screen mode, 16763 * to use as much of the display as possible for the video. When in this state 16764 * the user can not interact with the application; the system intercepts 16765 * touching on the screen to pop the UI out of full screen mode. See 16766 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 16767 * 16768 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 16769 * content} 16770 * 16771 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 16772 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 16773 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 16774 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 16775 * {@link #SYSTEM_UI_FLAG_TRANSPARENT_STATUS}, 16776 * and {@link #SYSTEM_UI_FLAG_TRANSPARENT_NAVIGATION}. 16777 */ 16778 public void setSystemUiVisibility(int visibility) { 16779 if (visibility != mSystemUiVisibility) { 16780 mSystemUiVisibility = visibility; 16781 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 16782 mParent.recomputeViewAttributes(this); 16783 } 16784 } 16785 } 16786 16787 /** 16788 * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested. 16789 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 16790 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 16791 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 16792 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 16793 * {@link #SYSTEM_UI_FLAG_TRANSPARENT_STATUS}, 16794 * and {@link #SYSTEM_UI_FLAG_TRANSPARENT_NAVIGATION}. 16795 */ 16796 public int getSystemUiVisibility() { 16797 return mSystemUiVisibility; 16798 } 16799 16800 /** 16801 * Returns the current system UI visibility that is currently set for 16802 * the entire window. This is the combination of the 16803 * {@link #setSystemUiVisibility(int)} values supplied by all of the 16804 * views in the window. 16805 */ 16806 public int getWindowSystemUiVisibility() { 16807 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 16808 } 16809 16810 /** 16811 * Override to find out when the window's requested system UI visibility 16812 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 16813 * This is different from the callbacks received through 16814 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 16815 * in that this is only telling you about the local request of the window, 16816 * not the actual values applied by the system. 16817 */ 16818 public void onWindowSystemUiVisibilityChanged(int visible) { 16819 } 16820 16821 /** 16822 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 16823 * the view hierarchy. 16824 */ 16825 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 16826 onWindowSystemUiVisibilityChanged(visible); 16827 } 16828 16829 /** 16830 * Set a listener to receive callbacks when the visibility of the system bar changes. 16831 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 16832 */ 16833 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 16834 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 16835 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 16836 mParent.recomputeViewAttributes(this); 16837 } 16838 } 16839 16840 /** 16841 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 16842 * the view hierarchy. 16843 */ 16844 public void dispatchSystemUiVisibilityChanged(int visibility) { 16845 ListenerInfo li = mListenerInfo; 16846 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 16847 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 16848 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 16849 } 16850 } 16851 16852 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 16853 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 16854 if (val != mSystemUiVisibility) { 16855 setSystemUiVisibility(val); 16856 return true; 16857 } 16858 return false; 16859 } 16860 16861 /** @hide */ 16862 public void setDisabledSystemUiVisibility(int flags) { 16863 if (mAttachInfo != null) { 16864 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 16865 mAttachInfo.mDisabledSystemUiVisibility = flags; 16866 if (mParent != null) { 16867 mParent.recomputeViewAttributes(this); 16868 } 16869 } 16870 } 16871 } 16872 16873 /** 16874 * Creates an image that the system displays during the drag and drop 16875 * operation. This is called a "drag shadow". The default implementation 16876 * for a DragShadowBuilder based on a View returns an image that has exactly the same 16877 * appearance as the given View. The default also positions the center of the drag shadow 16878 * directly under the touch point. If no View is provided (the constructor with no parameters 16879 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 16880 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 16881 * default is an invisible drag shadow. 16882 * <p> 16883 * You are not required to use the View you provide to the constructor as the basis of the 16884 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 16885 * anything you want as the drag shadow. 16886 * </p> 16887 * <p> 16888 * You pass a DragShadowBuilder object to the system when you start the drag. The system 16889 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 16890 * size and position of the drag shadow. It uses this data to construct a 16891 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 16892 * so that your application can draw the shadow image in the Canvas. 16893 * </p> 16894 * 16895 * <div class="special reference"> 16896 * <h3>Developer Guides</h3> 16897 * <p>For a guide to implementing drag and drop features, read the 16898 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 16899 * </div> 16900 */ 16901 public static class DragShadowBuilder { 16902 private final WeakReference<View> mView; 16903 16904 /** 16905 * Constructs a shadow image builder based on a View. By default, the resulting drag 16906 * shadow will have the same appearance and dimensions as the View, with the touch point 16907 * over the center of the View. 16908 * @param view A View. Any View in scope can be used. 16909 */ 16910 public DragShadowBuilder(View view) { 16911 mView = new WeakReference<View>(view); 16912 } 16913 16914 /** 16915 * Construct a shadow builder object with no associated View. This 16916 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 16917 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 16918 * to supply the drag shadow's dimensions and appearance without 16919 * reference to any View object. If they are not overridden, then the result is an 16920 * invisible drag shadow. 16921 */ 16922 public DragShadowBuilder() { 16923 mView = new WeakReference<View>(null); 16924 } 16925 16926 /** 16927 * Returns the View object that had been passed to the 16928 * {@link #View.DragShadowBuilder(View)} 16929 * constructor. If that View parameter was {@code null} or if the 16930 * {@link #View.DragShadowBuilder()} 16931 * constructor was used to instantiate the builder object, this method will return 16932 * null. 16933 * 16934 * @return The View object associate with this builder object. 16935 */ 16936 @SuppressWarnings({"JavadocReference"}) 16937 final public View getView() { 16938 return mView.get(); 16939 } 16940 16941 /** 16942 * Provides the metrics for the shadow image. These include the dimensions of 16943 * the shadow image, and the point within that shadow that should 16944 * be centered under the touch location while dragging. 16945 * <p> 16946 * The default implementation sets the dimensions of the shadow to be the 16947 * same as the dimensions of the View itself and centers the shadow under 16948 * the touch point. 16949 * </p> 16950 * 16951 * @param shadowSize A {@link android.graphics.Point} containing the width and height 16952 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 16953 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 16954 * image. 16955 * 16956 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 16957 * shadow image that should be underneath the touch point during the drag and drop 16958 * operation. Your application must set {@link android.graphics.Point#x} to the 16959 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 16960 */ 16961 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 16962 final View view = mView.get(); 16963 if (view != null) { 16964 shadowSize.set(view.getWidth(), view.getHeight()); 16965 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 16966 } else { 16967 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 16968 } 16969 } 16970 16971 /** 16972 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 16973 * based on the dimensions it received from the 16974 * {@link #onProvideShadowMetrics(Point, Point)} callback. 16975 * 16976 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 16977 */ 16978 public void onDrawShadow(Canvas canvas) { 16979 final View view = mView.get(); 16980 if (view != null) { 16981 view.draw(canvas); 16982 } else { 16983 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 16984 } 16985 } 16986 } 16987 16988 /** 16989 * Starts a drag and drop operation. When your application calls this method, it passes a 16990 * {@link android.view.View.DragShadowBuilder} object to the system. The 16991 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 16992 * to get metrics for the drag shadow, and then calls the object's 16993 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 16994 * <p> 16995 * Once the system has the drag shadow, it begins the drag and drop operation by sending 16996 * drag events to all the View objects in your application that are currently visible. It does 16997 * this either by calling the View object's drag listener (an implementation of 16998 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 16999 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 17000 * Both are passed a {@link android.view.DragEvent} object that has a 17001 * {@link android.view.DragEvent#getAction()} value of 17002 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 17003 * </p> 17004 * <p> 17005 * Your application can invoke startDrag() on any attached View object. The View object does not 17006 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 17007 * be related to the View the user selected for dragging. 17008 * </p> 17009 * @param data A {@link android.content.ClipData} object pointing to the data to be 17010 * transferred by the drag and drop operation. 17011 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 17012 * drag shadow. 17013 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 17014 * drop operation. This Object is put into every DragEvent object sent by the system during the 17015 * current drag. 17016 * <p> 17017 * myLocalState is a lightweight mechanism for the sending information from the dragged View 17018 * to the target Views. For example, it can contain flags that differentiate between a 17019 * a copy operation and a move operation. 17020 * </p> 17021 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 17022 * so the parameter should be set to 0. 17023 * @return {@code true} if the method completes successfully, or 17024 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 17025 * do a drag, and so no drag operation is in progress. 17026 */ 17027 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 17028 Object myLocalState, int flags) { 17029 if (ViewDebug.DEBUG_DRAG) { 17030 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 17031 } 17032 boolean okay = false; 17033 17034 Point shadowSize = new Point(); 17035 Point shadowTouchPoint = new Point(); 17036 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 17037 17038 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 17039 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 17040 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 17041 } 17042 17043 if (ViewDebug.DEBUG_DRAG) { 17044 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 17045 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 17046 } 17047 Surface surface = new Surface(); 17048 try { 17049 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 17050 flags, shadowSize.x, shadowSize.y, surface); 17051 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 17052 + " surface=" + surface); 17053 if (token != null) { 17054 Canvas canvas = surface.lockCanvas(null); 17055 try { 17056 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 17057 shadowBuilder.onDrawShadow(canvas); 17058 } finally { 17059 surface.unlockCanvasAndPost(canvas); 17060 } 17061 17062 final ViewRootImpl root = getViewRootImpl(); 17063 17064 // Cache the local state object for delivery with DragEvents 17065 root.setLocalDragState(myLocalState); 17066 17067 // repurpose 'shadowSize' for the last touch point 17068 root.getLastTouchPoint(shadowSize); 17069 17070 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 17071 shadowSize.x, shadowSize.y, 17072 shadowTouchPoint.x, shadowTouchPoint.y, data); 17073 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 17074 17075 // Off and running! Release our local surface instance; the drag 17076 // shadow surface is now managed by the system process. 17077 surface.release(); 17078 } 17079 } catch (Exception e) { 17080 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 17081 surface.destroy(); 17082 } 17083 17084 return okay; 17085 } 17086 17087 /** 17088 * Handles drag events sent by the system following a call to 17089 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 17090 *<p> 17091 * When the system calls this method, it passes a 17092 * {@link android.view.DragEvent} object. A call to 17093 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 17094 * in DragEvent. The method uses these to determine what is happening in the drag and drop 17095 * operation. 17096 * @param event The {@link android.view.DragEvent} sent by the system. 17097 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 17098 * in DragEvent, indicating the type of drag event represented by this object. 17099 * @return {@code true} if the method was successful, otherwise {@code false}. 17100 * <p> 17101 * The method should return {@code true} in response to an action type of 17102 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 17103 * operation. 17104 * </p> 17105 * <p> 17106 * The method should also return {@code true} in response to an action type of 17107 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 17108 * {@code false} if it didn't. 17109 * </p> 17110 */ 17111 public boolean onDragEvent(DragEvent event) { 17112 return false; 17113 } 17114 17115 /** 17116 * Detects if this View is enabled and has a drag event listener. 17117 * If both are true, then it calls the drag event listener with the 17118 * {@link android.view.DragEvent} it received. If the drag event listener returns 17119 * {@code true}, then dispatchDragEvent() returns {@code true}. 17120 * <p> 17121 * For all other cases, the method calls the 17122 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 17123 * method and returns its result. 17124 * </p> 17125 * <p> 17126 * This ensures that a drag event is always consumed, even if the View does not have a drag 17127 * event listener. However, if the View has a listener and the listener returns true, then 17128 * onDragEvent() is not called. 17129 * </p> 17130 */ 17131 public boolean dispatchDragEvent(DragEvent event) { 17132 ListenerInfo li = mListenerInfo; 17133 //noinspection SimplifiableIfStatement 17134 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 17135 && li.mOnDragListener.onDrag(this, event)) { 17136 return true; 17137 } 17138 return onDragEvent(event); 17139 } 17140 17141 boolean canAcceptDrag() { 17142 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 17143 } 17144 17145 /** 17146 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 17147 * it is ever exposed at all. 17148 * @hide 17149 */ 17150 public void onCloseSystemDialogs(String reason) { 17151 } 17152 17153 /** 17154 * Given a Drawable whose bounds have been set to draw into this view, 17155 * update a Region being computed for 17156 * {@link #gatherTransparentRegion(android.graphics.Region)} so 17157 * that any non-transparent parts of the Drawable are removed from the 17158 * given transparent region. 17159 * 17160 * @param dr The Drawable whose transparency is to be applied to the region. 17161 * @param region A Region holding the current transparency information, 17162 * where any parts of the region that are set are considered to be 17163 * transparent. On return, this region will be modified to have the 17164 * transparency information reduced by the corresponding parts of the 17165 * Drawable that are not transparent. 17166 * {@hide} 17167 */ 17168 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 17169 if (DBG) { 17170 Log.i("View", "Getting transparent region for: " + this); 17171 } 17172 final Region r = dr.getTransparentRegion(); 17173 final Rect db = dr.getBounds(); 17174 final AttachInfo attachInfo = mAttachInfo; 17175 if (r != null && attachInfo != null) { 17176 final int w = getRight()-getLeft(); 17177 final int h = getBottom()-getTop(); 17178 if (db.left > 0) { 17179 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 17180 r.op(0, 0, db.left, h, Region.Op.UNION); 17181 } 17182 if (db.right < w) { 17183 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 17184 r.op(db.right, 0, w, h, Region.Op.UNION); 17185 } 17186 if (db.top > 0) { 17187 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 17188 r.op(0, 0, w, db.top, Region.Op.UNION); 17189 } 17190 if (db.bottom < h) { 17191 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 17192 r.op(0, db.bottom, w, h, Region.Op.UNION); 17193 } 17194 final int[] location = attachInfo.mTransparentLocation; 17195 getLocationInWindow(location); 17196 r.translate(location[0], location[1]); 17197 region.op(r, Region.Op.INTERSECT); 17198 } else { 17199 region.op(db, Region.Op.DIFFERENCE); 17200 } 17201 } 17202 17203 private void checkForLongClick(int delayOffset) { 17204 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 17205 mHasPerformedLongPress = false; 17206 17207 if (mPendingCheckForLongPress == null) { 17208 mPendingCheckForLongPress = new CheckForLongPress(); 17209 } 17210 mPendingCheckForLongPress.rememberWindowAttachCount(); 17211 postDelayed(mPendingCheckForLongPress, 17212 ViewConfiguration.getLongPressTimeout() - delayOffset); 17213 } 17214 } 17215 17216 /** 17217 * Inflate a view from an XML resource. This convenience method wraps the {@link 17218 * LayoutInflater} class, which provides a full range of options for view inflation. 17219 * 17220 * @param context The Context object for your activity or application. 17221 * @param resource The resource ID to inflate 17222 * @param root A view group that will be the parent. Used to properly inflate the 17223 * layout_* parameters. 17224 * @see LayoutInflater 17225 */ 17226 public static View inflate(Context context, int resource, ViewGroup root) { 17227 LayoutInflater factory = LayoutInflater.from(context); 17228 return factory.inflate(resource, root); 17229 } 17230 17231 /** 17232 * Scroll the view with standard behavior for scrolling beyond the normal 17233 * content boundaries. Views that call this method should override 17234 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 17235 * results of an over-scroll operation. 17236 * 17237 * Views can use this method to handle any touch or fling-based scrolling. 17238 * 17239 * @param deltaX Change in X in pixels 17240 * @param deltaY Change in Y in pixels 17241 * @param scrollX Current X scroll value in pixels before applying deltaX 17242 * @param scrollY Current Y scroll value in pixels before applying deltaY 17243 * @param scrollRangeX Maximum content scroll range along the X axis 17244 * @param scrollRangeY Maximum content scroll range along the Y axis 17245 * @param maxOverScrollX Number of pixels to overscroll by in either direction 17246 * along the X axis. 17247 * @param maxOverScrollY Number of pixels to overscroll by in either direction 17248 * along the Y axis. 17249 * @param isTouchEvent true if this scroll operation is the result of a touch event. 17250 * @return true if scrolling was clamped to an over-scroll boundary along either 17251 * axis, false otherwise. 17252 */ 17253 @SuppressWarnings({"UnusedParameters"}) 17254 protected boolean overScrollBy(int deltaX, int deltaY, 17255 int scrollX, int scrollY, 17256 int scrollRangeX, int scrollRangeY, 17257 int maxOverScrollX, int maxOverScrollY, 17258 boolean isTouchEvent) { 17259 final int overScrollMode = mOverScrollMode; 17260 final boolean canScrollHorizontal = 17261 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 17262 final boolean canScrollVertical = 17263 computeVerticalScrollRange() > computeVerticalScrollExtent(); 17264 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 17265 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 17266 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 17267 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 17268 17269 int newScrollX = scrollX + deltaX; 17270 if (!overScrollHorizontal) { 17271 maxOverScrollX = 0; 17272 } 17273 17274 int newScrollY = scrollY + deltaY; 17275 if (!overScrollVertical) { 17276 maxOverScrollY = 0; 17277 } 17278 17279 // Clamp values if at the limits and record 17280 final int left = -maxOverScrollX; 17281 final int right = maxOverScrollX + scrollRangeX; 17282 final int top = -maxOverScrollY; 17283 final int bottom = maxOverScrollY + scrollRangeY; 17284 17285 boolean clampedX = false; 17286 if (newScrollX > right) { 17287 newScrollX = right; 17288 clampedX = true; 17289 } else if (newScrollX < left) { 17290 newScrollX = left; 17291 clampedX = true; 17292 } 17293 17294 boolean clampedY = false; 17295 if (newScrollY > bottom) { 17296 newScrollY = bottom; 17297 clampedY = true; 17298 } else if (newScrollY < top) { 17299 newScrollY = top; 17300 clampedY = true; 17301 } 17302 17303 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 17304 17305 return clampedX || clampedY; 17306 } 17307 17308 /** 17309 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 17310 * respond to the results of an over-scroll operation. 17311 * 17312 * @param scrollX New X scroll value in pixels 17313 * @param scrollY New Y scroll value in pixels 17314 * @param clampedX True if scrollX was clamped to an over-scroll boundary 17315 * @param clampedY True if scrollY was clamped to an over-scroll boundary 17316 */ 17317 protected void onOverScrolled(int scrollX, int scrollY, 17318 boolean clampedX, boolean clampedY) { 17319 // Intentionally empty. 17320 } 17321 17322 /** 17323 * Returns the over-scroll mode for this view. The result will be 17324 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 17325 * (allow over-scrolling only if the view content is larger than the container), 17326 * or {@link #OVER_SCROLL_NEVER}. 17327 * 17328 * @return This view's over-scroll mode. 17329 */ 17330 public int getOverScrollMode() { 17331 return mOverScrollMode; 17332 } 17333 17334 /** 17335 * Set the over-scroll mode for this view. Valid over-scroll modes are 17336 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 17337 * (allow over-scrolling only if the view content is larger than the container), 17338 * or {@link #OVER_SCROLL_NEVER}. 17339 * 17340 * Setting the over-scroll mode of a view will have an effect only if the 17341 * view is capable of scrolling. 17342 * 17343 * @param overScrollMode The new over-scroll mode for this view. 17344 */ 17345 public void setOverScrollMode(int overScrollMode) { 17346 if (overScrollMode != OVER_SCROLL_ALWAYS && 17347 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 17348 overScrollMode != OVER_SCROLL_NEVER) { 17349 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 17350 } 17351 mOverScrollMode = overScrollMode; 17352 } 17353 17354 /** 17355 * Gets a scale factor that determines the distance the view should scroll 17356 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 17357 * @return The vertical scroll scale factor. 17358 * @hide 17359 */ 17360 protected float getVerticalScrollFactor() { 17361 if (mVerticalScrollFactor == 0) { 17362 TypedValue outValue = new TypedValue(); 17363 if (!mContext.getTheme().resolveAttribute( 17364 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 17365 throw new IllegalStateException( 17366 "Expected theme to define listPreferredItemHeight."); 17367 } 17368 mVerticalScrollFactor = outValue.getDimension( 17369 mContext.getResources().getDisplayMetrics()); 17370 } 17371 return mVerticalScrollFactor; 17372 } 17373 17374 /** 17375 * Gets a scale factor that determines the distance the view should scroll 17376 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 17377 * @return The horizontal scroll scale factor. 17378 * @hide 17379 */ 17380 protected float getHorizontalScrollFactor() { 17381 // TODO: Should use something else. 17382 return getVerticalScrollFactor(); 17383 } 17384 17385 /** 17386 * Return the value specifying the text direction or policy that was set with 17387 * {@link #setTextDirection(int)}. 17388 * 17389 * @return the defined text direction. It can be one of: 17390 * 17391 * {@link #TEXT_DIRECTION_INHERIT}, 17392 * {@link #TEXT_DIRECTION_FIRST_STRONG} 17393 * {@link #TEXT_DIRECTION_ANY_RTL}, 17394 * {@link #TEXT_DIRECTION_LTR}, 17395 * {@link #TEXT_DIRECTION_RTL}, 17396 * {@link #TEXT_DIRECTION_LOCALE} 17397 * 17398 * @attr ref android.R.styleable#View_textDirection 17399 * 17400 * @hide 17401 */ 17402 @ViewDebug.ExportedProperty(category = "text", mapping = { 17403 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 17404 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 17405 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 17406 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 17407 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 17408 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 17409 }) 17410 public int getRawTextDirection() { 17411 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 17412 } 17413 17414 /** 17415 * Set the text direction. 17416 * 17417 * @param textDirection the direction to set. Should be one of: 17418 * 17419 * {@link #TEXT_DIRECTION_INHERIT}, 17420 * {@link #TEXT_DIRECTION_FIRST_STRONG} 17421 * {@link #TEXT_DIRECTION_ANY_RTL}, 17422 * {@link #TEXT_DIRECTION_LTR}, 17423 * {@link #TEXT_DIRECTION_RTL}, 17424 * {@link #TEXT_DIRECTION_LOCALE} 17425 * 17426 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution 17427 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will 17428 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 17429 * 17430 * @attr ref android.R.styleable#View_textDirection 17431 */ 17432 public void setTextDirection(int textDirection) { 17433 if (getRawTextDirection() != textDirection) { 17434 // Reset the current text direction and the resolved one 17435 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 17436 resetResolvedTextDirection(); 17437 // Set the new text direction 17438 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 17439 // Do resolution 17440 resolveTextDirection(); 17441 // Notify change 17442 onRtlPropertiesChanged(getLayoutDirection()); 17443 // Refresh 17444 requestLayout(); 17445 invalidate(true); 17446 } 17447 } 17448 17449 /** 17450 * Return the resolved text direction. 17451 * 17452 * @return the resolved text direction. Returns one of: 17453 * 17454 * {@link #TEXT_DIRECTION_FIRST_STRONG} 17455 * {@link #TEXT_DIRECTION_ANY_RTL}, 17456 * {@link #TEXT_DIRECTION_LTR}, 17457 * {@link #TEXT_DIRECTION_RTL}, 17458 * {@link #TEXT_DIRECTION_LOCALE} 17459 * 17460 * @attr ref android.R.styleable#View_textDirection 17461 */ 17462 @ViewDebug.ExportedProperty(category = "text", mapping = { 17463 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 17464 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 17465 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 17466 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 17467 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 17468 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 17469 }) 17470 public int getTextDirection() { 17471 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 17472 } 17473 17474 /** 17475 * Resolve the text direction. 17476 * 17477 * @return true if resolution has been done, false otherwise. 17478 * 17479 * @hide 17480 */ 17481 public boolean resolveTextDirection() { 17482 // Reset any previous text direction resolution 17483 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 17484 17485 if (hasRtlSupport()) { 17486 // Set resolved text direction flag depending on text direction flag 17487 final int textDirection = getRawTextDirection(); 17488 switch(textDirection) { 17489 case TEXT_DIRECTION_INHERIT: 17490 if (!canResolveTextDirection()) { 17491 // We cannot do the resolution if there is no parent, so use the default one 17492 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 17493 // Resolution will need to happen again later 17494 return false; 17495 } 17496 17497 // Parent has not yet resolved, so we still return the default 17498 try { 17499 if (!mParent.isTextDirectionResolved()) { 17500 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 17501 // Resolution will need to happen again later 17502 return false; 17503 } 17504 } catch (AbstractMethodError e) { 17505 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 17506 " does not fully implement ViewParent", e); 17507 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED | 17508 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 17509 return true; 17510 } 17511 17512 // Set current resolved direction to the same value as the parent's one 17513 int parentResolvedDirection; 17514 try { 17515 parentResolvedDirection = mParent.getTextDirection(); 17516 } catch (AbstractMethodError e) { 17517 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 17518 " does not fully implement ViewParent", e); 17519 parentResolvedDirection = TEXT_DIRECTION_LTR; 17520 } 17521 switch (parentResolvedDirection) { 17522 case TEXT_DIRECTION_FIRST_STRONG: 17523 case TEXT_DIRECTION_ANY_RTL: 17524 case TEXT_DIRECTION_LTR: 17525 case TEXT_DIRECTION_RTL: 17526 case TEXT_DIRECTION_LOCALE: 17527 mPrivateFlags2 |= 17528 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 17529 break; 17530 default: 17531 // Default resolved direction is "first strong" heuristic 17532 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 17533 } 17534 break; 17535 case TEXT_DIRECTION_FIRST_STRONG: 17536 case TEXT_DIRECTION_ANY_RTL: 17537 case TEXT_DIRECTION_LTR: 17538 case TEXT_DIRECTION_RTL: 17539 case TEXT_DIRECTION_LOCALE: 17540 // Resolved direction is the same as text direction 17541 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 17542 break; 17543 default: 17544 // Default resolved direction is "first strong" heuristic 17545 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 17546 } 17547 } else { 17548 // Default resolved direction is "first strong" heuristic 17549 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 17550 } 17551 17552 // Set to resolved 17553 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 17554 return true; 17555 } 17556 17557 /** 17558 * Check if text direction resolution can be done. 17559 * 17560 * @return true if text direction resolution can be done otherwise return false. 17561 */ 17562 public boolean canResolveTextDirection() { 17563 switch (getRawTextDirection()) { 17564 case TEXT_DIRECTION_INHERIT: 17565 if (mParent != null) { 17566 try { 17567 return mParent.canResolveTextDirection(); 17568 } catch (AbstractMethodError e) { 17569 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 17570 " does not fully implement ViewParent", e); 17571 } 17572 } 17573 return false; 17574 17575 default: 17576 return true; 17577 } 17578 } 17579 17580 /** 17581 * Reset resolved text direction. Text direction will be resolved during a call to 17582 * {@link #onMeasure(int, int)}. 17583 * 17584 * @hide 17585 */ 17586 public void resetResolvedTextDirection() { 17587 // Reset any previous text direction resolution 17588 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 17589 // Set to default value 17590 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 17591 } 17592 17593 /** 17594 * @return true if text direction is inherited. 17595 * 17596 * @hide 17597 */ 17598 public boolean isTextDirectionInherited() { 17599 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 17600 } 17601 17602 /** 17603 * @return true if text direction is resolved. 17604 */ 17605 public boolean isTextDirectionResolved() { 17606 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED; 17607 } 17608 17609 /** 17610 * Return the value specifying the text alignment or policy that was set with 17611 * {@link #setTextAlignment(int)}. 17612 * 17613 * @return the defined text alignment. It can be one of: 17614 * 17615 * {@link #TEXT_ALIGNMENT_INHERIT}, 17616 * {@link #TEXT_ALIGNMENT_GRAVITY}, 17617 * {@link #TEXT_ALIGNMENT_CENTER}, 17618 * {@link #TEXT_ALIGNMENT_TEXT_START}, 17619 * {@link #TEXT_ALIGNMENT_TEXT_END}, 17620 * {@link #TEXT_ALIGNMENT_VIEW_START}, 17621 * {@link #TEXT_ALIGNMENT_VIEW_END} 17622 * 17623 * @attr ref android.R.styleable#View_textAlignment 17624 * 17625 * @hide 17626 */ 17627 @ViewDebug.ExportedProperty(category = "text", mapping = { 17628 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 17629 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 17630 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 17631 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 17632 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 17633 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 17634 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 17635 }) 17636 public int getRawTextAlignment() { 17637 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 17638 } 17639 17640 /** 17641 * Set the text alignment. 17642 * 17643 * @param textAlignment The text alignment to set. Should be one of 17644 * 17645 * {@link #TEXT_ALIGNMENT_INHERIT}, 17646 * {@link #TEXT_ALIGNMENT_GRAVITY}, 17647 * {@link #TEXT_ALIGNMENT_CENTER}, 17648 * {@link #TEXT_ALIGNMENT_TEXT_START}, 17649 * {@link #TEXT_ALIGNMENT_TEXT_END}, 17650 * {@link #TEXT_ALIGNMENT_VIEW_START}, 17651 * {@link #TEXT_ALIGNMENT_VIEW_END} 17652 * 17653 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution 17654 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 17655 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}. 17656 * 17657 * @attr ref android.R.styleable#View_textAlignment 17658 */ 17659 public void setTextAlignment(int textAlignment) { 17660 if (textAlignment != getRawTextAlignment()) { 17661 // Reset the current and resolved text alignment 17662 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 17663 resetResolvedTextAlignment(); 17664 // Set the new text alignment 17665 mPrivateFlags2 |= 17666 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 17667 // Do resolution 17668 resolveTextAlignment(); 17669 // Notify change 17670 onRtlPropertiesChanged(getLayoutDirection()); 17671 // Refresh 17672 requestLayout(); 17673 invalidate(true); 17674 } 17675 } 17676 17677 /** 17678 * Return the resolved text alignment. 17679 * 17680 * @return the resolved text alignment. Returns one of: 17681 * 17682 * {@link #TEXT_ALIGNMENT_GRAVITY}, 17683 * {@link #TEXT_ALIGNMENT_CENTER}, 17684 * {@link #TEXT_ALIGNMENT_TEXT_START}, 17685 * {@link #TEXT_ALIGNMENT_TEXT_END}, 17686 * {@link #TEXT_ALIGNMENT_VIEW_START}, 17687 * {@link #TEXT_ALIGNMENT_VIEW_END} 17688 * 17689 * @attr ref android.R.styleable#View_textAlignment 17690 */ 17691 @ViewDebug.ExportedProperty(category = "text", mapping = { 17692 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 17693 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 17694 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 17695 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 17696 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 17697 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 17698 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 17699 }) 17700 public int getTextAlignment() { 17701 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> 17702 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 17703 } 17704 17705 /** 17706 * Resolve the text alignment. 17707 * 17708 * @return true if resolution has been done, false otherwise. 17709 * 17710 * @hide 17711 */ 17712 public boolean resolveTextAlignment() { 17713 // Reset any previous text alignment resolution 17714 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 17715 17716 if (hasRtlSupport()) { 17717 // Set resolved text alignment flag depending on text alignment flag 17718 final int textAlignment = getRawTextAlignment(); 17719 switch (textAlignment) { 17720 case TEXT_ALIGNMENT_INHERIT: 17721 // Check if we can resolve the text alignment 17722 if (!canResolveTextAlignment()) { 17723 // We cannot do the resolution if there is no parent so use the default 17724 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 17725 // Resolution will need to happen again later 17726 return false; 17727 } 17728 17729 // Parent has not yet resolved, so we still return the default 17730 try { 17731 if (!mParent.isTextAlignmentResolved()) { 17732 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 17733 // Resolution will need to happen again later 17734 return false; 17735 } 17736 } catch (AbstractMethodError e) { 17737 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 17738 " does not fully implement ViewParent", e); 17739 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED | 17740 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 17741 return true; 17742 } 17743 17744 int parentResolvedTextAlignment; 17745 try { 17746 parentResolvedTextAlignment = mParent.getTextAlignment(); 17747 } catch (AbstractMethodError e) { 17748 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 17749 " does not fully implement ViewParent", e); 17750 parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY; 17751 } 17752 switch (parentResolvedTextAlignment) { 17753 case TEXT_ALIGNMENT_GRAVITY: 17754 case TEXT_ALIGNMENT_TEXT_START: 17755 case TEXT_ALIGNMENT_TEXT_END: 17756 case TEXT_ALIGNMENT_CENTER: 17757 case TEXT_ALIGNMENT_VIEW_START: 17758 case TEXT_ALIGNMENT_VIEW_END: 17759 // Resolved text alignment is the same as the parent resolved 17760 // text alignment 17761 mPrivateFlags2 |= 17762 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 17763 break; 17764 default: 17765 // Use default resolved text alignment 17766 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 17767 } 17768 break; 17769 case TEXT_ALIGNMENT_GRAVITY: 17770 case TEXT_ALIGNMENT_TEXT_START: 17771 case TEXT_ALIGNMENT_TEXT_END: 17772 case TEXT_ALIGNMENT_CENTER: 17773 case TEXT_ALIGNMENT_VIEW_START: 17774 case TEXT_ALIGNMENT_VIEW_END: 17775 // Resolved text alignment is the same as text alignment 17776 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 17777 break; 17778 default: 17779 // Use default resolved text alignment 17780 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 17781 } 17782 } else { 17783 // Use default resolved text alignment 17784 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 17785 } 17786 17787 // Set the resolved 17788 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 17789 return true; 17790 } 17791 17792 /** 17793 * Check if text alignment resolution can be done. 17794 * 17795 * @return true if text alignment resolution can be done otherwise return false. 17796 */ 17797 public boolean canResolveTextAlignment() { 17798 switch (getRawTextAlignment()) { 17799 case TEXT_DIRECTION_INHERIT: 17800 if (mParent != null) { 17801 try { 17802 return mParent.canResolveTextAlignment(); 17803 } catch (AbstractMethodError e) { 17804 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 17805 " does not fully implement ViewParent", e); 17806 } 17807 } 17808 return false; 17809 17810 default: 17811 return true; 17812 } 17813 } 17814 17815 /** 17816 * Reset resolved text alignment. Text alignment will be resolved during a call to 17817 * {@link #onMeasure(int, int)}. 17818 * 17819 * @hide 17820 */ 17821 public void resetResolvedTextAlignment() { 17822 // Reset any previous text alignment resolution 17823 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 17824 // Set to default 17825 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 17826 } 17827 17828 /** 17829 * @return true if text alignment is inherited. 17830 * 17831 * @hide 17832 */ 17833 public boolean isTextAlignmentInherited() { 17834 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 17835 } 17836 17837 /** 17838 * @return true if text alignment is resolved. 17839 */ 17840 public boolean isTextAlignmentResolved() { 17841 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED; 17842 } 17843 17844 /** 17845 * Generate a value suitable for use in {@link #setId(int)}. 17846 * This value will not collide with ID values generated at build time by aapt for R.id. 17847 * 17848 * @return a generated ID value 17849 */ 17850 public static int generateViewId() { 17851 for (;;) { 17852 final int result = sNextGeneratedId.get(); 17853 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 17854 int newValue = result + 1; 17855 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 17856 if (sNextGeneratedId.compareAndSet(result, newValue)) { 17857 return result; 17858 } 17859 } 17860 } 17861 17862 // 17863 // Properties 17864 // 17865 /** 17866 * A Property wrapper around the <code>alpha</code> functionality handled by the 17867 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 17868 */ 17869 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 17870 @Override 17871 public void setValue(View object, float value) { 17872 object.setAlpha(value); 17873 } 17874 17875 @Override 17876 public Float get(View object) { 17877 return object.getAlpha(); 17878 } 17879 }; 17880 17881 /** 17882 * A Property wrapper around the <code>translationX</code> functionality handled by the 17883 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 17884 */ 17885 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 17886 @Override 17887 public void setValue(View object, float value) { 17888 object.setTranslationX(value); 17889 } 17890 17891 @Override 17892 public Float get(View object) { 17893 return object.getTranslationX(); 17894 } 17895 }; 17896 17897 /** 17898 * A Property wrapper around the <code>translationY</code> functionality handled by the 17899 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 17900 */ 17901 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 17902 @Override 17903 public void setValue(View object, float value) { 17904 object.setTranslationY(value); 17905 } 17906 17907 @Override 17908 public Float get(View object) { 17909 return object.getTranslationY(); 17910 } 17911 }; 17912 17913 /** 17914 * A Property wrapper around the <code>x</code> functionality handled by the 17915 * {@link View#setX(float)} and {@link View#getX()} methods. 17916 */ 17917 public static final Property<View, Float> X = new FloatProperty<View>("x") { 17918 @Override 17919 public void setValue(View object, float value) { 17920 object.setX(value); 17921 } 17922 17923 @Override 17924 public Float get(View object) { 17925 return object.getX(); 17926 } 17927 }; 17928 17929 /** 17930 * A Property wrapper around the <code>y</code> functionality handled by the 17931 * {@link View#setY(float)} and {@link View#getY()} methods. 17932 */ 17933 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 17934 @Override 17935 public void setValue(View object, float value) { 17936 object.setY(value); 17937 } 17938 17939 @Override 17940 public Float get(View object) { 17941 return object.getY(); 17942 } 17943 }; 17944 17945 /** 17946 * A Property wrapper around the <code>rotation</code> functionality handled by the 17947 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 17948 */ 17949 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 17950 @Override 17951 public void setValue(View object, float value) { 17952 object.setRotation(value); 17953 } 17954 17955 @Override 17956 public Float get(View object) { 17957 return object.getRotation(); 17958 } 17959 }; 17960 17961 /** 17962 * A Property wrapper around the <code>rotationX</code> functionality handled by the 17963 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 17964 */ 17965 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 17966 @Override 17967 public void setValue(View object, float value) { 17968 object.setRotationX(value); 17969 } 17970 17971 @Override 17972 public Float get(View object) { 17973 return object.getRotationX(); 17974 } 17975 }; 17976 17977 /** 17978 * A Property wrapper around the <code>rotationY</code> functionality handled by the 17979 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 17980 */ 17981 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 17982 @Override 17983 public void setValue(View object, float value) { 17984 object.setRotationY(value); 17985 } 17986 17987 @Override 17988 public Float get(View object) { 17989 return object.getRotationY(); 17990 } 17991 }; 17992 17993 /** 17994 * A Property wrapper around the <code>scaleX</code> functionality handled by the 17995 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 17996 */ 17997 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 17998 @Override 17999 public void setValue(View object, float value) { 18000 object.setScaleX(value); 18001 } 18002 18003 @Override 18004 public Float get(View object) { 18005 return object.getScaleX(); 18006 } 18007 }; 18008 18009 /** 18010 * A Property wrapper around the <code>scaleY</code> functionality handled by the 18011 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 18012 */ 18013 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 18014 @Override 18015 public void setValue(View object, float value) { 18016 object.setScaleY(value); 18017 } 18018 18019 @Override 18020 public Float get(View object) { 18021 return object.getScaleY(); 18022 } 18023 }; 18024 18025 /** 18026 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 18027 * Each MeasureSpec represents a requirement for either the width or the height. 18028 * A MeasureSpec is comprised of a size and a mode. There are three possible 18029 * modes: 18030 * <dl> 18031 * <dt>UNSPECIFIED</dt> 18032 * <dd> 18033 * The parent has not imposed any constraint on the child. It can be whatever size 18034 * it wants. 18035 * </dd> 18036 * 18037 * <dt>EXACTLY</dt> 18038 * <dd> 18039 * The parent has determined an exact size for the child. The child is going to be 18040 * given those bounds regardless of how big it wants to be. 18041 * </dd> 18042 * 18043 * <dt>AT_MOST</dt> 18044 * <dd> 18045 * The child can be as large as it wants up to the specified size. 18046 * </dd> 18047 * </dl> 18048 * 18049 * MeasureSpecs are implemented as ints to reduce object allocation. This class 18050 * is provided to pack and unpack the <size, mode> tuple into the int. 18051 */ 18052 public static class MeasureSpec { 18053 private static final int MODE_SHIFT = 30; 18054 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 18055 18056 /** 18057 * Measure specification mode: The parent has not imposed any constraint 18058 * on the child. It can be whatever size it wants. 18059 */ 18060 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 18061 18062 /** 18063 * Measure specification mode: The parent has determined an exact size 18064 * for the child. The child is going to be given those bounds regardless 18065 * of how big it wants to be. 18066 */ 18067 public static final int EXACTLY = 1 << MODE_SHIFT; 18068 18069 /** 18070 * Measure specification mode: The child can be as large as it wants up 18071 * to the specified size. 18072 */ 18073 public static final int AT_MOST = 2 << MODE_SHIFT; 18074 18075 /** 18076 * Creates a measure specification based on the supplied size and mode. 18077 * 18078 * The mode must always be one of the following: 18079 * <ul> 18080 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 18081 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 18082 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 18083 * </ul> 18084 * 18085 * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's 18086 * implementation was such that the order of arguments did not matter 18087 * and overflow in either value could impact the resulting MeasureSpec. 18088 * {@link android.widget.RelativeLayout} was affected by this bug. 18089 * Apps targeting API levels greater than 17 will get the fixed, more strict 18090 * behavior.</p> 18091 * 18092 * @param size the size of the measure specification 18093 * @param mode the mode of the measure specification 18094 * @return the measure specification based on size and mode 18095 */ 18096 public static int makeMeasureSpec(int size, int mode) { 18097 if (sUseBrokenMakeMeasureSpec) { 18098 return size + mode; 18099 } else { 18100 return (size & ~MODE_MASK) | (mode & MODE_MASK); 18101 } 18102 } 18103 18104 /** 18105 * Extracts the mode from the supplied measure specification. 18106 * 18107 * @param measureSpec the measure specification to extract the mode from 18108 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 18109 * {@link android.view.View.MeasureSpec#AT_MOST} or 18110 * {@link android.view.View.MeasureSpec#EXACTLY} 18111 */ 18112 public static int getMode(int measureSpec) { 18113 return (measureSpec & MODE_MASK); 18114 } 18115 18116 /** 18117 * Extracts the size from the supplied measure specification. 18118 * 18119 * @param measureSpec the measure specification to extract the size from 18120 * @return the size in pixels defined in the supplied measure specification 18121 */ 18122 public static int getSize(int measureSpec) { 18123 return (measureSpec & ~MODE_MASK); 18124 } 18125 18126 static int adjust(int measureSpec, int delta) { 18127 return makeMeasureSpec(getSize(measureSpec + delta), getMode(measureSpec)); 18128 } 18129 18130 /** 18131 * Returns a String representation of the specified measure 18132 * specification. 18133 * 18134 * @param measureSpec the measure specification to convert to a String 18135 * @return a String with the following format: "MeasureSpec: MODE SIZE" 18136 */ 18137 public static String toString(int measureSpec) { 18138 int mode = getMode(measureSpec); 18139 int size = getSize(measureSpec); 18140 18141 StringBuilder sb = new StringBuilder("MeasureSpec: "); 18142 18143 if (mode == UNSPECIFIED) 18144 sb.append("UNSPECIFIED "); 18145 else if (mode == EXACTLY) 18146 sb.append("EXACTLY "); 18147 else if (mode == AT_MOST) 18148 sb.append("AT_MOST "); 18149 else 18150 sb.append(mode).append(" "); 18151 18152 sb.append(size); 18153 return sb.toString(); 18154 } 18155 } 18156 18157 class CheckForLongPress implements Runnable { 18158 18159 private int mOriginalWindowAttachCount; 18160 18161 public void run() { 18162 if (isPressed() && (mParent != null) 18163 && mOriginalWindowAttachCount == mWindowAttachCount) { 18164 if (performLongClick()) { 18165 mHasPerformedLongPress = true; 18166 } 18167 } 18168 } 18169 18170 public void rememberWindowAttachCount() { 18171 mOriginalWindowAttachCount = mWindowAttachCount; 18172 } 18173 } 18174 18175 private final class CheckForTap implements Runnable { 18176 public void run() { 18177 mPrivateFlags &= ~PFLAG_PREPRESSED; 18178 setPressed(true); 18179 checkForLongClick(ViewConfiguration.getTapTimeout()); 18180 } 18181 } 18182 18183 private final class PerformClick implements Runnable { 18184 public void run() { 18185 performClick(); 18186 } 18187 } 18188 18189 /** @hide */ 18190 public void hackTurnOffWindowResizeAnim(boolean off) { 18191 mAttachInfo.mTurnOffWindowResizeAnim = off; 18192 } 18193 18194 /** 18195 * This method returns a ViewPropertyAnimator object, which can be used to animate 18196 * specific properties on this View. 18197 * 18198 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 18199 */ 18200 public ViewPropertyAnimator animate() { 18201 if (mAnimator == null) { 18202 mAnimator = new ViewPropertyAnimator(this); 18203 } 18204 return mAnimator; 18205 } 18206 18207 /** 18208 * Interface definition for a callback to be invoked when a hardware key event is 18209 * dispatched to this view. The callback will be invoked before the key event is 18210 * given to the view. This is only useful for hardware keyboards; a software input 18211 * method has no obligation to trigger this listener. 18212 */ 18213 public interface OnKeyListener { 18214 /** 18215 * Called when a hardware key is dispatched to a view. This allows listeners to 18216 * get a chance to respond before the target view. 18217 * <p>Key presses in software keyboards will generally NOT trigger this method, 18218 * although some may elect to do so in some situations. Do not assume a 18219 * software input method has to be key-based; even if it is, it may use key presses 18220 * in a different way than you expect, so there is no way to reliably catch soft 18221 * input key presses. 18222 * 18223 * @param v The view the key has been dispatched to. 18224 * @param keyCode The code for the physical key that was pressed 18225 * @param event The KeyEvent object containing full information about 18226 * the event. 18227 * @return True if the listener has consumed the event, false otherwise. 18228 */ 18229 boolean onKey(View v, int keyCode, KeyEvent event); 18230 } 18231 18232 /** 18233 * Interface definition for a callback to be invoked when a touch event is 18234 * dispatched to this view. The callback will be invoked before the touch 18235 * event is given to the view. 18236 */ 18237 public interface OnTouchListener { 18238 /** 18239 * Called when a touch event is dispatched to a view. This allows listeners to 18240 * get a chance to respond before the target view. 18241 * 18242 * @param v The view the touch event has been dispatched to. 18243 * @param event The MotionEvent object containing full information about 18244 * the event. 18245 * @return True if the listener has consumed the event, false otherwise. 18246 */ 18247 boolean onTouch(View v, MotionEvent event); 18248 } 18249 18250 /** 18251 * Interface definition for a callback to be invoked when a hover event is 18252 * dispatched to this view. The callback will be invoked before the hover 18253 * event is given to the view. 18254 */ 18255 public interface OnHoverListener { 18256 /** 18257 * Called when a hover event is dispatched to a view. This allows listeners to 18258 * get a chance to respond before the target view. 18259 * 18260 * @param v The view the hover event has been dispatched to. 18261 * @param event The MotionEvent object containing full information about 18262 * the event. 18263 * @return True if the listener has consumed the event, false otherwise. 18264 */ 18265 boolean onHover(View v, MotionEvent event); 18266 } 18267 18268 /** 18269 * Interface definition for a callback to be invoked when a generic motion event is 18270 * dispatched to this view. The callback will be invoked before the generic motion 18271 * event is given to the view. 18272 */ 18273 public interface OnGenericMotionListener { 18274 /** 18275 * Called when a generic motion event is dispatched to a view. This allows listeners to 18276 * get a chance to respond before the target view. 18277 * 18278 * @param v The view the generic motion event has been dispatched to. 18279 * @param event The MotionEvent object containing full information about 18280 * the event. 18281 * @return True if the listener has consumed the event, false otherwise. 18282 */ 18283 boolean onGenericMotion(View v, MotionEvent event); 18284 } 18285 18286 /** 18287 * Interface definition for a callback to be invoked when a view has been clicked and held. 18288 */ 18289 public interface OnLongClickListener { 18290 /** 18291 * Called when a view has been clicked and held. 18292 * 18293 * @param v The view that was clicked and held. 18294 * 18295 * @return true if the callback consumed the long click, false otherwise. 18296 */ 18297 boolean onLongClick(View v); 18298 } 18299 18300 /** 18301 * Interface definition for a callback to be invoked when a drag is being dispatched 18302 * to this view. The callback will be invoked before the hosting view's own 18303 * onDrag(event) method. If the listener wants to fall back to the hosting view's 18304 * onDrag(event) behavior, it should return 'false' from this callback. 18305 * 18306 * <div class="special reference"> 18307 * <h3>Developer Guides</h3> 18308 * <p>For a guide to implementing drag and drop features, read the 18309 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 18310 * </div> 18311 */ 18312 public interface OnDragListener { 18313 /** 18314 * Called when a drag event is dispatched to a view. This allows listeners 18315 * to get a chance to override base View behavior. 18316 * 18317 * @param v The View that received the drag event. 18318 * @param event The {@link android.view.DragEvent} object for the drag event. 18319 * @return {@code true} if the drag event was handled successfully, or {@code false} 18320 * if the drag event was not handled. Note that {@code false} will trigger the View 18321 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 18322 */ 18323 boolean onDrag(View v, DragEvent event); 18324 } 18325 18326 /** 18327 * Interface definition for a callback to be invoked when the focus state of 18328 * a view changed. 18329 */ 18330 public interface OnFocusChangeListener { 18331 /** 18332 * Called when the focus state of a view has changed. 18333 * 18334 * @param v The view whose state has changed. 18335 * @param hasFocus The new focus state of v. 18336 */ 18337 void onFocusChange(View v, boolean hasFocus); 18338 } 18339 18340 /** 18341 * Interface definition for a callback to be invoked when a view is clicked. 18342 */ 18343 public interface OnClickListener { 18344 /** 18345 * Called when a view has been clicked. 18346 * 18347 * @param v The view that was clicked. 18348 */ 18349 void onClick(View v); 18350 } 18351 18352 /** 18353 * Interface definition for a callback to be invoked when the context menu 18354 * for this view is being built. 18355 */ 18356 public interface OnCreateContextMenuListener { 18357 /** 18358 * Called when the context menu for this view is being built. It is not 18359 * safe to hold onto the menu after this method returns. 18360 * 18361 * @param menu The context menu that is being built 18362 * @param v The view for which the context menu is being built 18363 * @param menuInfo Extra information about the item for which the 18364 * context menu should be shown. This information will vary 18365 * depending on the class of v. 18366 */ 18367 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 18368 } 18369 18370 /** 18371 * Interface definition for a callback to be invoked when the status bar changes 18372 * visibility. This reports <strong>global</strong> changes to the system UI 18373 * state, not what the application is requesting. 18374 * 18375 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 18376 */ 18377 public interface OnSystemUiVisibilityChangeListener { 18378 /** 18379 * Called when the status bar changes visibility because of a call to 18380 * {@link View#setSystemUiVisibility(int)}. 18381 * 18382 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 18383 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 18384 * This tells you the <strong>global</strong> state of these UI visibility 18385 * flags, not what your app is currently applying. 18386 */ 18387 public void onSystemUiVisibilityChange(int visibility); 18388 } 18389 18390 /** 18391 * Interface definition for a callback to be invoked when this view is attached 18392 * or detached from its window. 18393 */ 18394 public interface OnAttachStateChangeListener { 18395 /** 18396 * Called when the view is attached to a window. 18397 * @param v The view that was attached 18398 */ 18399 public void onViewAttachedToWindow(View v); 18400 /** 18401 * Called when the view is detached from a window. 18402 * @param v The view that was detached 18403 */ 18404 public void onViewDetachedFromWindow(View v); 18405 } 18406 18407 private final class UnsetPressedState implements Runnable { 18408 public void run() { 18409 setPressed(false); 18410 } 18411 } 18412 18413 /** 18414 * Base class for derived classes that want to save and restore their own 18415 * state in {@link android.view.View#onSaveInstanceState()}. 18416 */ 18417 public static class BaseSavedState extends AbsSavedState { 18418 /** 18419 * Constructor used when reading from a parcel. Reads the state of the superclass. 18420 * 18421 * @param source 18422 */ 18423 public BaseSavedState(Parcel source) { 18424 super(source); 18425 } 18426 18427 /** 18428 * Constructor called by derived classes when creating their SavedState objects 18429 * 18430 * @param superState The state of the superclass of this view 18431 */ 18432 public BaseSavedState(Parcelable superState) { 18433 super(superState); 18434 } 18435 18436 public static final Parcelable.Creator<BaseSavedState> CREATOR = 18437 new Parcelable.Creator<BaseSavedState>() { 18438 public BaseSavedState createFromParcel(Parcel in) { 18439 return new BaseSavedState(in); 18440 } 18441 18442 public BaseSavedState[] newArray(int size) { 18443 return new BaseSavedState[size]; 18444 } 18445 }; 18446 } 18447 18448 /** 18449 * A set of information given to a view when it is attached to its parent 18450 * window. 18451 */ 18452 static class AttachInfo { 18453 interface Callbacks { 18454 void playSoundEffect(int effectId); 18455 boolean performHapticFeedback(int effectId, boolean always); 18456 } 18457 18458 /** 18459 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 18460 * to a Handler. This class contains the target (View) to invalidate and 18461 * the coordinates of the dirty rectangle. 18462 * 18463 * For performance purposes, this class also implements a pool of up to 18464 * POOL_LIMIT objects that get reused. This reduces memory allocations 18465 * whenever possible. 18466 */ 18467 static class InvalidateInfo { 18468 private static final int POOL_LIMIT = 10; 18469 18470 private static final SynchronizedPool<InvalidateInfo> sPool = 18471 new SynchronizedPool<InvalidateInfo>(POOL_LIMIT); 18472 18473 View target; 18474 18475 int left; 18476 int top; 18477 int right; 18478 int bottom; 18479 18480 public static InvalidateInfo obtain() { 18481 InvalidateInfo instance = sPool.acquire(); 18482 return (instance != null) ? instance : new InvalidateInfo(); 18483 } 18484 18485 public void recycle() { 18486 target = null; 18487 sPool.release(this); 18488 } 18489 } 18490 18491 final IWindowSession mSession; 18492 18493 final IWindow mWindow; 18494 18495 final IBinder mWindowToken; 18496 18497 final Display mDisplay; 18498 18499 final Callbacks mRootCallbacks; 18500 18501 HardwareCanvas mHardwareCanvas; 18502 18503 IWindowId mIWindowId; 18504 WindowId mWindowId; 18505 18506 /** 18507 * The top view of the hierarchy. 18508 */ 18509 View mRootView; 18510 18511 IBinder mPanelParentWindowToken; 18512 Surface mSurface; 18513 18514 boolean mHardwareAccelerated; 18515 boolean mHardwareAccelerationRequested; 18516 HardwareRenderer mHardwareRenderer; 18517 18518 boolean mScreenOn; 18519 18520 /** 18521 * Scale factor used by the compatibility mode 18522 */ 18523 float mApplicationScale; 18524 18525 /** 18526 * Indicates whether the application is in compatibility mode 18527 */ 18528 boolean mScalingRequired; 18529 18530 /** 18531 * If set, ViewRootImpl doesn't use its lame animation for when the window resizes. 18532 */ 18533 boolean mTurnOffWindowResizeAnim; 18534 18535 /** 18536 * Left position of this view's window 18537 */ 18538 int mWindowLeft; 18539 18540 /** 18541 * Top position of this view's window 18542 */ 18543 int mWindowTop; 18544 18545 /** 18546 * Indicates whether views need to use 32-bit drawing caches 18547 */ 18548 boolean mUse32BitDrawingCache; 18549 18550 /** 18551 * For windows that are full-screen but using insets to layout inside 18552 * of the screen areas, these are the current insets to appear inside 18553 * the overscan area of the display. 18554 */ 18555 final Rect mOverscanInsets = new Rect(); 18556 18557 /** 18558 * For windows that are full-screen but using insets to layout inside 18559 * of the screen decorations, these are the current insets for the 18560 * content of the window. 18561 */ 18562 final Rect mContentInsets = new Rect(); 18563 18564 /** 18565 * For windows that are full-screen but using insets to layout inside 18566 * of the screen decorations, these are the current insets for the 18567 * actual visible parts of the window. 18568 */ 18569 final Rect mVisibleInsets = new Rect(); 18570 18571 /** 18572 * The internal insets given by this window. This value is 18573 * supplied by the client (through 18574 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 18575 * be given to the window manager when changed to be used in laying 18576 * out windows behind it. 18577 */ 18578 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 18579 = new ViewTreeObserver.InternalInsetsInfo(); 18580 18581 /** 18582 * All views in the window's hierarchy that serve as scroll containers, 18583 * used to determine if the window can be resized or must be panned 18584 * to adjust for a soft input area. 18585 */ 18586 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 18587 18588 final KeyEvent.DispatcherState mKeyDispatchState 18589 = new KeyEvent.DispatcherState(); 18590 18591 /** 18592 * Indicates whether the view's window currently has the focus. 18593 */ 18594 boolean mHasWindowFocus; 18595 18596 /** 18597 * The current visibility of the window. 18598 */ 18599 int mWindowVisibility; 18600 18601 /** 18602 * Indicates the time at which drawing started to occur. 18603 */ 18604 long mDrawingTime; 18605 18606 /** 18607 * Indicates whether or not ignoring the DIRTY_MASK flags. 18608 */ 18609 boolean mIgnoreDirtyState; 18610 18611 /** 18612 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 18613 * to avoid clearing that flag prematurely. 18614 */ 18615 boolean mSetIgnoreDirtyState = false; 18616 18617 /** 18618 * Indicates whether the view's window is currently in touch mode. 18619 */ 18620 boolean mInTouchMode; 18621 18622 /** 18623 * Indicates that ViewAncestor should trigger a global layout change 18624 * the next time it performs a traversal 18625 */ 18626 boolean mRecomputeGlobalAttributes; 18627 18628 /** 18629 * Always report new attributes at next traversal. 18630 */ 18631 boolean mForceReportNewAttributes; 18632 18633 /** 18634 * Set during a traveral if any views want to keep the screen on. 18635 */ 18636 boolean mKeepScreenOn; 18637 18638 /** 18639 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 18640 */ 18641 int mSystemUiVisibility; 18642 18643 /** 18644 * Hack to force certain system UI visibility flags to be cleared. 18645 */ 18646 int mDisabledSystemUiVisibility; 18647 18648 /** 18649 * Last global system UI visibility reported by the window manager. 18650 */ 18651 int mGlobalSystemUiVisibility; 18652 18653 /** 18654 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 18655 * attached. 18656 */ 18657 boolean mHasSystemUiListeners; 18658 18659 /** 18660 * Set if the window has requested to extend into the overscan region 18661 * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN. 18662 */ 18663 boolean mOverscanRequested; 18664 18665 /** 18666 * Set if the visibility of any views has changed. 18667 */ 18668 boolean mViewVisibilityChanged; 18669 18670 /** 18671 * Set to true if a view has been scrolled. 18672 */ 18673 boolean mViewScrollChanged; 18674 18675 /** 18676 * Global to the view hierarchy used as a temporary for dealing with 18677 * x/y points in the transparent region computations. 18678 */ 18679 final int[] mTransparentLocation = new int[2]; 18680 18681 /** 18682 * Global to the view hierarchy used as a temporary for dealing with 18683 * x/y points in the ViewGroup.invalidateChild implementation. 18684 */ 18685 final int[] mInvalidateChildLocation = new int[2]; 18686 18687 18688 /** 18689 * Global to the view hierarchy used as a temporary for dealing with 18690 * x/y location when view is transformed. 18691 */ 18692 final float[] mTmpTransformLocation = new float[2]; 18693 18694 /** 18695 * The view tree observer used to dispatch global events like 18696 * layout, pre-draw, touch mode change, etc. 18697 */ 18698 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 18699 18700 /** 18701 * A Canvas used by the view hierarchy to perform bitmap caching. 18702 */ 18703 Canvas mCanvas; 18704 18705 /** 18706 * The view root impl. 18707 */ 18708 final ViewRootImpl mViewRootImpl; 18709 18710 /** 18711 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 18712 * handler can be used to pump events in the UI events queue. 18713 */ 18714 final Handler mHandler; 18715 18716 /** 18717 * Temporary for use in computing invalidate rectangles while 18718 * calling up the hierarchy. 18719 */ 18720 final Rect mTmpInvalRect = new Rect(); 18721 18722 /** 18723 * Temporary for use in computing hit areas with transformed views 18724 */ 18725 final RectF mTmpTransformRect = new RectF(); 18726 18727 /** 18728 * Temporary for use in transforming invalidation rect 18729 */ 18730 final Matrix mTmpMatrix = new Matrix(); 18731 18732 /** 18733 * Temporary for use in transforming invalidation rect 18734 */ 18735 final Transformation mTmpTransformation = new Transformation(); 18736 18737 /** 18738 * Temporary list for use in collecting focusable descendents of a view. 18739 */ 18740 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 18741 18742 /** 18743 * The id of the window for accessibility purposes. 18744 */ 18745 int mAccessibilityWindowId = View.NO_ID; 18746 18747 /** 18748 * Flags related to accessibility processing. 18749 * 18750 * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 18751 * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS 18752 */ 18753 int mAccessibilityFetchFlags; 18754 18755 /** 18756 * The drawable for highlighting accessibility focus. 18757 */ 18758 Drawable mAccessibilityFocusDrawable; 18759 18760 /** 18761 * Show where the margins, bounds and layout bounds are for each view. 18762 */ 18763 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 18764 18765 /** 18766 * Point used to compute visible regions. 18767 */ 18768 final Point mPoint = new Point(); 18769 18770 /** 18771 * Used to track which View originated a requestLayout() call, used when 18772 * requestLayout() is called during layout. 18773 */ 18774 View mViewRequestingLayout; 18775 18776 /** 18777 * Creates a new set of attachment information with the specified 18778 * events handler and thread. 18779 * 18780 * @param handler the events handler the view must use 18781 */ 18782 AttachInfo(IWindowSession session, IWindow window, Display display, 18783 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) { 18784 mSession = session; 18785 mWindow = window; 18786 mWindowToken = window.asBinder(); 18787 mDisplay = display; 18788 mViewRootImpl = viewRootImpl; 18789 mHandler = handler; 18790 mRootCallbacks = effectPlayer; 18791 } 18792 } 18793 18794 /** 18795 * <p>ScrollabilityCache holds various fields used by a View when scrolling 18796 * is supported. This avoids keeping too many unused fields in most 18797 * instances of View.</p> 18798 */ 18799 private static class ScrollabilityCache implements Runnable { 18800 18801 /** 18802 * Scrollbars are not visible 18803 */ 18804 public static final int OFF = 0; 18805 18806 /** 18807 * Scrollbars are visible 18808 */ 18809 public static final int ON = 1; 18810 18811 /** 18812 * Scrollbars are fading away 18813 */ 18814 public static final int FADING = 2; 18815 18816 public boolean fadeScrollBars; 18817 18818 public int fadingEdgeLength; 18819 public int scrollBarDefaultDelayBeforeFade; 18820 public int scrollBarFadeDuration; 18821 18822 public int scrollBarSize; 18823 public ScrollBarDrawable scrollBar; 18824 public float[] interpolatorValues; 18825 public View host; 18826 18827 public final Paint paint; 18828 public final Matrix matrix; 18829 public Shader shader; 18830 18831 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 18832 18833 private static final float[] OPAQUE = { 255 }; 18834 private static final float[] TRANSPARENT = { 0.0f }; 18835 18836 /** 18837 * When fading should start. This time moves into the future every time 18838 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 18839 */ 18840 public long fadeStartTime; 18841 18842 18843 /** 18844 * The current state of the scrollbars: ON, OFF, or FADING 18845 */ 18846 public int state = OFF; 18847 18848 private int mLastColor; 18849 18850 public ScrollabilityCache(ViewConfiguration configuration, View host) { 18851 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 18852 scrollBarSize = configuration.getScaledScrollBarSize(); 18853 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 18854 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 18855 18856 paint = new Paint(); 18857 matrix = new Matrix(); 18858 // use use a height of 1, and then wack the matrix each time we 18859 // actually use it. 18860 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 18861 paint.setShader(shader); 18862 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 18863 18864 this.host = host; 18865 } 18866 18867 public void setFadeColor(int color) { 18868 if (color != mLastColor) { 18869 mLastColor = color; 18870 18871 if (color != 0) { 18872 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 18873 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 18874 paint.setShader(shader); 18875 // Restore the default transfer mode (src_over) 18876 paint.setXfermode(null); 18877 } else { 18878 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 18879 paint.setShader(shader); 18880 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 18881 } 18882 } 18883 } 18884 18885 public void run() { 18886 long now = AnimationUtils.currentAnimationTimeMillis(); 18887 if (now >= fadeStartTime) { 18888 18889 // the animation fades the scrollbars out by changing 18890 // the opacity (alpha) from fully opaque to fully 18891 // transparent 18892 int nextFrame = (int) now; 18893 int framesCount = 0; 18894 18895 Interpolator interpolator = scrollBarInterpolator; 18896 18897 // Start opaque 18898 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 18899 18900 // End transparent 18901 nextFrame += scrollBarFadeDuration; 18902 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 18903 18904 state = FADING; 18905 18906 // Kick off the fade animation 18907 host.invalidate(true); 18908 } 18909 } 18910 } 18911 18912 /** 18913 * Resuable callback for sending 18914 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 18915 */ 18916 private class SendViewScrolledAccessibilityEvent implements Runnable { 18917 public volatile boolean mIsPending; 18918 18919 public void run() { 18920 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 18921 mIsPending = false; 18922 } 18923 } 18924 18925 /** 18926 * <p> 18927 * This class represents a delegate that can be registered in a {@link View} 18928 * to enhance accessibility support via composition rather via inheritance. 18929 * It is specifically targeted to widget developers that extend basic View 18930 * classes i.e. classes in package android.view, that would like their 18931 * applications to be backwards compatible. 18932 * </p> 18933 * <div class="special reference"> 18934 * <h3>Developer Guides</h3> 18935 * <p>For more information about making applications accessible, read the 18936 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 18937 * developer guide.</p> 18938 * </div> 18939 * <p> 18940 * A scenario in which a developer would like to use an accessibility delegate 18941 * is overriding a method introduced in a later API version then the minimal API 18942 * version supported by the application. For example, the method 18943 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 18944 * in API version 4 when the accessibility APIs were first introduced. If a 18945 * developer would like his application to run on API version 4 devices (assuming 18946 * all other APIs used by the application are version 4 or lower) and take advantage 18947 * of this method, instead of overriding the method which would break the application's 18948 * backwards compatibility, he can override the corresponding method in this 18949 * delegate and register the delegate in the target View if the API version of 18950 * the system is high enough i.e. the API version is same or higher to the API 18951 * version that introduced 18952 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 18953 * </p> 18954 * <p> 18955 * Here is an example implementation: 18956 * </p> 18957 * <code><pre><p> 18958 * if (Build.VERSION.SDK_INT >= 14) { 18959 * // If the API version is equal of higher than the version in 18960 * // which onInitializeAccessibilityNodeInfo was introduced we 18961 * // register a delegate with a customized implementation. 18962 * View view = findViewById(R.id.view_id); 18963 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 18964 * public void onInitializeAccessibilityNodeInfo(View host, 18965 * AccessibilityNodeInfo info) { 18966 * // Let the default implementation populate the info. 18967 * super.onInitializeAccessibilityNodeInfo(host, info); 18968 * // Set some other information. 18969 * info.setEnabled(host.isEnabled()); 18970 * } 18971 * }); 18972 * } 18973 * </code></pre></p> 18974 * <p> 18975 * This delegate contains methods that correspond to the accessibility methods 18976 * in View. If a delegate has been specified the implementation in View hands 18977 * off handling to the corresponding method in this delegate. The default 18978 * implementation the delegate methods behaves exactly as the corresponding 18979 * method in View for the case of no accessibility delegate been set. Hence, 18980 * to customize the behavior of a View method, clients can override only the 18981 * corresponding delegate method without altering the behavior of the rest 18982 * accessibility related methods of the host view. 18983 * </p> 18984 */ 18985 public static class AccessibilityDelegate { 18986 18987 /** 18988 * Sends an accessibility event of the given type. If accessibility is not 18989 * enabled this method has no effect. 18990 * <p> 18991 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 18992 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 18993 * been set. 18994 * </p> 18995 * 18996 * @param host The View hosting the delegate. 18997 * @param eventType The type of the event to send. 18998 * 18999 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 19000 */ 19001 public void sendAccessibilityEvent(View host, int eventType) { 19002 host.sendAccessibilityEventInternal(eventType); 19003 } 19004 19005 /** 19006 * Performs the specified accessibility action on the view. For 19007 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 19008 * <p> 19009 * The default implementation behaves as 19010 * {@link View#performAccessibilityAction(int, Bundle) 19011 * View#performAccessibilityAction(int, Bundle)} for the case of 19012 * no accessibility delegate been set. 19013 * </p> 19014 * 19015 * @param action The action to perform. 19016 * @return Whether the action was performed. 19017 * 19018 * @see View#performAccessibilityAction(int, Bundle) 19019 * View#performAccessibilityAction(int, Bundle) 19020 */ 19021 public boolean performAccessibilityAction(View host, int action, Bundle args) { 19022 return host.performAccessibilityActionInternal(action, args); 19023 } 19024 19025 /** 19026 * Sends an accessibility event. This method behaves exactly as 19027 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 19028 * empty {@link AccessibilityEvent} and does not perform a check whether 19029 * accessibility is enabled. 19030 * <p> 19031 * The default implementation behaves as 19032 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 19033 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 19034 * the case of no accessibility delegate been set. 19035 * </p> 19036 * 19037 * @param host The View hosting the delegate. 19038 * @param event The event to send. 19039 * 19040 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 19041 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 19042 */ 19043 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 19044 host.sendAccessibilityEventUncheckedInternal(event); 19045 } 19046 19047 /** 19048 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 19049 * to its children for adding their text content to the event. 19050 * <p> 19051 * The default implementation behaves as 19052 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 19053 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 19054 * the case of no accessibility delegate been set. 19055 * </p> 19056 * 19057 * @param host The View hosting the delegate. 19058 * @param event The event. 19059 * @return True if the event population was completed. 19060 * 19061 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 19062 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 19063 */ 19064 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 19065 return host.dispatchPopulateAccessibilityEventInternal(event); 19066 } 19067 19068 /** 19069 * Gives a chance to the host View to populate the accessibility event with its 19070 * text content. 19071 * <p> 19072 * The default implementation behaves as 19073 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 19074 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 19075 * the case of no accessibility delegate been set. 19076 * </p> 19077 * 19078 * @param host The View hosting the delegate. 19079 * @param event The accessibility event which to populate. 19080 * 19081 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 19082 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 19083 */ 19084 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 19085 host.onPopulateAccessibilityEventInternal(event); 19086 } 19087 19088 /** 19089 * Initializes an {@link AccessibilityEvent} with information about the 19090 * the host View which is the event source. 19091 * <p> 19092 * The default implementation behaves as 19093 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 19094 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 19095 * the case of no accessibility delegate been set. 19096 * </p> 19097 * 19098 * @param host The View hosting the delegate. 19099 * @param event The event to initialize. 19100 * 19101 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 19102 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 19103 */ 19104 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 19105 host.onInitializeAccessibilityEventInternal(event); 19106 } 19107 19108 /** 19109 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 19110 * <p> 19111 * The default implementation behaves as 19112 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 19113 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 19114 * the case of no accessibility delegate been set. 19115 * </p> 19116 * 19117 * @param host The View hosting the delegate. 19118 * @param info The instance to initialize. 19119 * 19120 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 19121 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 19122 */ 19123 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 19124 host.onInitializeAccessibilityNodeInfoInternal(info); 19125 } 19126 19127 /** 19128 * Called when a child of the host View has requested sending an 19129 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 19130 * to augment the event. 19131 * <p> 19132 * The default implementation behaves as 19133 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 19134 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 19135 * the case of no accessibility delegate been set. 19136 * </p> 19137 * 19138 * @param host The View hosting the delegate. 19139 * @param child The child which requests sending the event. 19140 * @param event The event to be sent. 19141 * @return True if the event should be sent 19142 * 19143 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 19144 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 19145 */ 19146 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 19147 AccessibilityEvent event) { 19148 return host.onRequestSendAccessibilityEventInternal(child, event); 19149 } 19150 19151 /** 19152 * Gets the provider for managing a virtual view hierarchy rooted at this View 19153 * and reported to {@link android.accessibilityservice.AccessibilityService}s 19154 * that explore the window content. 19155 * <p> 19156 * The default implementation behaves as 19157 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 19158 * the case of no accessibility delegate been set. 19159 * </p> 19160 * 19161 * @return The provider. 19162 * 19163 * @see AccessibilityNodeProvider 19164 */ 19165 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 19166 return null; 19167 } 19168 19169 /** 19170 * Returns an {@link AccessibilityNodeInfo} representing the host view from the 19171 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 19172 * This method is responsible for obtaining an accessibility node info from a 19173 * pool of reusable instances and calling 19174 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host 19175 * view to initialize the former. 19176 * <p> 19177 * <strong>Note:</strong> The client is responsible for recycling the obtained 19178 * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object 19179 * creation. 19180 * </p> 19181 * <p> 19182 * The default implementation behaves as 19183 * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for 19184 * the case of no accessibility delegate been set. 19185 * </p> 19186 * @return A populated {@link AccessibilityNodeInfo}. 19187 * 19188 * @see AccessibilityNodeInfo 19189 * 19190 * @hide 19191 */ 19192 public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) { 19193 return host.createAccessibilityNodeInfoInternal(); 19194 } 19195 } 19196 19197 private class MatchIdPredicate implements Predicate<View> { 19198 public int mId; 19199 19200 @Override 19201 public boolean apply(View view) { 19202 return (view.mID == mId); 19203 } 19204 } 19205 19206 private class MatchLabelForPredicate implements Predicate<View> { 19207 private int mLabeledId; 19208 19209 @Override 19210 public boolean apply(View view) { 19211 return (view.mLabelForId == mLabeledId); 19212 } 19213 } 19214 19215 private class SendViewStateChangedAccessibilityEvent implements Runnable { 19216 private boolean mPosted; 19217 private long mLastEventTimeMillis; 19218 19219 public void run() { 19220 mPosted = false; 19221 mLastEventTimeMillis = SystemClock.uptimeMillis(); 19222 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 19223 AccessibilityEvent event = AccessibilityEvent.obtain(); 19224 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 19225 event.setContentChangeType(AccessibilityEvent.CONTENT_CHANGE_TYPE_NODE); 19226 sendAccessibilityEventUnchecked(event); 19227 } 19228 } 19229 19230 public void runOrPost() { 19231 if (mPosted) { 19232 return; 19233 } 19234 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 19235 final long minEventIntevalMillis = 19236 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 19237 if (timeSinceLastMillis >= minEventIntevalMillis) { 19238 removeCallbacks(this); 19239 run(); 19240 } else { 19241 postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 19242 mPosted = true; 19243 } 19244 } 19245 } 19246 19247 /** 19248 * Dump all private flags in readable format, useful for documentation and 19249 * sanity checking. 19250 */ 19251 private static void dumpFlags() { 19252 final HashMap<String, String> found = Maps.newHashMap(); 19253 try { 19254 for (Field field : View.class.getDeclaredFields()) { 19255 final int modifiers = field.getModifiers(); 19256 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 19257 if (field.getType().equals(int.class)) { 19258 final int value = field.getInt(null); 19259 dumpFlag(found, field.getName(), value); 19260 } else if (field.getType().equals(int[].class)) { 19261 final int[] values = (int[]) field.get(null); 19262 for (int i = 0; i < values.length; i++) { 19263 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 19264 } 19265 } 19266 } 19267 } 19268 } catch (IllegalAccessException e) { 19269 throw new RuntimeException(e); 19270 } 19271 19272 final ArrayList<String> keys = Lists.newArrayList(); 19273 keys.addAll(found.keySet()); 19274 Collections.sort(keys); 19275 for (String key : keys) { 19276 Log.d(VIEW_LOG_TAG, found.get(key)); 19277 } 19278 } 19279 19280 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 19281 // Sort flags by prefix, then by bits, always keeping unique keys 19282 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 19283 final int prefix = name.indexOf('_'); 19284 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 19285 final String output = bits + " " + name; 19286 found.put(key, output); 19287 } 19288} 19289