View.java revision 8c549d6ffec427ed3f8f99eb25ffefaf55003893
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.Log; 55import android.util.Pool; 56import android.util.Poolable; 57import android.util.PoolableManager; 58import android.util.Pools; 59import android.util.Property; 60import android.util.SparseArray; 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_longClickable 627 * @attr ref android.R.styleable#View_minHeight 628 * @attr ref android.R.styleable#View_minWidth 629 * @attr ref android.R.styleable#View_nextFocusDown 630 * @attr ref android.R.styleable#View_nextFocusLeft 631 * @attr ref android.R.styleable#View_nextFocusRight 632 * @attr ref android.R.styleable#View_nextFocusUp 633 * @attr ref android.R.styleable#View_onClick 634 * @attr ref android.R.styleable#View_padding 635 * @attr ref android.R.styleable#View_paddingBottom 636 * @attr ref android.R.styleable#View_paddingLeft 637 * @attr ref android.R.styleable#View_paddingRight 638 * @attr ref android.R.styleable#View_paddingTop 639 * @attr ref android.R.styleable#View_paddingStart 640 * @attr ref android.R.styleable#View_paddingEnd 641 * @attr ref android.R.styleable#View_saveEnabled 642 * @attr ref android.R.styleable#View_rotation 643 * @attr ref android.R.styleable#View_rotationX 644 * @attr ref android.R.styleable#View_rotationY 645 * @attr ref android.R.styleable#View_scaleX 646 * @attr ref android.R.styleable#View_scaleY 647 * @attr ref android.R.styleable#View_scrollX 648 * @attr ref android.R.styleable#View_scrollY 649 * @attr ref android.R.styleable#View_scrollbarSize 650 * @attr ref android.R.styleable#View_scrollbarStyle 651 * @attr ref android.R.styleable#View_scrollbars 652 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 653 * @attr ref android.R.styleable#View_scrollbarFadeDuration 654 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 655 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 656 * @attr ref android.R.styleable#View_scrollbarThumbVertical 657 * @attr ref android.R.styleable#View_scrollbarTrackVertical 658 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 659 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 660 * @attr ref android.R.styleable#View_soundEffectsEnabled 661 * @attr ref android.R.styleable#View_tag 662 * @attr ref android.R.styleable#View_textAlignment 663 * @attr ref android.R.styleable#View_transformPivotX 664 * @attr ref android.R.styleable#View_transformPivotY 665 * @attr ref android.R.styleable#View_translationX 666 * @attr ref android.R.styleable#View_translationY 667 * @attr ref android.R.styleable#View_visibility 668 * 669 * @see android.view.ViewGroup 670 */ 671public class View implements Drawable.Callback, KeyEvent.Callback, 672 AccessibilityEventSource { 673 private static final boolean DBG = false; 674 675 /** 676 * The logging tag used by this class with android.util.Log. 677 */ 678 protected static final String VIEW_LOG_TAG = "View"; 679 680 /** 681 * When set to true, apps will draw debugging information about their layouts. 682 * 683 * @hide 684 */ 685 public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout"; 686 687 /** 688 * Used to mark a View that has no ID. 689 */ 690 public static final int NO_ID = -1; 691 692 /** 693 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 694 * calling setFlags. 695 */ 696 private static final int NOT_FOCUSABLE = 0x00000000; 697 698 /** 699 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 700 * setFlags. 701 */ 702 private static final int FOCUSABLE = 0x00000001; 703 704 /** 705 * Mask for use with setFlags indicating bits used for focus. 706 */ 707 private static final int FOCUSABLE_MASK = 0x00000001; 708 709 /** 710 * This view will adjust its padding to fit sytem windows (e.g. status bar) 711 */ 712 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 713 714 /** 715 * This view is visible. 716 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 717 * android:visibility}. 718 */ 719 public static final int VISIBLE = 0x00000000; 720 721 /** 722 * This view is invisible, but it still takes up space for layout purposes. 723 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 724 * android:visibility}. 725 */ 726 public static final int INVISIBLE = 0x00000004; 727 728 /** 729 * This view is invisible, and it doesn't take any space for layout 730 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 731 * android:visibility}. 732 */ 733 public static final int GONE = 0x00000008; 734 735 /** 736 * Mask for use with setFlags indicating bits used for visibility. 737 * {@hide} 738 */ 739 static final int VISIBILITY_MASK = 0x0000000C; 740 741 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 742 743 /** 744 * This view is enabled. Interpretation varies by subclass. 745 * Use with ENABLED_MASK when calling setFlags. 746 * {@hide} 747 */ 748 static final int ENABLED = 0x00000000; 749 750 /** 751 * This view is disabled. Interpretation varies by subclass. 752 * Use with ENABLED_MASK when calling setFlags. 753 * {@hide} 754 */ 755 static final int DISABLED = 0x00000020; 756 757 /** 758 * Mask for use with setFlags indicating bits used for indicating whether 759 * this view is enabled 760 * {@hide} 761 */ 762 static final int ENABLED_MASK = 0x00000020; 763 764 /** 765 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 766 * called and further optimizations will be performed. It is okay to have 767 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 768 * {@hide} 769 */ 770 static final int WILL_NOT_DRAW = 0x00000080; 771 772 /** 773 * Mask for use with setFlags indicating bits used for indicating whether 774 * this view is will draw 775 * {@hide} 776 */ 777 static final int DRAW_MASK = 0x00000080; 778 779 /** 780 * <p>This view doesn't show scrollbars.</p> 781 * {@hide} 782 */ 783 static final int SCROLLBARS_NONE = 0x00000000; 784 785 /** 786 * <p>This view shows horizontal scrollbars.</p> 787 * {@hide} 788 */ 789 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 790 791 /** 792 * <p>This view shows vertical scrollbars.</p> 793 * {@hide} 794 */ 795 static final int SCROLLBARS_VERTICAL = 0x00000200; 796 797 /** 798 * <p>Mask for use with setFlags indicating bits used for indicating which 799 * scrollbars are enabled.</p> 800 * {@hide} 801 */ 802 static final int SCROLLBARS_MASK = 0x00000300; 803 804 /** 805 * Indicates that the view should filter touches when its window is obscured. 806 * Refer to the class comments for more information about this security feature. 807 * {@hide} 808 */ 809 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 810 811 /** 812 * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate 813 * that they are optional and should be skipped if the window has 814 * requested system UI flags that ignore those insets for layout. 815 */ 816 static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800; 817 818 /** 819 * <p>This view doesn't show fading edges.</p> 820 * {@hide} 821 */ 822 static final int FADING_EDGE_NONE = 0x00000000; 823 824 /** 825 * <p>This view shows horizontal fading edges.</p> 826 * {@hide} 827 */ 828 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 829 830 /** 831 * <p>This view shows vertical fading edges.</p> 832 * {@hide} 833 */ 834 static final int FADING_EDGE_VERTICAL = 0x00002000; 835 836 /** 837 * <p>Mask for use with setFlags indicating bits used for indicating which 838 * fading edges are enabled.</p> 839 * {@hide} 840 */ 841 static final int FADING_EDGE_MASK = 0x00003000; 842 843 /** 844 * <p>Indicates this view can be clicked. When clickable, a View reacts 845 * to clicks by notifying the OnClickListener.<p> 846 * {@hide} 847 */ 848 static final int CLICKABLE = 0x00004000; 849 850 /** 851 * <p>Indicates this view is caching its drawing into a bitmap.</p> 852 * {@hide} 853 */ 854 static final int DRAWING_CACHE_ENABLED = 0x00008000; 855 856 /** 857 * <p>Indicates that no icicle should be saved for this view.<p> 858 * {@hide} 859 */ 860 static final int SAVE_DISABLED = 0x000010000; 861 862 /** 863 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 864 * property.</p> 865 * {@hide} 866 */ 867 static final int SAVE_DISABLED_MASK = 0x000010000; 868 869 /** 870 * <p>Indicates that no drawing cache should ever be created for this view.<p> 871 * {@hide} 872 */ 873 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 874 875 /** 876 * <p>Indicates this view can take / keep focus when int touch mode.</p> 877 * {@hide} 878 */ 879 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 880 881 /** 882 * <p>Enables low quality mode for the drawing cache.</p> 883 */ 884 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 885 886 /** 887 * <p>Enables high quality mode for the drawing cache.</p> 888 */ 889 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 890 891 /** 892 * <p>Enables automatic quality mode for the drawing cache.</p> 893 */ 894 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 895 896 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 897 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 898 }; 899 900 /** 901 * <p>Mask for use with setFlags indicating bits used for the cache 902 * quality property.</p> 903 * {@hide} 904 */ 905 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 906 907 /** 908 * <p> 909 * Indicates this view can be long clicked. When long clickable, a View 910 * reacts to long clicks by notifying the OnLongClickListener or showing a 911 * context menu. 912 * </p> 913 * {@hide} 914 */ 915 static final int LONG_CLICKABLE = 0x00200000; 916 917 /** 918 * <p>Indicates that this view gets its drawable states from its direct parent 919 * and ignores its original internal states.</p> 920 * 921 * @hide 922 */ 923 static final int DUPLICATE_PARENT_STATE = 0x00400000; 924 925 /** 926 * The scrollbar style to display the scrollbars inside the content area, 927 * without increasing the padding. The scrollbars will be overlaid with 928 * translucency on the view's content. 929 */ 930 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 931 932 /** 933 * The scrollbar style to display the scrollbars inside the padded area, 934 * increasing the padding of the view. The scrollbars will not overlap the 935 * content area of the view. 936 */ 937 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 938 939 /** 940 * The scrollbar style to display the scrollbars at the edge of the view, 941 * without increasing the padding. The scrollbars will be overlaid with 942 * translucency. 943 */ 944 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 945 946 /** 947 * The scrollbar style to display the scrollbars at the edge of the view, 948 * increasing the padding of the view. The scrollbars will only overlap the 949 * background, if any. 950 */ 951 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 952 953 /** 954 * Mask to check if the scrollbar style is overlay or inset. 955 * {@hide} 956 */ 957 static final int SCROLLBARS_INSET_MASK = 0x01000000; 958 959 /** 960 * Mask to check if the scrollbar style is inside or outside. 961 * {@hide} 962 */ 963 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 964 965 /** 966 * Mask for scrollbar style. 967 * {@hide} 968 */ 969 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 970 971 /** 972 * View flag indicating that the screen should remain on while the 973 * window containing this view is visible to the user. This effectively 974 * takes care of automatically setting the WindowManager's 975 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 976 */ 977 public static final int KEEP_SCREEN_ON = 0x04000000; 978 979 /** 980 * View flag indicating whether this view should have sound effects enabled 981 * for events such as clicking and touching. 982 */ 983 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 984 985 /** 986 * View flag indicating whether this view should have haptic feedback 987 * enabled for events such as long presses. 988 */ 989 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 990 991 /** 992 * <p>Indicates that the view hierarchy should stop saving state when 993 * it reaches this view. If state saving is initiated immediately at 994 * the view, it will be allowed. 995 * {@hide} 996 */ 997 static final int PARENT_SAVE_DISABLED = 0x20000000; 998 999 /** 1000 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 1001 * {@hide} 1002 */ 1003 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 1004 1005 /** 1006 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1007 * should add all focusable Views regardless if they are focusable in touch mode. 1008 */ 1009 public static final int FOCUSABLES_ALL = 0x00000000; 1010 1011 /** 1012 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1013 * should add only Views focusable in touch mode. 1014 */ 1015 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1016 1017 /** 1018 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1019 * item. 1020 */ 1021 public static final int FOCUS_BACKWARD = 0x00000001; 1022 1023 /** 1024 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1025 * item. 1026 */ 1027 public static final int FOCUS_FORWARD = 0x00000002; 1028 1029 /** 1030 * Use with {@link #focusSearch(int)}. Move focus to the left. 1031 */ 1032 public static final int FOCUS_LEFT = 0x00000011; 1033 1034 /** 1035 * Use with {@link #focusSearch(int)}. Move focus up. 1036 */ 1037 public static final int FOCUS_UP = 0x00000021; 1038 1039 /** 1040 * Use with {@link #focusSearch(int)}. Move focus to the right. 1041 */ 1042 public static final int FOCUS_RIGHT = 0x00000042; 1043 1044 /** 1045 * Use with {@link #focusSearch(int)}. Move focus down. 1046 */ 1047 public static final int FOCUS_DOWN = 0x00000082; 1048 1049 /** 1050 * Bits of {@link #getMeasuredWidthAndState()} and 1051 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1052 */ 1053 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1054 1055 /** 1056 * Bits of {@link #getMeasuredWidthAndState()} and 1057 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1058 */ 1059 public static final int MEASURED_STATE_MASK = 0xff000000; 1060 1061 /** 1062 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1063 * for functions that combine both width and height into a single int, 1064 * such as {@link #getMeasuredState()} and the childState argument of 1065 * {@link #resolveSizeAndState(int, int, int)}. 1066 */ 1067 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1068 1069 /** 1070 * Bit of {@link #getMeasuredWidthAndState()} and 1071 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1072 * is smaller that the space the view would like to have. 1073 */ 1074 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1075 1076 /** 1077 * Base View state sets 1078 */ 1079 // Singles 1080 /** 1081 * Indicates the view has no states set. States are used with 1082 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1083 * view depending on its state. 1084 * 1085 * @see android.graphics.drawable.Drawable 1086 * @see #getDrawableState() 1087 */ 1088 protected static final int[] EMPTY_STATE_SET; 1089 /** 1090 * Indicates the view is enabled. States are used with 1091 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1092 * view depending on its state. 1093 * 1094 * @see android.graphics.drawable.Drawable 1095 * @see #getDrawableState() 1096 */ 1097 protected static final int[] ENABLED_STATE_SET; 1098 /** 1099 * Indicates the view is focused. States are used with 1100 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1101 * view depending on its state. 1102 * 1103 * @see android.graphics.drawable.Drawable 1104 * @see #getDrawableState() 1105 */ 1106 protected static final int[] FOCUSED_STATE_SET; 1107 /** 1108 * Indicates the view is selected. States are used with 1109 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1110 * view depending on its state. 1111 * 1112 * @see android.graphics.drawable.Drawable 1113 * @see #getDrawableState() 1114 */ 1115 protected static final int[] SELECTED_STATE_SET; 1116 /** 1117 * Indicates the view is pressed. States are used with 1118 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1119 * view depending on its state. 1120 * 1121 * @see android.graphics.drawable.Drawable 1122 * @see #getDrawableState() 1123 * @hide 1124 */ 1125 protected static final int[] PRESSED_STATE_SET; 1126 /** 1127 * Indicates the view's window has focus. States are used with 1128 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1129 * view depending on its state. 1130 * 1131 * @see android.graphics.drawable.Drawable 1132 * @see #getDrawableState() 1133 */ 1134 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1135 // Doubles 1136 /** 1137 * Indicates the view is enabled and has the focus. 1138 * 1139 * @see #ENABLED_STATE_SET 1140 * @see #FOCUSED_STATE_SET 1141 */ 1142 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1143 /** 1144 * Indicates the view is enabled and selected. 1145 * 1146 * @see #ENABLED_STATE_SET 1147 * @see #SELECTED_STATE_SET 1148 */ 1149 protected static final int[] ENABLED_SELECTED_STATE_SET; 1150 /** 1151 * Indicates the view is enabled and that its window has focus. 1152 * 1153 * @see #ENABLED_STATE_SET 1154 * @see #WINDOW_FOCUSED_STATE_SET 1155 */ 1156 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1157 /** 1158 * Indicates the view is focused and selected. 1159 * 1160 * @see #FOCUSED_STATE_SET 1161 * @see #SELECTED_STATE_SET 1162 */ 1163 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1164 /** 1165 * Indicates the view has the focus and that its window has the focus. 1166 * 1167 * @see #FOCUSED_STATE_SET 1168 * @see #WINDOW_FOCUSED_STATE_SET 1169 */ 1170 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1171 /** 1172 * Indicates the view is selected and that its window has the focus. 1173 * 1174 * @see #SELECTED_STATE_SET 1175 * @see #WINDOW_FOCUSED_STATE_SET 1176 */ 1177 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1178 // Triples 1179 /** 1180 * Indicates the view is enabled, focused and selected. 1181 * 1182 * @see #ENABLED_STATE_SET 1183 * @see #FOCUSED_STATE_SET 1184 * @see #SELECTED_STATE_SET 1185 */ 1186 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1187 /** 1188 * Indicates the view is enabled, focused and its window has the focus. 1189 * 1190 * @see #ENABLED_STATE_SET 1191 * @see #FOCUSED_STATE_SET 1192 * @see #WINDOW_FOCUSED_STATE_SET 1193 */ 1194 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1195 /** 1196 * Indicates the view is enabled, selected and its window has the focus. 1197 * 1198 * @see #ENABLED_STATE_SET 1199 * @see #SELECTED_STATE_SET 1200 * @see #WINDOW_FOCUSED_STATE_SET 1201 */ 1202 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1203 /** 1204 * Indicates the view is focused, selected and its window has the focus. 1205 * 1206 * @see #FOCUSED_STATE_SET 1207 * @see #SELECTED_STATE_SET 1208 * @see #WINDOW_FOCUSED_STATE_SET 1209 */ 1210 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1211 /** 1212 * Indicates the view is enabled, focused, selected and its window 1213 * has the focus. 1214 * 1215 * @see #ENABLED_STATE_SET 1216 * @see #FOCUSED_STATE_SET 1217 * @see #SELECTED_STATE_SET 1218 * @see #WINDOW_FOCUSED_STATE_SET 1219 */ 1220 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1221 /** 1222 * Indicates the view is pressed and its window has the focus. 1223 * 1224 * @see #PRESSED_STATE_SET 1225 * @see #WINDOW_FOCUSED_STATE_SET 1226 */ 1227 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1228 /** 1229 * Indicates the view is pressed and selected. 1230 * 1231 * @see #PRESSED_STATE_SET 1232 * @see #SELECTED_STATE_SET 1233 */ 1234 protected static final int[] PRESSED_SELECTED_STATE_SET; 1235 /** 1236 * Indicates the view is pressed, selected and its window has the focus. 1237 * 1238 * @see #PRESSED_STATE_SET 1239 * @see #SELECTED_STATE_SET 1240 * @see #WINDOW_FOCUSED_STATE_SET 1241 */ 1242 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1243 /** 1244 * Indicates the view is pressed and focused. 1245 * 1246 * @see #PRESSED_STATE_SET 1247 * @see #FOCUSED_STATE_SET 1248 */ 1249 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1250 /** 1251 * Indicates the view is pressed, focused and its window has the focus. 1252 * 1253 * @see #PRESSED_STATE_SET 1254 * @see #FOCUSED_STATE_SET 1255 * @see #WINDOW_FOCUSED_STATE_SET 1256 */ 1257 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1258 /** 1259 * Indicates the view is pressed, focused and selected. 1260 * 1261 * @see #PRESSED_STATE_SET 1262 * @see #SELECTED_STATE_SET 1263 * @see #FOCUSED_STATE_SET 1264 */ 1265 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1266 /** 1267 * Indicates the view is pressed, focused, selected and its window has the focus. 1268 * 1269 * @see #PRESSED_STATE_SET 1270 * @see #FOCUSED_STATE_SET 1271 * @see #SELECTED_STATE_SET 1272 * @see #WINDOW_FOCUSED_STATE_SET 1273 */ 1274 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1275 /** 1276 * Indicates the view is pressed and enabled. 1277 * 1278 * @see #PRESSED_STATE_SET 1279 * @see #ENABLED_STATE_SET 1280 */ 1281 protected static final int[] PRESSED_ENABLED_STATE_SET; 1282 /** 1283 * Indicates the view is pressed, enabled and its window has the focus. 1284 * 1285 * @see #PRESSED_STATE_SET 1286 * @see #ENABLED_STATE_SET 1287 * @see #WINDOW_FOCUSED_STATE_SET 1288 */ 1289 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1290 /** 1291 * Indicates the view is pressed, enabled and selected. 1292 * 1293 * @see #PRESSED_STATE_SET 1294 * @see #ENABLED_STATE_SET 1295 * @see #SELECTED_STATE_SET 1296 */ 1297 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1298 /** 1299 * Indicates the view is pressed, enabled, selected and its window has the 1300 * focus. 1301 * 1302 * @see #PRESSED_STATE_SET 1303 * @see #ENABLED_STATE_SET 1304 * @see #SELECTED_STATE_SET 1305 * @see #WINDOW_FOCUSED_STATE_SET 1306 */ 1307 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1308 /** 1309 * Indicates the view is pressed, enabled and focused. 1310 * 1311 * @see #PRESSED_STATE_SET 1312 * @see #ENABLED_STATE_SET 1313 * @see #FOCUSED_STATE_SET 1314 */ 1315 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1316 /** 1317 * Indicates the view is pressed, enabled, focused and its window has the 1318 * focus. 1319 * 1320 * @see #PRESSED_STATE_SET 1321 * @see #ENABLED_STATE_SET 1322 * @see #FOCUSED_STATE_SET 1323 * @see #WINDOW_FOCUSED_STATE_SET 1324 */ 1325 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1326 /** 1327 * Indicates the view is pressed, enabled, focused and selected. 1328 * 1329 * @see #PRESSED_STATE_SET 1330 * @see #ENABLED_STATE_SET 1331 * @see #SELECTED_STATE_SET 1332 * @see #FOCUSED_STATE_SET 1333 */ 1334 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1335 /** 1336 * Indicates the view is pressed, enabled, focused, selected and its window 1337 * has the focus. 1338 * 1339 * @see #PRESSED_STATE_SET 1340 * @see #ENABLED_STATE_SET 1341 * @see #SELECTED_STATE_SET 1342 * @see #FOCUSED_STATE_SET 1343 * @see #WINDOW_FOCUSED_STATE_SET 1344 */ 1345 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1346 1347 /** 1348 * The order here is very important to {@link #getDrawableState()} 1349 */ 1350 private static final int[][] VIEW_STATE_SETS; 1351 1352 static final int VIEW_STATE_WINDOW_FOCUSED = 1; 1353 static final int VIEW_STATE_SELECTED = 1 << 1; 1354 static final int VIEW_STATE_FOCUSED = 1 << 2; 1355 static final int VIEW_STATE_ENABLED = 1 << 3; 1356 static final int VIEW_STATE_PRESSED = 1 << 4; 1357 static final int VIEW_STATE_ACTIVATED = 1 << 5; 1358 static final int VIEW_STATE_ACCELERATED = 1 << 6; 1359 static final int VIEW_STATE_HOVERED = 1 << 7; 1360 static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8; 1361 static final int VIEW_STATE_DRAG_HOVERED = 1 << 9; 1362 1363 static final int[] VIEW_STATE_IDS = new int[] { 1364 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED, 1365 R.attr.state_selected, VIEW_STATE_SELECTED, 1366 R.attr.state_focused, VIEW_STATE_FOCUSED, 1367 R.attr.state_enabled, VIEW_STATE_ENABLED, 1368 R.attr.state_pressed, VIEW_STATE_PRESSED, 1369 R.attr.state_activated, VIEW_STATE_ACTIVATED, 1370 R.attr.state_accelerated, VIEW_STATE_ACCELERATED, 1371 R.attr.state_hovered, VIEW_STATE_HOVERED, 1372 R.attr.state_drag_can_accept, VIEW_STATE_DRAG_CAN_ACCEPT, 1373 R.attr.state_drag_hovered, VIEW_STATE_DRAG_HOVERED 1374 }; 1375 1376 static { 1377 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) { 1378 throw new IllegalStateException( 1379 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array"); 1380 } 1381 int[] orderedIds = new int[VIEW_STATE_IDS.length]; 1382 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) { 1383 int viewState = R.styleable.ViewDrawableStates[i]; 1384 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) { 1385 if (VIEW_STATE_IDS[j] == viewState) { 1386 orderedIds[i * 2] = viewState; 1387 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1]; 1388 } 1389 } 1390 } 1391 final int NUM_BITS = VIEW_STATE_IDS.length / 2; 1392 VIEW_STATE_SETS = new int[1 << NUM_BITS][]; 1393 for (int i = 0; i < VIEW_STATE_SETS.length; i++) { 1394 int numBits = Integer.bitCount(i); 1395 int[] set = new int[numBits]; 1396 int pos = 0; 1397 for (int j = 0; j < orderedIds.length; j += 2) { 1398 if ((i & orderedIds[j+1]) != 0) { 1399 set[pos++] = orderedIds[j]; 1400 } 1401 } 1402 VIEW_STATE_SETS[i] = set; 1403 } 1404 1405 EMPTY_STATE_SET = VIEW_STATE_SETS[0]; 1406 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED]; 1407 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED]; 1408 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1409 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED]; 1410 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED]; 1411 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1412 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED]; 1413 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1414 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED]; 1415 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1416 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1417 | VIEW_STATE_FOCUSED]; 1418 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED]; 1419 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1420 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED]; 1421 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1422 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED]; 1423 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1424 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1425 | VIEW_STATE_ENABLED]; 1426 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1427 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED]; 1428 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1429 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1430 | VIEW_STATE_ENABLED]; 1431 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1432 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1433 | VIEW_STATE_ENABLED]; 1434 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1435 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1436 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED]; 1437 1438 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED]; 1439 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1440 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED]; 1441 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1442 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED]; 1443 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1444 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1445 | VIEW_STATE_PRESSED]; 1446 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1447 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1448 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1449 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1450 | VIEW_STATE_PRESSED]; 1451 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1452 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1453 | VIEW_STATE_PRESSED]; 1454 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1455 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1456 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1457 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[ 1458 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1459 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1460 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED 1461 | VIEW_STATE_PRESSED]; 1462 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1463 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED 1464 | VIEW_STATE_PRESSED]; 1465 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1466 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1467 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1468 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1469 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED 1470 | VIEW_STATE_PRESSED]; 1471 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1472 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1473 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1474 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1475 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1476 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1477 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1478 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1479 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED 1480 | VIEW_STATE_PRESSED]; 1481 } 1482 1483 /** 1484 * Accessibility event types that are dispatched for text population. 1485 */ 1486 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 1487 AccessibilityEvent.TYPE_VIEW_CLICKED 1488 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 1489 | AccessibilityEvent.TYPE_VIEW_SELECTED 1490 | AccessibilityEvent.TYPE_VIEW_FOCUSED 1491 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 1492 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 1493 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 1494 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 1495 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED 1496 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED 1497 | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY; 1498 1499 /** 1500 * Temporary Rect currently for use in setBackground(). This will probably 1501 * be extended in the future to hold our own class with more than just 1502 * a Rect. :) 1503 */ 1504 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1505 1506 /** 1507 * Map used to store views' tags. 1508 */ 1509 private SparseArray<Object> mKeyedTags; 1510 1511 /** 1512 * The next available accessibility id. 1513 */ 1514 private static int sNextAccessibilityViewId; 1515 1516 /** 1517 * The animation currently associated with this view. 1518 * @hide 1519 */ 1520 protected Animation mCurrentAnimation = null; 1521 1522 /** 1523 * Width as measured during measure pass. 1524 * {@hide} 1525 */ 1526 @ViewDebug.ExportedProperty(category = "measurement") 1527 int mMeasuredWidth; 1528 1529 /** 1530 * Height as measured during measure pass. 1531 * {@hide} 1532 */ 1533 @ViewDebug.ExportedProperty(category = "measurement") 1534 int mMeasuredHeight; 1535 1536 /** 1537 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1538 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1539 * its display list. This flag, used only when hw accelerated, allows us to clear the 1540 * flag while retaining this information until it's needed (at getDisplayList() time and 1541 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1542 * 1543 * {@hide} 1544 */ 1545 boolean mRecreateDisplayList = false; 1546 1547 /** 1548 * The view's identifier. 1549 * {@hide} 1550 * 1551 * @see #setId(int) 1552 * @see #getId() 1553 */ 1554 @ViewDebug.ExportedProperty(resolveId = true) 1555 int mID = NO_ID; 1556 1557 /** 1558 * The stable ID of this view for accessibility purposes. 1559 */ 1560 int mAccessibilityViewId = NO_ID; 1561 1562 /** 1563 * @hide 1564 */ 1565 private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 1566 1567 /** 1568 * The view's tag. 1569 * {@hide} 1570 * 1571 * @see #setTag(Object) 1572 * @see #getTag() 1573 */ 1574 protected Object mTag; 1575 1576 // for mPrivateFlags: 1577 /** {@hide} */ 1578 static final int PFLAG_WANTS_FOCUS = 0x00000001; 1579 /** {@hide} */ 1580 static final int PFLAG_FOCUSED = 0x00000002; 1581 /** {@hide} */ 1582 static final int PFLAG_SELECTED = 0x00000004; 1583 /** {@hide} */ 1584 static final int PFLAG_IS_ROOT_NAMESPACE = 0x00000008; 1585 /** {@hide} */ 1586 static final int PFLAG_HAS_BOUNDS = 0x00000010; 1587 /** {@hide} */ 1588 static final int PFLAG_DRAWN = 0x00000020; 1589 /** 1590 * When this flag is set, this view is running an animation on behalf of its 1591 * children and should therefore not cancel invalidate requests, even if they 1592 * lie outside of this view's bounds. 1593 * 1594 * {@hide} 1595 */ 1596 static final int PFLAG_DRAW_ANIMATION = 0x00000040; 1597 /** {@hide} */ 1598 static final int PFLAG_SKIP_DRAW = 0x00000080; 1599 /** {@hide} */ 1600 static final int PFLAG_ONLY_DRAWS_BACKGROUND = 0x00000100; 1601 /** {@hide} */ 1602 static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1603 /** {@hide} */ 1604 static final int PFLAG_DRAWABLE_STATE_DIRTY = 0x00000400; 1605 /** {@hide} */ 1606 static final int PFLAG_MEASURED_DIMENSION_SET = 0x00000800; 1607 /** {@hide} */ 1608 static final int PFLAG_FORCE_LAYOUT = 0x00001000; 1609 /** {@hide} */ 1610 static final int PFLAG_LAYOUT_REQUIRED = 0x00002000; 1611 1612 private static final int PFLAG_PRESSED = 0x00004000; 1613 1614 /** {@hide} */ 1615 static final int PFLAG_DRAWING_CACHE_VALID = 0x00008000; 1616 /** 1617 * Flag used to indicate that this view should be drawn once more (and only once 1618 * more) after its animation has completed. 1619 * {@hide} 1620 */ 1621 static final int PFLAG_ANIMATION_STARTED = 0x00010000; 1622 1623 private static final int PFLAG_SAVE_STATE_CALLED = 0x00020000; 1624 1625 /** 1626 * Indicates that the View returned true when onSetAlpha() was called and that 1627 * the alpha must be restored. 1628 * {@hide} 1629 */ 1630 static final int PFLAG_ALPHA_SET = 0x00040000; 1631 1632 /** 1633 * Set by {@link #setScrollContainer(boolean)}. 1634 */ 1635 static final int PFLAG_SCROLL_CONTAINER = 0x00080000; 1636 1637 /** 1638 * Set by {@link #setScrollContainer(boolean)}. 1639 */ 1640 static final int PFLAG_SCROLL_CONTAINER_ADDED = 0x00100000; 1641 1642 /** 1643 * View flag indicating whether this view was invalidated (fully or partially.) 1644 * 1645 * @hide 1646 */ 1647 static final int PFLAG_DIRTY = 0x00200000; 1648 1649 /** 1650 * View flag indicating whether this view was invalidated by an opaque 1651 * invalidate request. 1652 * 1653 * @hide 1654 */ 1655 static final int PFLAG_DIRTY_OPAQUE = 0x00400000; 1656 1657 /** 1658 * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}. 1659 * 1660 * @hide 1661 */ 1662 static final int PFLAG_DIRTY_MASK = 0x00600000; 1663 1664 /** 1665 * Indicates whether the background is opaque. 1666 * 1667 * @hide 1668 */ 1669 static final int PFLAG_OPAQUE_BACKGROUND = 0x00800000; 1670 1671 /** 1672 * Indicates whether the scrollbars are opaque. 1673 * 1674 * @hide 1675 */ 1676 static final int PFLAG_OPAQUE_SCROLLBARS = 0x01000000; 1677 1678 /** 1679 * Indicates whether the view is opaque. 1680 * 1681 * @hide 1682 */ 1683 static final int PFLAG_OPAQUE_MASK = 0x01800000; 1684 1685 /** 1686 * Indicates a prepressed state; 1687 * the short time between ACTION_DOWN and recognizing 1688 * a 'real' press. Prepressed is used to recognize quick taps 1689 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1690 * 1691 * @hide 1692 */ 1693 private static final int PFLAG_PREPRESSED = 0x02000000; 1694 1695 /** 1696 * Indicates whether the view is temporarily detached. 1697 * 1698 * @hide 1699 */ 1700 static final int PFLAG_CANCEL_NEXT_UP_EVENT = 0x04000000; 1701 1702 /** 1703 * Indicates that we should awaken scroll bars once attached 1704 * 1705 * @hide 1706 */ 1707 private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1708 1709 /** 1710 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1711 * @hide 1712 */ 1713 private static final int PFLAG_HOVERED = 0x10000000; 1714 1715 /** 1716 * Indicates that pivotX or pivotY were explicitly set and we should not assume the center 1717 * for transform operations 1718 * 1719 * @hide 1720 */ 1721 private static final int PFLAG_PIVOT_EXPLICITLY_SET = 0x20000000; 1722 1723 /** {@hide} */ 1724 static final int PFLAG_ACTIVATED = 0x40000000; 1725 1726 /** 1727 * Indicates that this view was specifically invalidated, not just dirtied because some 1728 * child view was invalidated. The flag is used to determine when we need to recreate 1729 * a view's display list (as opposed to just returning a reference to its existing 1730 * display list). 1731 * 1732 * @hide 1733 */ 1734 static final int PFLAG_INVALIDATED = 0x80000000; 1735 1736 /** 1737 * Masks for mPrivateFlags2, as generated by dumpFlags(): 1738 * 1739 * -------|-------|-------|-------| 1740 * PFLAG2_TEXT_ALIGNMENT_FLAGS[0] 1741 * PFLAG2_TEXT_DIRECTION_FLAGS[0] 1742 * 1 PFLAG2_DRAG_CAN_ACCEPT 1743 * 1 PFLAG2_DRAG_HOVERED 1744 * 1 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT 1745 * 11 PFLAG2_TEXT_DIRECTION_MASK_SHIFT 1746 * 1 1 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT 1747 * 11 PFLAG2_LAYOUT_DIRECTION_MASK 1748 * 11 1 PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 1749 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL 1750 * 1 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT 1751 * 1 1 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT 1752 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED 1753 * 11 PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK 1754 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[1] 1755 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[2] 1756 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[3] 1757 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[4] 1758 * 1 1 PFLAG2_TEXT_DIRECTION_FLAGS[5] 1759 * 111 PFLAG2_TEXT_DIRECTION_MASK 1760 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED 1761 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT 1762 * 111 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK 1763 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[1] 1764 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[2] 1765 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[3] 1766 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[4] 1767 * 1 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[5] 1768 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[6] 1769 * 111 PFLAG2_TEXT_ALIGNMENT_MASK 1770 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED 1771 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT 1772 * 111 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK 1773 * 11 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK 1774 * 1 PFLAG2_HAS_TRANSIENT_STATE 1775 * 1 PFLAG2_ACCESSIBILITY_FOCUSED 1776 * 1 PFLAG2_ACCESSIBILITY_STATE_CHANGED 1777 * 1 PFLAG2_VIEW_QUICK_REJECTED 1778 * 1 PFLAG2_PADDING_RESOLVED 1779 * -------|-------|-------|-------| 1780 */ 1781 1782 /** 1783 * Indicates that this view has reported that it can accept the current drag's content. 1784 * Cleared when the drag operation concludes. 1785 * @hide 1786 */ 1787 static final int PFLAG2_DRAG_CAN_ACCEPT = 0x00000001; 1788 1789 /** 1790 * Indicates that this view is currently directly under the drag location in a 1791 * drag-and-drop operation involving content that it can accept. Cleared when 1792 * the drag exits the view, or when the drag operation concludes. 1793 * @hide 1794 */ 1795 static final int PFLAG2_DRAG_HOVERED = 0x00000002; 1796 1797 /** 1798 * Horizontal layout direction of this view is from Left to Right. 1799 * Use with {@link #setLayoutDirection}. 1800 */ 1801 public static final int LAYOUT_DIRECTION_LTR = 0; 1802 1803 /** 1804 * Horizontal layout direction of this view is from Right to Left. 1805 * Use with {@link #setLayoutDirection}. 1806 */ 1807 public static final int LAYOUT_DIRECTION_RTL = 1; 1808 1809 /** 1810 * Horizontal layout direction of this view is inherited from its parent. 1811 * Use with {@link #setLayoutDirection}. 1812 */ 1813 public static final int LAYOUT_DIRECTION_INHERIT = 2; 1814 1815 /** 1816 * Horizontal layout direction of this view is from deduced from the default language 1817 * script for the locale. Use with {@link #setLayoutDirection}. 1818 */ 1819 public static final int LAYOUT_DIRECTION_LOCALE = 3; 1820 1821 /** 1822 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1823 * @hide 1824 */ 1825 static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2; 1826 1827 /** 1828 * Mask for use with private flags indicating bits used for horizontal layout direction. 1829 * @hide 1830 */ 1831 static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1832 1833 /** 1834 * Indicates whether the view horizontal layout direction has been resolved and drawn to the 1835 * right-to-left direction. 1836 * @hide 1837 */ 1838 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1839 1840 /** 1841 * Indicates whether the view horizontal layout direction has been resolved. 1842 * @hide 1843 */ 1844 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1845 1846 /** 1847 * Mask for use with private flags indicating bits used for resolved horizontal layout direction. 1848 * @hide 1849 */ 1850 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C 1851 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1852 1853 /* 1854 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct 1855 * flag value. 1856 * @hide 1857 */ 1858 private static final int[] LAYOUT_DIRECTION_FLAGS = { 1859 LAYOUT_DIRECTION_LTR, 1860 LAYOUT_DIRECTION_RTL, 1861 LAYOUT_DIRECTION_INHERIT, 1862 LAYOUT_DIRECTION_LOCALE 1863 }; 1864 1865 /** 1866 * Default horizontal layout direction. 1867 * @hide 1868 */ 1869 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 1870 1871 /** 1872 * Indicates that the view is tracking some sort of transient state 1873 * that the app should not need to be aware of, but that the framework 1874 * should take special care to preserve. 1875 * 1876 * @hide 1877 */ 1878 static final int PFLAG2_HAS_TRANSIENT_STATE = 0x1 << 22; 1879 1880 /** 1881 * Text direction is inherited thru {@link ViewGroup} 1882 */ 1883 public static final int TEXT_DIRECTION_INHERIT = 0; 1884 1885 /** 1886 * Text direction is using "first strong algorithm". The first strong directional character 1887 * determines the paragraph direction. If there is no strong directional character, the 1888 * paragraph direction is the view's resolved layout direction. 1889 */ 1890 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 1891 1892 /** 1893 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 1894 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 1895 * If there are neither, the paragraph direction is the view's resolved layout direction. 1896 */ 1897 public static final int TEXT_DIRECTION_ANY_RTL = 2; 1898 1899 /** 1900 * Text direction is forced to LTR. 1901 */ 1902 public static final int TEXT_DIRECTION_LTR = 3; 1903 1904 /** 1905 * Text direction is forced to RTL. 1906 */ 1907 public static final int TEXT_DIRECTION_RTL = 4; 1908 1909 /** 1910 * Text direction is coming from the system Locale. 1911 */ 1912 public static final int TEXT_DIRECTION_LOCALE = 5; 1913 1914 /** 1915 * Default text direction is inherited 1916 */ 1917 public static int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT; 1918 1919 /** 1920 * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED) 1921 * @hide 1922 */ 1923 static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6; 1924 1925 /** 1926 * Mask for use with private flags indicating bits used for text direction. 1927 * @hide 1928 */ 1929 static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007 1930 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 1931 1932 /** 1933 * Array of text direction flags for mapping attribute "textDirection" to correct 1934 * flag value. 1935 * @hide 1936 */ 1937 private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = { 1938 TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1939 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1940 TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1941 TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1942 TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1943 TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT 1944 }; 1945 1946 /** 1947 * Indicates whether the view text direction has been resolved. 1948 * @hide 1949 */ 1950 static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008 1951 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 1952 1953 /** 1954 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1955 * @hide 1956 */ 1957 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10; 1958 1959 /** 1960 * Mask for use with private flags indicating bits used for resolved text direction. 1961 * @hide 1962 */ 1963 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 1964 << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 1965 1966 /** 1967 * Indicates whether the view text direction has been resolved to the "first strong" heuristic. 1968 * @hide 1969 */ 1970 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT = 1971 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 1972 1973 /* 1974 * Default text alignment. The text alignment of this View is inherited from its parent. 1975 * Use with {@link #setTextAlignment(int)} 1976 */ 1977 public static final int TEXT_ALIGNMENT_INHERIT = 0; 1978 1979 /** 1980 * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL, 1981 * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction. 1982 * 1983 * Use with {@link #setTextAlignment(int)} 1984 */ 1985 public static final int TEXT_ALIGNMENT_GRAVITY = 1; 1986 1987 /** 1988 * Align to the start of the paragraph, e.g. ALIGN_NORMAL. 1989 * 1990 * Use with {@link #setTextAlignment(int)} 1991 */ 1992 public static final int TEXT_ALIGNMENT_TEXT_START = 2; 1993 1994 /** 1995 * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE. 1996 * 1997 * Use with {@link #setTextAlignment(int)} 1998 */ 1999 public static final int TEXT_ALIGNMENT_TEXT_END = 3; 2000 2001 /** 2002 * Center the paragraph, e.g. ALIGN_CENTER. 2003 * 2004 * Use with {@link #setTextAlignment(int)} 2005 */ 2006 public static final int TEXT_ALIGNMENT_CENTER = 4; 2007 2008 /** 2009 * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved 2010 * layoutDirection is LTR, and ALIGN_RIGHT otherwise. 2011 * 2012 * Use with {@link #setTextAlignment(int)} 2013 */ 2014 public static final int TEXT_ALIGNMENT_VIEW_START = 5; 2015 2016 /** 2017 * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved 2018 * layoutDirection is LTR, and ALIGN_LEFT otherwise. 2019 * 2020 * Use with {@link #setTextAlignment(int)} 2021 */ 2022 public static final int TEXT_ALIGNMENT_VIEW_END = 6; 2023 2024 /** 2025 * Default text alignment is inherited 2026 */ 2027 public static int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2028 2029 /** 2030 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2031 * @hide 2032 */ 2033 static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13; 2034 2035 /** 2036 * Mask for use with private flags indicating bits used for text alignment. 2037 * @hide 2038 */ 2039 static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2040 2041 /** 2042 * Array of text direction flags for mapping attribute "textAlignment" to correct 2043 * flag value. 2044 * @hide 2045 */ 2046 private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = { 2047 TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2048 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2049 TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2050 TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2051 TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2052 TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2053 TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 2054 }; 2055 2056 /** 2057 * Indicates whether the view text alignment has been resolved. 2058 * @hide 2059 */ 2060 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2061 2062 /** 2063 * Bit shift to get the resolved text alignment. 2064 * @hide 2065 */ 2066 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17; 2067 2068 /** 2069 * Mask for use with private flags indicating bits used for text alignment. 2070 * @hide 2071 */ 2072 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 2073 << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2074 2075 /** 2076 * Indicates whether if the view text alignment has been resolved to gravity 2077 */ 2078 private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT = 2079 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2080 2081 // Accessiblity constants for mPrivateFlags2 2082 2083 /** 2084 * Shift for the bits in {@link #mPrivateFlags2} related to the 2085 * "importantForAccessibility" attribute. 2086 */ 2087 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20; 2088 2089 /** 2090 * Automatically determine whether a view is important for accessibility. 2091 */ 2092 public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000; 2093 2094 /** 2095 * The view is important for accessibility. 2096 */ 2097 public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001; 2098 2099 /** 2100 * The view is not important for accessibility. 2101 */ 2102 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002; 2103 2104 /** 2105 * The default whether the view is important for accessibility. 2106 */ 2107 static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO; 2108 2109 /** 2110 * Mask for obtainig the bits which specify how to determine 2111 * whether a view is important for accessibility. 2112 */ 2113 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO 2114 | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO) 2115 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2116 2117 /** 2118 * Flag indicating whether a view has accessibility focus. 2119 */ 2120 static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x00000040 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2121 2122 /** 2123 * Flag indicating whether a view state for accessibility has changed. 2124 */ 2125 static final int PFLAG2_ACCESSIBILITY_STATE_CHANGED = 0x00000080 2126 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2127 2128 /** 2129 * Flag indicating whether a view failed the quickReject() check in draw(). This condition 2130 * is used to check whether later changes to the view's transform should invalidate the 2131 * view to force the quickReject test to run again. 2132 */ 2133 static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000; 2134 2135 /** 2136 * Flag indicating that start/end padding has been resolved into left/right padding 2137 * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()} 2138 * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved 2139 * during measurement. In some special cases this is required such as when an adapter-based 2140 * view measures prospective children without attaching them to a window. 2141 */ 2142 static final int PFLAG2_PADDING_RESOLVED = 0x20000000; 2143 2144 // There are a couple of flags left in mPrivateFlags2 2145 2146 /* End of masks for mPrivateFlags2 */ 2147 2148 /* Masks for mPrivateFlags3 */ 2149 2150 /** 2151 * Flag indicating that view has a transform animation set on it. This is used to track whether 2152 * an animation is cleared between successive frames, in order to tell the associated 2153 * DisplayList to clear its animation matrix. 2154 */ 2155 static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1; 2156 2157 /** 2158 * Flag indicating that view has an alpha animation set on it. This is used to track whether an 2159 * animation is cleared between successive frames, in order to tell the associated 2160 * DisplayList to restore its alpha value. 2161 */ 2162 static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2; 2163 2164 2165 /* End of masks for mPrivateFlags3 */ 2166 2167 static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED; 2168 2169 /** 2170 * Always allow a user to over-scroll this view, provided it is a 2171 * view that can scroll. 2172 * 2173 * @see #getOverScrollMode() 2174 * @see #setOverScrollMode(int) 2175 */ 2176 public static final int OVER_SCROLL_ALWAYS = 0; 2177 2178 /** 2179 * Allow a user to over-scroll this view only if the content is large 2180 * enough to meaningfully scroll, provided it is a view that can scroll. 2181 * 2182 * @see #getOverScrollMode() 2183 * @see #setOverScrollMode(int) 2184 */ 2185 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 2186 2187 /** 2188 * Never allow a user to over-scroll this view. 2189 * 2190 * @see #getOverScrollMode() 2191 * @see #setOverScrollMode(int) 2192 */ 2193 public static final int OVER_SCROLL_NEVER = 2; 2194 2195 /** 2196 * Special constant for {@link #setSystemUiVisibility(int)}: View has 2197 * requested the system UI (status bar) to be visible (the default). 2198 * 2199 * @see #setSystemUiVisibility(int) 2200 */ 2201 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 2202 2203 /** 2204 * Flag for {@link #setSystemUiVisibility(int)}: View has requested the 2205 * system UI to enter an unobtrusive "low profile" mode. 2206 * 2207 * <p>This is for use in games, book readers, video players, or any other 2208 * "immersive" application where the usual system chrome is deemed too distracting. 2209 * 2210 * <p>In low profile mode, the status bar and/or navigation icons may dim. 2211 * 2212 * @see #setSystemUiVisibility(int) 2213 */ 2214 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 2215 2216 /** 2217 * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the 2218 * system navigation be temporarily hidden. 2219 * 2220 * <p>This is an even less obtrusive state than that called for by 2221 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 2222 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 2223 * those to disappear. This is useful (in conjunction with the 2224 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 2225 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 2226 * window flags) for displaying content using every last pixel on the display. 2227 * 2228 * <p>There is a limitation: because navigation controls are so important, the least user 2229 * interaction will cause them to reappear immediately. When this happens, both 2230 * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically, 2231 * so that both elements reappear at the same time. 2232 * 2233 * @see #setSystemUiVisibility(int) 2234 */ 2235 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 2236 2237 /** 2238 * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go 2239 * into the normal fullscreen mode so that its content can take over the screen 2240 * while still allowing the user to interact with the application. 2241 * 2242 * <p>This has the same visual effect as 2243 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN 2244 * WindowManager.LayoutParams.FLAG_FULLSCREEN}, 2245 * meaning that non-critical screen decorations (such as the status bar) will be 2246 * hidden while the user is in the View's window, focusing the experience on 2247 * that content. Unlike the window flag, if you are using ActionBar in 2248 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2249 * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also 2250 * hide the action bar. 2251 * 2252 * <p>This approach to going fullscreen is best used over the window flag when 2253 * it is a transient state -- that is, the application does this at certain 2254 * points in its user interaction where it wants to allow the user to focus 2255 * on content, but not as a continuous state. For situations where the application 2256 * would like to simply stay full screen the entire time (such as a game that 2257 * wants to take over the screen), the 2258 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag} 2259 * is usually a better approach. The state set here will be removed by the system 2260 * in various situations (such as the user moving to another application) like 2261 * the other system UI states. 2262 * 2263 * <p>When using this flag, the application should provide some easy facility 2264 * for the user to go out of it. A common example would be in an e-book 2265 * reader, where tapping on the screen brings back whatever screen and UI 2266 * decorations that had been hidden while the user was immersed in reading 2267 * the book. 2268 * 2269 * @see #setSystemUiVisibility(int) 2270 */ 2271 public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004; 2272 2273 /** 2274 * Flag for {@link #setSystemUiVisibility(int)}: When using other layout 2275 * flags, we would like a stable view of the content insets given to 2276 * {@link #fitSystemWindows(Rect)}. This means that the insets seen there 2277 * will always represent the worst case that the application can expect 2278 * as a continuous state. In the stock Android UI this is the space for 2279 * the system bar, nav bar, and status bar, but not more transient elements 2280 * such as an input method. 2281 * 2282 * The stable layout your UI sees is based on the system UI modes you can 2283 * switch to. That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 2284 * then you will get a stable layout for changes of the 2285 * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify 2286 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and 2287 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition 2288 * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} 2289 * with a stable layout. (Note that you should avoid using 2290 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.) 2291 * 2292 * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN} 2293 * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}), 2294 * then a hidden status bar will be considered a "stable" state for purposes 2295 * here. This allows your UI to continually hide the status bar, while still 2296 * using the system UI flags to hide the action bar while still retaining 2297 * a stable layout. Note that changing the window fullscreen flag will never 2298 * provide a stable layout for a clean transition. 2299 * 2300 * <p>If you are using ActionBar in 2301 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2302 * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the 2303 * insets it adds to those given to the application. 2304 */ 2305 public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100; 2306 2307 /** 2308 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2309 * to be layed out as if it has requested 2310 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't. This 2311 * allows it to avoid artifacts when switching in and out of that mode, at 2312 * the expense that some of its user interface may be covered by screen 2313 * decorations when they are shown. You can perform layout of your inner 2314 * UI elements to account for the navagation system UI through the 2315 * {@link #fitSystemWindows(Rect)} method. 2316 */ 2317 public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200; 2318 2319 /** 2320 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2321 * to be layed out as if it has requested 2322 * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't. This 2323 * allows it to avoid artifacts when switching in and out of that mode, at 2324 * the expense that some of its user interface may be covered by screen 2325 * decorations when they are shown. You can perform layout of your inner 2326 * UI elements to account for non-fullscreen system UI through the 2327 * {@link #fitSystemWindows(Rect)} method. 2328 */ 2329 public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400; 2330 2331 /** 2332 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 2333 */ 2334 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 2335 2336 /** 2337 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 2338 */ 2339 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 2340 2341 /** 2342 * @hide 2343 * 2344 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2345 * out of the public fields to keep the undefined bits out of the developer's way. 2346 * 2347 * Flag to make the status bar not expandable. Unless you also 2348 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 2349 */ 2350 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 2351 2352 /** 2353 * @hide 2354 * 2355 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2356 * out of the public fields to keep the undefined bits out of the developer's way. 2357 * 2358 * Flag to hide notification icons and scrolling ticker text. 2359 */ 2360 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 2361 2362 /** 2363 * @hide 2364 * 2365 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2366 * out of the public fields to keep the undefined bits out of the developer's way. 2367 * 2368 * Flag to disable incoming notification alerts. This will not block 2369 * icons, but it will block sound, vibrating and other visual or aural notifications. 2370 */ 2371 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 2372 2373 /** 2374 * @hide 2375 * 2376 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2377 * out of the public fields to keep the undefined bits out of the developer's way. 2378 * 2379 * Flag to hide only the scrolling ticker. Note that 2380 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 2381 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 2382 */ 2383 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 2384 2385 /** 2386 * @hide 2387 * 2388 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2389 * out of the public fields to keep the undefined bits out of the developer's way. 2390 * 2391 * Flag to hide the center system info area. 2392 */ 2393 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 2394 2395 /** 2396 * @hide 2397 * 2398 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2399 * out of the public fields to keep the undefined bits out of the developer's way. 2400 * 2401 * Flag to hide only the home button. Don't use this 2402 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2403 */ 2404 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 2405 2406 /** 2407 * @hide 2408 * 2409 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2410 * out of the public fields to keep the undefined bits out of the developer's way. 2411 * 2412 * Flag to hide only the back button. Don't use this 2413 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2414 */ 2415 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 2416 2417 /** 2418 * @hide 2419 * 2420 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2421 * out of the public fields to keep the undefined bits out of the developer's way. 2422 * 2423 * Flag to hide only the clock. You might use this if your activity has 2424 * its own clock making the status bar's clock redundant. 2425 */ 2426 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 2427 2428 /** 2429 * @hide 2430 * 2431 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2432 * out of the public fields to keep the undefined bits out of the developer's way. 2433 * 2434 * Flag to hide only the recent apps button. Don't use this 2435 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2436 */ 2437 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 2438 2439 /** 2440 * @hide 2441 */ 2442 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF; 2443 2444 /** 2445 * These are the system UI flags that can be cleared by events outside 2446 * of an application. Currently this is just the ability to tap on the 2447 * screen while hiding the navigation bar to have it return. 2448 * @hide 2449 */ 2450 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 2451 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 2452 | SYSTEM_UI_FLAG_FULLSCREEN; 2453 2454 /** 2455 * Flags that can impact the layout in relation to system UI. 2456 */ 2457 public static final int SYSTEM_UI_LAYOUT_FLAGS = 2458 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 2459 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 2460 2461 /** 2462 * Find views that render the specified text. 2463 * 2464 * @see #findViewsWithText(ArrayList, CharSequence, int) 2465 */ 2466 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 2467 2468 /** 2469 * Find find views that contain the specified content description. 2470 * 2471 * @see #findViewsWithText(ArrayList, CharSequence, int) 2472 */ 2473 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 2474 2475 /** 2476 * Find views that contain {@link AccessibilityNodeProvider}. Such 2477 * a View is a root of virtual view hierarchy and may contain the searched 2478 * text. If this flag is set Views with providers are automatically 2479 * added and it is a responsibility of the client to call the APIs of 2480 * the provider to determine whether the virtual tree rooted at this View 2481 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 2482 * represeting the virtual views with this text. 2483 * 2484 * @see #findViewsWithText(ArrayList, CharSequence, int) 2485 * 2486 * @hide 2487 */ 2488 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 2489 2490 /** 2491 * The undefined cursor position. 2492 */ 2493 private static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1; 2494 2495 /** 2496 * Indicates that the screen has changed state and is now off. 2497 * 2498 * @see #onScreenStateChanged(int) 2499 */ 2500 public static final int SCREEN_STATE_OFF = 0x0; 2501 2502 /** 2503 * Indicates that the screen has changed state and is now on. 2504 * 2505 * @see #onScreenStateChanged(int) 2506 */ 2507 public static final int SCREEN_STATE_ON = 0x1; 2508 2509 /** 2510 * Controls the over-scroll mode for this view. 2511 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 2512 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 2513 * and {@link #OVER_SCROLL_NEVER}. 2514 */ 2515 private int mOverScrollMode; 2516 2517 /** 2518 * The parent this view is attached to. 2519 * {@hide} 2520 * 2521 * @see #getParent() 2522 */ 2523 protected ViewParent mParent; 2524 2525 /** 2526 * {@hide} 2527 */ 2528 AttachInfo mAttachInfo; 2529 2530 /** 2531 * {@hide} 2532 */ 2533 @ViewDebug.ExportedProperty(flagMapping = { 2534 @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT, 2535 name = "FORCE_LAYOUT"), 2536 @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED, 2537 name = "LAYOUT_REQUIRED"), 2538 @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID, 2539 name = "DRAWING_CACHE_INVALID", outputIf = false), 2540 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true), 2541 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false), 2542 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 2543 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY") 2544 }) 2545 int mPrivateFlags; 2546 int mPrivateFlags2; 2547 int mPrivateFlags3; 2548 2549 /** 2550 * This view's request for the visibility of the status bar. 2551 * @hide 2552 */ 2553 @ViewDebug.ExportedProperty(flagMapping = { 2554 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 2555 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 2556 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 2557 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2558 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2559 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 2560 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 2561 equals = SYSTEM_UI_FLAG_VISIBLE, 2562 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 2563 }) 2564 int mSystemUiVisibility; 2565 2566 /** 2567 * Reference count for transient state. 2568 * @see #setHasTransientState(boolean) 2569 */ 2570 int mTransientStateCount = 0; 2571 2572 /** 2573 * Count of how many windows this view has been attached to. 2574 */ 2575 int mWindowAttachCount; 2576 2577 /** 2578 * The layout parameters associated with this view and used by the parent 2579 * {@link android.view.ViewGroup} to determine how this view should be 2580 * laid out. 2581 * {@hide} 2582 */ 2583 protected ViewGroup.LayoutParams mLayoutParams; 2584 2585 /** 2586 * The view flags hold various views states. 2587 * {@hide} 2588 */ 2589 @ViewDebug.ExportedProperty 2590 int mViewFlags; 2591 2592 static class TransformationInfo { 2593 /** 2594 * The transform matrix for the View. This transform is calculated internally 2595 * based on the rotation, scaleX, and scaleY properties. The identity matrix 2596 * is used by default. Do *not* use this variable directly; instead call 2597 * getMatrix(), which will automatically recalculate the matrix if necessary 2598 * to get the correct matrix based on the latest rotation and scale properties. 2599 */ 2600 private final Matrix mMatrix = new Matrix(); 2601 2602 /** 2603 * The transform matrix for the View. This transform is calculated internally 2604 * based on the rotation, scaleX, and scaleY properties. The identity matrix 2605 * is used by default. Do *not* use this variable directly; instead call 2606 * getInverseMatrix(), which will automatically recalculate the matrix if necessary 2607 * to get the correct matrix based on the latest rotation and scale properties. 2608 */ 2609 private Matrix mInverseMatrix; 2610 2611 /** 2612 * An internal variable that tracks whether we need to recalculate the 2613 * transform matrix, based on whether the rotation or scaleX/Y properties 2614 * have changed since the matrix was last calculated. 2615 */ 2616 boolean mMatrixDirty = false; 2617 2618 /** 2619 * An internal variable that tracks whether we need to recalculate the 2620 * transform matrix, based on whether the rotation or scaleX/Y properties 2621 * have changed since the matrix was last calculated. 2622 */ 2623 private boolean mInverseMatrixDirty = true; 2624 2625 /** 2626 * A variable that tracks whether we need to recalculate the 2627 * transform matrix, based on whether the rotation or scaleX/Y properties 2628 * have changed since the matrix was last calculated. This variable 2629 * is only valid after a call to updateMatrix() or to a function that 2630 * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix(). 2631 */ 2632 private boolean mMatrixIsIdentity = true; 2633 2634 /** 2635 * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set. 2636 */ 2637 private Camera mCamera = null; 2638 2639 /** 2640 * This matrix is used when computing the matrix for 3D rotations. 2641 */ 2642 private Matrix matrix3D = null; 2643 2644 /** 2645 * These prev values are used to recalculate a centered pivot point when necessary. The 2646 * pivot point is only used in matrix operations (when rotation, scale, or translation are 2647 * set), so thes values are only used then as well. 2648 */ 2649 private int mPrevWidth = -1; 2650 private int mPrevHeight = -1; 2651 2652 /** 2653 * The degrees rotation around the vertical axis through the pivot point. 2654 */ 2655 @ViewDebug.ExportedProperty 2656 float mRotationY = 0f; 2657 2658 /** 2659 * The degrees rotation around the horizontal axis through the pivot point. 2660 */ 2661 @ViewDebug.ExportedProperty 2662 float mRotationX = 0f; 2663 2664 /** 2665 * The degrees rotation around the pivot point. 2666 */ 2667 @ViewDebug.ExportedProperty 2668 float mRotation = 0f; 2669 2670 /** 2671 * The amount of translation of the object away from its left property (post-layout). 2672 */ 2673 @ViewDebug.ExportedProperty 2674 float mTranslationX = 0f; 2675 2676 /** 2677 * The amount of translation of the object away from its top property (post-layout). 2678 */ 2679 @ViewDebug.ExportedProperty 2680 float mTranslationY = 0f; 2681 2682 /** 2683 * The amount of scale in the x direction around the pivot point. A 2684 * value of 1 means no scaling is applied. 2685 */ 2686 @ViewDebug.ExportedProperty 2687 float mScaleX = 1f; 2688 2689 /** 2690 * The amount of scale in the y direction around the pivot point. A 2691 * value of 1 means no scaling is applied. 2692 */ 2693 @ViewDebug.ExportedProperty 2694 float mScaleY = 1f; 2695 2696 /** 2697 * The x location of the point around which the view is rotated and scaled. 2698 */ 2699 @ViewDebug.ExportedProperty 2700 float mPivotX = 0f; 2701 2702 /** 2703 * The y location of the point around which the view is rotated and scaled. 2704 */ 2705 @ViewDebug.ExportedProperty 2706 float mPivotY = 0f; 2707 2708 /** 2709 * The opacity of the View. This is a value from 0 to 1, where 0 means 2710 * completely transparent and 1 means completely opaque. 2711 */ 2712 @ViewDebug.ExportedProperty 2713 float mAlpha = 1f; 2714 } 2715 2716 TransformationInfo mTransformationInfo; 2717 2718 private boolean mLastIsOpaque; 2719 2720 /** 2721 * Convenience value to check for float values that are close enough to zero to be considered 2722 * zero. 2723 */ 2724 private static final float NONZERO_EPSILON = .001f; 2725 2726 /** 2727 * The distance in pixels from the left edge of this view's parent 2728 * to the left edge of this view. 2729 * {@hide} 2730 */ 2731 @ViewDebug.ExportedProperty(category = "layout") 2732 protected int mLeft; 2733 /** 2734 * The distance in pixels from the left edge of this view's parent 2735 * to the right edge of this view. 2736 * {@hide} 2737 */ 2738 @ViewDebug.ExportedProperty(category = "layout") 2739 protected int mRight; 2740 /** 2741 * The distance in pixels from the top edge of this view's parent 2742 * to the top edge of this view. 2743 * {@hide} 2744 */ 2745 @ViewDebug.ExportedProperty(category = "layout") 2746 protected int mTop; 2747 /** 2748 * The distance in pixels from the top edge of this view's parent 2749 * to the bottom edge of this view. 2750 * {@hide} 2751 */ 2752 @ViewDebug.ExportedProperty(category = "layout") 2753 protected int mBottom; 2754 2755 /** 2756 * The offset, in pixels, by which the content of this view is scrolled 2757 * horizontally. 2758 * {@hide} 2759 */ 2760 @ViewDebug.ExportedProperty(category = "scrolling") 2761 protected int mScrollX; 2762 /** 2763 * The offset, in pixels, by which the content of this view is scrolled 2764 * vertically. 2765 * {@hide} 2766 */ 2767 @ViewDebug.ExportedProperty(category = "scrolling") 2768 protected int mScrollY; 2769 2770 /** 2771 * The left padding in pixels, that is the distance in pixels between the 2772 * left edge of this view and the left edge of its content. 2773 * {@hide} 2774 */ 2775 @ViewDebug.ExportedProperty(category = "padding") 2776 protected int mPaddingLeft = UNDEFINED_PADDING; 2777 /** 2778 * The right padding in pixels, that is the distance in pixels between the 2779 * right edge of this view and the right edge of its content. 2780 * {@hide} 2781 */ 2782 @ViewDebug.ExportedProperty(category = "padding") 2783 protected int mPaddingRight = UNDEFINED_PADDING; 2784 /** 2785 * The top padding in pixels, that is the distance in pixels between the 2786 * top edge of this view and the top edge of its content. 2787 * {@hide} 2788 */ 2789 @ViewDebug.ExportedProperty(category = "padding") 2790 protected int mPaddingTop; 2791 /** 2792 * The bottom padding in pixels, that is the distance in pixels between the 2793 * bottom edge of this view and the bottom edge of its content. 2794 * {@hide} 2795 */ 2796 @ViewDebug.ExportedProperty(category = "padding") 2797 protected int mPaddingBottom; 2798 2799 /** 2800 * The layout insets in pixels, that is the distance in pixels between the 2801 * visible edges of this view its bounds. 2802 */ 2803 private Insets mLayoutInsets; 2804 2805 /** 2806 * Briefly describes the view and is primarily used for accessibility support. 2807 */ 2808 private CharSequence mContentDescription; 2809 2810 /** 2811 * Specifies the id of a view for which this view serves as a label for 2812 * accessibility purposes. 2813 */ 2814 private int mLabelForId = View.NO_ID; 2815 2816 /** 2817 * Predicate for matching labeled view id with its label for 2818 * accessibility purposes. 2819 */ 2820 private MatchLabelForPredicate mMatchLabelForPredicate; 2821 2822 /** 2823 * Predicate for matching a view by its id. 2824 */ 2825 private MatchIdPredicate mMatchIdPredicate; 2826 2827 /** 2828 * Cache the paddingRight set by the user to append to the scrollbar's size. 2829 * 2830 * @hide 2831 */ 2832 @ViewDebug.ExportedProperty(category = "padding") 2833 protected int mUserPaddingRight; 2834 2835 /** 2836 * Cache the paddingBottom set by the user to append to the scrollbar's size. 2837 * 2838 * @hide 2839 */ 2840 @ViewDebug.ExportedProperty(category = "padding") 2841 protected int mUserPaddingBottom; 2842 2843 /** 2844 * Cache the paddingLeft set by the user to append to the scrollbar's size. 2845 * 2846 * @hide 2847 */ 2848 @ViewDebug.ExportedProperty(category = "padding") 2849 protected int mUserPaddingLeft; 2850 2851 /** 2852 * Cache the paddingStart set by the user to append to the scrollbar's size. 2853 * 2854 */ 2855 @ViewDebug.ExportedProperty(category = "padding") 2856 int mUserPaddingStart; 2857 2858 /** 2859 * Cache the paddingEnd set by the user to append to the scrollbar's size. 2860 * 2861 */ 2862 @ViewDebug.ExportedProperty(category = "padding") 2863 int mUserPaddingEnd; 2864 2865 /** 2866 * Cache initial left padding. 2867 * 2868 * @hide 2869 */ 2870 int mUserPaddingLeftInitial = UNDEFINED_PADDING; 2871 2872 /** 2873 * Cache initial right padding. 2874 * 2875 * @hide 2876 */ 2877 int mUserPaddingRightInitial = UNDEFINED_PADDING; 2878 2879 /** 2880 * Default undefined padding 2881 */ 2882 private static final int UNDEFINED_PADDING = Integer.MIN_VALUE; 2883 2884 /** 2885 * @hide 2886 */ 2887 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 2888 /** 2889 * @hide 2890 */ 2891 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 2892 2893 private Drawable mBackground; 2894 2895 private int mBackgroundResource; 2896 private boolean mBackgroundSizeChanged; 2897 2898 static class ListenerInfo { 2899 /** 2900 * Listener used to dispatch focus change events. 2901 * This field should be made private, so it is hidden from the SDK. 2902 * {@hide} 2903 */ 2904 protected OnFocusChangeListener mOnFocusChangeListener; 2905 2906 /** 2907 * Listeners for layout change events. 2908 */ 2909 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 2910 2911 /** 2912 * Listeners for attach events. 2913 */ 2914 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 2915 2916 /** 2917 * Listener used to dispatch click events. 2918 * This field should be made private, so it is hidden from the SDK. 2919 * {@hide} 2920 */ 2921 public OnClickListener mOnClickListener; 2922 2923 /** 2924 * Listener used to dispatch long click events. 2925 * This field should be made private, so it is hidden from the SDK. 2926 * {@hide} 2927 */ 2928 protected OnLongClickListener mOnLongClickListener; 2929 2930 /** 2931 * Listener used to build the context menu. 2932 * This field should be made private, so it is hidden from the SDK. 2933 * {@hide} 2934 */ 2935 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 2936 2937 private OnKeyListener mOnKeyListener; 2938 2939 private OnTouchListener mOnTouchListener; 2940 2941 private OnHoverListener mOnHoverListener; 2942 2943 private OnGenericMotionListener mOnGenericMotionListener; 2944 2945 private OnDragListener mOnDragListener; 2946 2947 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 2948 } 2949 2950 ListenerInfo mListenerInfo; 2951 2952 /** 2953 * The application environment this view lives in. 2954 * This field should be made private, so it is hidden from the SDK. 2955 * {@hide} 2956 */ 2957 protected Context mContext; 2958 2959 private final Resources mResources; 2960 2961 private ScrollabilityCache mScrollCache; 2962 2963 private int[] mDrawableState = null; 2964 2965 /** 2966 * Set to true when drawing cache is enabled and cannot be created. 2967 * 2968 * @hide 2969 */ 2970 public boolean mCachingFailed; 2971 2972 private Bitmap mDrawingCache; 2973 private Bitmap mUnscaledDrawingCache; 2974 private HardwareLayer mHardwareLayer; 2975 DisplayList mDisplayList; 2976 2977 /** 2978 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 2979 * the user may specify which view to go to next. 2980 */ 2981 private int mNextFocusLeftId = View.NO_ID; 2982 2983 /** 2984 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 2985 * the user may specify which view to go to next. 2986 */ 2987 private int mNextFocusRightId = View.NO_ID; 2988 2989 /** 2990 * When this view has focus and the next focus is {@link #FOCUS_UP}, 2991 * the user may specify which view to go to next. 2992 */ 2993 private int mNextFocusUpId = View.NO_ID; 2994 2995 /** 2996 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 2997 * the user may specify which view to go to next. 2998 */ 2999 private int mNextFocusDownId = View.NO_ID; 3000 3001 /** 3002 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 3003 * the user may specify which view to go to next. 3004 */ 3005 int mNextFocusForwardId = View.NO_ID; 3006 3007 private CheckForLongPress mPendingCheckForLongPress; 3008 private CheckForTap mPendingCheckForTap = null; 3009 private PerformClick mPerformClick; 3010 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 3011 3012 private UnsetPressedState mUnsetPressedState; 3013 3014 /** 3015 * Whether the long press's action has been invoked. The tap's action is invoked on the 3016 * up event while a long press is invoked as soon as the long press duration is reached, so 3017 * a long press could be performed before the tap is checked, in which case the tap's action 3018 * should not be invoked. 3019 */ 3020 private boolean mHasPerformedLongPress; 3021 3022 /** 3023 * The minimum height of the view. We'll try our best to have the height 3024 * of this view to at least this amount. 3025 */ 3026 @ViewDebug.ExportedProperty(category = "measurement") 3027 private int mMinHeight; 3028 3029 /** 3030 * The minimum width of the view. We'll try our best to have the width 3031 * of this view to at least this amount. 3032 */ 3033 @ViewDebug.ExportedProperty(category = "measurement") 3034 private int mMinWidth; 3035 3036 /** 3037 * The delegate to handle touch events that are physically in this view 3038 * but should be handled by another view. 3039 */ 3040 private TouchDelegate mTouchDelegate = null; 3041 3042 /** 3043 * Solid color to use as a background when creating the drawing cache. Enables 3044 * the cache to use 16 bit bitmaps instead of 32 bit. 3045 */ 3046 private int mDrawingCacheBackgroundColor = 0; 3047 3048 /** 3049 * Special tree observer used when mAttachInfo is null. 3050 */ 3051 private ViewTreeObserver mFloatingTreeObserver; 3052 3053 /** 3054 * Cache the touch slop from the context that created the view. 3055 */ 3056 private int mTouchSlop; 3057 3058 /** 3059 * Object that handles automatic animation of view properties. 3060 */ 3061 private ViewPropertyAnimator mAnimator = null; 3062 3063 /** 3064 * Flag indicating that a drag can cross window boundaries. When 3065 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 3066 * with this flag set, all visible applications will be able to participate 3067 * in the drag operation and receive the dragged content. 3068 * 3069 * @hide 3070 */ 3071 public static final int DRAG_FLAG_GLOBAL = 1; 3072 3073 /** 3074 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 3075 */ 3076 private float mVerticalScrollFactor; 3077 3078 /** 3079 * Position of the vertical scroll bar. 3080 */ 3081 private int mVerticalScrollbarPosition; 3082 3083 /** 3084 * Position the scroll bar at the default position as determined by the system. 3085 */ 3086 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 3087 3088 /** 3089 * Position the scroll bar along the left edge. 3090 */ 3091 public static final int SCROLLBAR_POSITION_LEFT = 1; 3092 3093 /** 3094 * Position the scroll bar along the right edge. 3095 */ 3096 public static final int SCROLLBAR_POSITION_RIGHT = 2; 3097 3098 /** 3099 * Indicates that the view does not have a layer. 3100 * 3101 * @see #getLayerType() 3102 * @see #setLayerType(int, android.graphics.Paint) 3103 * @see #LAYER_TYPE_SOFTWARE 3104 * @see #LAYER_TYPE_HARDWARE 3105 */ 3106 public static final int LAYER_TYPE_NONE = 0; 3107 3108 /** 3109 * <p>Indicates that the view has a software layer. A software layer is backed 3110 * by a bitmap and causes the view to be rendered using Android's software 3111 * rendering pipeline, even if hardware acceleration is enabled.</p> 3112 * 3113 * <p>Software layers have various usages:</p> 3114 * <p>When the application is not using hardware acceleration, a software layer 3115 * is useful to apply a specific color filter and/or blending mode and/or 3116 * translucency to a view and all its children.</p> 3117 * <p>When the application is using hardware acceleration, a software layer 3118 * is useful to render drawing primitives not supported by the hardware 3119 * accelerated pipeline. It can also be used to cache a complex view tree 3120 * into a texture and reduce the complexity of drawing operations. For instance, 3121 * when animating a complex view tree with a translation, a software layer can 3122 * be used to render the view tree only once.</p> 3123 * <p>Software layers should be avoided when the affected view tree updates 3124 * often. Every update will require to re-render the software layer, which can 3125 * potentially be slow (particularly when hardware acceleration is turned on 3126 * since the layer will have to be uploaded into a hardware texture after every 3127 * update.)</p> 3128 * 3129 * @see #getLayerType() 3130 * @see #setLayerType(int, android.graphics.Paint) 3131 * @see #LAYER_TYPE_NONE 3132 * @see #LAYER_TYPE_HARDWARE 3133 */ 3134 public static final int LAYER_TYPE_SOFTWARE = 1; 3135 3136 /** 3137 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 3138 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 3139 * OpenGL hardware) and causes the view to be rendered using Android's hardware 3140 * rendering pipeline, but only if hardware acceleration is turned on for the 3141 * view hierarchy. When hardware acceleration is turned off, hardware layers 3142 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 3143 * 3144 * <p>A hardware layer is useful to apply a specific color filter and/or 3145 * blending mode and/or translucency to a view and all its children.</p> 3146 * <p>A hardware layer can be used to cache a complex view tree into a 3147 * texture and reduce the complexity of drawing operations. For instance, 3148 * when animating a complex view tree with a translation, a hardware layer can 3149 * be used to render the view tree only once.</p> 3150 * <p>A hardware layer can also be used to increase the rendering quality when 3151 * rotation transformations are applied on a view. It can also be used to 3152 * prevent potential clipping issues when applying 3D transforms on a view.</p> 3153 * 3154 * @see #getLayerType() 3155 * @see #setLayerType(int, android.graphics.Paint) 3156 * @see #LAYER_TYPE_NONE 3157 * @see #LAYER_TYPE_SOFTWARE 3158 */ 3159 public static final int LAYER_TYPE_HARDWARE = 2; 3160 3161 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 3162 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 3163 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 3164 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 3165 }) 3166 int mLayerType = LAYER_TYPE_NONE; 3167 Paint mLayerPaint; 3168 Rect mLocalDirtyRect; 3169 3170 /** 3171 * Set to true when the view is sending hover accessibility events because it 3172 * is the innermost hovered view. 3173 */ 3174 private boolean mSendingHoverAccessibilityEvents; 3175 3176 /** 3177 * Delegate for injecting accessibility functionality. 3178 */ 3179 AccessibilityDelegate mAccessibilityDelegate; 3180 3181 /** 3182 * Consistency verifier for debugging purposes. 3183 * @hide 3184 */ 3185 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 3186 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 3187 new InputEventConsistencyVerifier(this, 0) : null; 3188 3189 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); 3190 3191 /** 3192 * Simple constructor to use when creating a view from code. 3193 * 3194 * @param context The Context the view is running in, through which it can 3195 * access the current theme, resources, etc. 3196 */ 3197 public View(Context context) { 3198 mContext = context; 3199 mResources = context != null ? context.getResources() : null; 3200 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 3201 // Set layout and text direction defaults 3202 mPrivateFlags2 = (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) | 3203 (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) | 3204 (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) | 3205 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT); 3206 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 3207 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 3208 mUserPaddingStart = UNDEFINED_PADDING; 3209 mUserPaddingEnd = UNDEFINED_PADDING; 3210 } 3211 3212 /** 3213 * Constructor that is called when inflating a view from XML. This is called 3214 * when a view is being constructed from an XML file, supplying attributes 3215 * that were specified in the XML file. This version uses a default style of 3216 * 0, so the only attribute values applied are those in the Context's Theme 3217 * and the given AttributeSet. 3218 * 3219 * <p> 3220 * The method onFinishInflate() will be called after all children have been 3221 * added. 3222 * 3223 * @param context The Context the view is running in, through which it can 3224 * access the current theme, resources, etc. 3225 * @param attrs The attributes of the XML tag that is inflating the view. 3226 * @see #View(Context, AttributeSet, int) 3227 */ 3228 public View(Context context, AttributeSet attrs) { 3229 this(context, attrs, 0); 3230 } 3231 3232 /** 3233 * Perform inflation from XML and apply a class-specific base style. This 3234 * constructor of View allows subclasses to use their own base style when 3235 * they are inflating. For example, a Button class's constructor would call 3236 * this version of the super class constructor and supply 3237 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows 3238 * the theme's button style to modify all of the base view attributes (in 3239 * particular its background) as well as the Button class's attributes. 3240 * 3241 * @param context The Context the view is running in, through which it can 3242 * access the current theme, resources, etc. 3243 * @param attrs The attributes of the XML tag that is inflating the view. 3244 * @param defStyle The default style to apply to this view. If 0, no style 3245 * will be applied (beyond what is included in the theme). This may 3246 * either be an attribute resource, whose value will be retrieved 3247 * from the current theme, or an explicit style resource. 3248 * @see #View(Context, AttributeSet) 3249 */ 3250 public View(Context context, AttributeSet attrs, int defStyle) { 3251 this(context); 3252 3253 TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View, 3254 defStyle, 0); 3255 3256 Drawable background = null; 3257 3258 int leftPadding = -1; 3259 int topPadding = -1; 3260 int rightPadding = -1; 3261 int bottomPadding = -1; 3262 int startPadding = UNDEFINED_PADDING; 3263 int endPadding = UNDEFINED_PADDING; 3264 3265 int padding = -1; 3266 3267 int viewFlagValues = 0; 3268 int viewFlagMasks = 0; 3269 3270 boolean setScrollContainer = false; 3271 3272 int x = 0; 3273 int y = 0; 3274 3275 float tx = 0; 3276 float ty = 0; 3277 float rotation = 0; 3278 float rotationX = 0; 3279 float rotationY = 0; 3280 float sx = 1f; 3281 float sy = 1f; 3282 boolean transformSet = false; 3283 3284 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 3285 int overScrollMode = mOverScrollMode; 3286 boolean initializeScrollbars = false; 3287 3288 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3289 3290 final int N = a.getIndexCount(); 3291 for (int i = 0; i < N; i++) { 3292 int attr = a.getIndex(i); 3293 switch (attr) { 3294 case com.android.internal.R.styleable.View_background: 3295 background = a.getDrawable(attr); 3296 break; 3297 case com.android.internal.R.styleable.View_padding: 3298 padding = a.getDimensionPixelSize(attr, -1); 3299 mUserPaddingLeftInitial = padding; 3300 mUserPaddingRightInitial = padding; 3301 break; 3302 case com.android.internal.R.styleable.View_paddingLeft: 3303 leftPadding = a.getDimensionPixelSize(attr, -1); 3304 mUserPaddingLeftInitial = leftPadding; 3305 break; 3306 case com.android.internal.R.styleable.View_paddingTop: 3307 topPadding = a.getDimensionPixelSize(attr, -1); 3308 break; 3309 case com.android.internal.R.styleable.View_paddingRight: 3310 rightPadding = a.getDimensionPixelSize(attr, -1); 3311 mUserPaddingRightInitial = rightPadding; 3312 break; 3313 case com.android.internal.R.styleable.View_paddingBottom: 3314 bottomPadding = a.getDimensionPixelSize(attr, -1); 3315 break; 3316 case com.android.internal.R.styleable.View_paddingStart: 3317 startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3318 break; 3319 case com.android.internal.R.styleable.View_paddingEnd: 3320 endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3321 break; 3322 case com.android.internal.R.styleable.View_scrollX: 3323 x = a.getDimensionPixelOffset(attr, 0); 3324 break; 3325 case com.android.internal.R.styleable.View_scrollY: 3326 y = a.getDimensionPixelOffset(attr, 0); 3327 break; 3328 case com.android.internal.R.styleable.View_alpha: 3329 setAlpha(a.getFloat(attr, 1f)); 3330 break; 3331 case com.android.internal.R.styleable.View_transformPivotX: 3332 setPivotX(a.getDimensionPixelOffset(attr, 0)); 3333 break; 3334 case com.android.internal.R.styleable.View_transformPivotY: 3335 setPivotY(a.getDimensionPixelOffset(attr, 0)); 3336 break; 3337 case com.android.internal.R.styleable.View_translationX: 3338 tx = a.getDimensionPixelOffset(attr, 0); 3339 transformSet = true; 3340 break; 3341 case com.android.internal.R.styleable.View_translationY: 3342 ty = a.getDimensionPixelOffset(attr, 0); 3343 transformSet = true; 3344 break; 3345 case com.android.internal.R.styleable.View_rotation: 3346 rotation = a.getFloat(attr, 0); 3347 transformSet = true; 3348 break; 3349 case com.android.internal.R.styleable.View_rotationX: 3350 rotationX = a.getFloat(attr, 0); 3351 transformSet = true; 3352 break; 3353 case com.android.internal.R.styleable.View_rotationY: 3354 rotationY = a.getFloat(attr, 0); 3355 transformSet = true; 3356 break; 3357 case com.android.internal.R.styleable.View_scaleX: 3358 sx = a.getFloat(attr, 1f); 3359 transformSet = true; 3360 break; 3361 case com.android.internal.R.styleable.View_scaleY: 3362 sy = a.getFloat(attr, 1f); 3363 transformSet = true; 3364 break; 3365 case com.android.internal.R.styleable.View_id: 3366 mID = a.getResourceId(attr, NO_ID); 3367 break; 3368 case com.android.internal.R.styleable.View_tag: 3369 mTag = a.getText(attr); 3370 break; 3371 case com.android.internal.R.styleable.View_fitsSystemWindows: 3372 if (a.getBoolean(attr, false)) { 3373 viewFlagValues |= FITS_SYSTEM_WINDOWS; 3374 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 3375 } 3376 break; 3377 case com.android.internal.R.styleable.View_focusable: 3378 if (a.getBoolean(attr, false)) { 3379 viewFlagValues |= FOCUSABLE; 3380 viewFlagMasks |= FOCUSABLE_MASK; 3381 } 3382 break; 3383 case com.android.internal.R.styleable.View_focusableInTouchMode: 3384 if (a.getBoolean(attr, false)) { 3385 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 3386 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 3387 } 3388 break; 3389 case com.android.internal.R.styleable.View_clickable: 3390 if (a.getBoolean(attr, false)) { 3391 viewFlagValues |= CLICKABLE; 3392 viewFlagMasks |= CLICKABLE; 3393 } 3394 break; 3395 case com.android.internal.R.styleable.View_longClickable: 3396 if (a.getBoolean(attr, false)) { 3397 viewFlagValues |= LONG_CLICKABLE; 3398 viewFlagMasks |= LONG_CLICKABLE; 3399 } 3400 break; 3401 case com.android.internal.R.styleable.View_saveEnabled: 3402 if (!a.getBoolean(attr, true)) { 3403 viewFlagValues |= SAVE_DISABLED; 3404 viewFlagMasks |= SAVE_DISABLED_MASK; 3405 } 3406 break; 3407 case com.android.internal.R.styleable.View_duplicateParentState: 3408 if (a.getBoolean(attr, false)) { 3409 viewFlagValues |= DUPLICATE_PARENT_STATE; 3410 viewFlagMasks |= DUPLICATE_PARENT_STATE; 3411 } 3412 break; 3413 case com.android.internal.R.styleable.View_visibility: 3414 final int visibility = a.getInt(attr, 0); 3415 if (visibility != 0) { 3416 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 3417 viewFlagMasks |= VISIBILITY_MASK; 3418 } 3419 break; 3420 case com.android.internal.R.styleable.View_layoutDirection: 3421 // Clear any layout direction flags (included resolved bits) already set 3422 mPrivateFlags2 &= ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK); 3423 // Set the layout direction flags depending on the value of the attribute 3424 final int layoutDirection = a.getInt(attr, -1); 3425 final int value = (layoutDirection != -1) ? 3426 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 3427 mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT); 3428 break; 3429 case com.android.internal.R.styleable.View_drawingCacheQuality: 3430 final int cacheQuality = a.getInt(attr, 0); 3431 if (cacheQuality != 0) { 3432 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 3433 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 3434 } 3435 break; 3436 case com.android.internal.R.styleable.View_contentDescription: 3437 setContentDescription(a.getString(attr)); 3438 break; 3439 case com.android.internal.R.styleable.View_labelFor: 3440 setLabelFor(a.getResourceId(attr, NO_ID)); 3441 break; 3442 case com.android.internal.R.styleable.View_soundEffectsEnabled: 3443 if (!a.getBoolean(attr, true)) { 3444 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 3445 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 3446 } 3447 break; 3448 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 3449 if (!a.getBoolean(attr, true)) { 3450 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 3451 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 3452 } 3453 break; 3454 case R.styleable.View_scrollbars: 3455 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 3456 if (scrollbars != SCROLLBARS_NONE) { 3457 viewFlagValues |= scrollbars; 3458 viewFlagMasks |= SCROLLBARS_MASK; 3459 initializeScrollbars = true; 3460 } 3461 break; 3462 //noinspection deprecation 3463 case R.styleable.View_fadingEdge: 3464 if (targetSdkVersion >= ICE_CREAM_SANDWICH) { 3465 // Ignore the attribute starting with ICS 3466 break; 3467 } 3468 // With builds < ICS, fall through and apply fading edges 3469 case R.styleable.View_requiresFadingEdge: 3470 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 3471 if (fadingEdge != FADING_EDGE_NONE) { 3472 viewFlagValues |= fadingEdge; 3473 viewFlagMasks |= FADING_EDGE_MASK; 3474 initializeFadingEdge(a); 3475 } 3476 break; 3477 case R.styleable.View_scrollbarStyle: 3478 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 3479 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3480 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 3481 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 3482 } 3483 break; 3484 case R.styleable.View_isScrollContainer: 3485 setScrollContainer = true; 3486 if (a.getBoolean(attr, false)) { 3487 setScrollContainer(true); 3488 } 3489 break; 3490 case com.android.internal.R.styleable.View_keepScreenOn: 3491 if (a.getBoolean(attr, false)) { 3492 viewFlagValues |= KEEP_SCREEN_ON; 3493 viewFlagMasks |= KEEP_SCREEN_ON; 3494 } 3495 break; 3496 case R.styleable.View_filterTouchesWhenObscured: 3497 if (a.getBoolean(attr, false)) { 3498 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 3499 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 3500 } 3501 break; 3502 case R.styleable.View_nextFocusLeft: 3503 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 3504 break; 3505 case R.styleable.View_nextFocusRight: 3506 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 3507 break; 3508 case R.styleable.View_nextFocusUp: 3509 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 3510 break; 3511 case R.styleable.View_nextFocusDown: 3512 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 3513 break; 3514 case R.styleable.View_nextFocusForward: 3515 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 3516 break; 3517 case R.styleable.View_minWidth: 3518 mMinWidth = a.getDimensionPixelSize(attr, 0); 3519 break; 3520 case R.styleable.View_minHeight: 3521 mMinHeight = a.getDimensionPixelSize(attr, 0); 3522 break; 3523 case R.styleable.View_onClick: 3524 if (context.isRestricted()) { 3525 throw new IllegalStateException("The android:onClick attribute cannot " 3526 + "be used within a restricted context"); 3527 } 3528 3529 final String handlerName = a.getString(attr); 3530 if (handlerName != null) { 3531 setOnClickListener(new OnClickListener() { 3532 private Method mHandler; 3533 3534 public void onClick(View v) { 3535 if (mHandler == null) { 3536 try { 3537 mHandler = getContext().getClass().getMethod(handlerName, 3538 View.class); 3539 } catch (NoSuchMethodException e) { 3540 int id = getId(); 3541 String idText = id == NO_ID ? "" : " with id '" 3542 + getContext().getResources().getResourceEntryName( 3543 id) + "'"; 3544 throw new IllegalStateException("Could not find a method " + 3545 handlerName + "(View) in the activity " 3546 + getContext().getClass() + " for onClick handler" 3547 + " on view " + View.this.getClass() + idText, e); 3548 } 3549 } 3550 3551 try { 3552 mHandler.invoke(getContext(), View.this); 3553 } catch (IllegalAccessException e) { 3554 throw new IllegalStateException("Could not execute non " 3555 + "public method of the activity", e); 3556 } catch (InvocationTargetException e) { 3557 throw new IllegalStateException("Could not execute " 3558 + "method of the activity", e); 3559 } 3560 } 3561 }); 3562 } 3563 break; 3564 case R.styleable.View_overScrollMode: 3565 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 3566 break; 3567 case R.styleable.View_verticalScrollbarPosition: 3568 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 3569 break; 3570 case R.styleable.View_layerType: 3571 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 3572 break; 3573 case R.styleable.View_textDirection: 3574 // Clear any text direction flag already set 3575 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 3576 // Set the text direction flags depending on the value of the attribute 3577 final int textDirection = a.getInt(attr, -1); 3578 if (textDirection != -1) { 3579 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection]; 3580 } 3581 break; 3582 case R.styleable.View_textAlignment: 3583 // Clear any text alignment flag already set 3584 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 3585 // Set the text alignment flag depending on the value of the attribute 3586 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); 3587 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment]; 3588 break; 3589 case R.styleable.View_importantForAccessibility: 3590 setImportantForAccessibility(a.getInt(attr, 3591 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); 3592 break; 3593 } 3594 } 3595 3596 setOverScrollMode(overScrollMode); 3597 3598 // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet 3599 // the resolved layout direction). Those cached values will be used later during padding 3600 // resolution. 3601 mUserPaddingStart = startPadding; 3602 mUserPaddingEnd = endPadding; 3603 3604 if (background != null) { 3605 setBackground(background); 3606 } 3607 3608 if (padding >= 0) { 3609 leftPadding = padding; 3610 topPadding = padding; 3611 rightPadding = padding; 3612 bottomPadding = padding; 3613 mUserPaddingLeftInitial = padding; 3614 mUserPaddingRightInitial = padding; 3615 } 3616 3617 // If the user specified the padding (either with android:padding or 3618 // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise 3619 // use the default padding or the padding from the background drawable 3620 // (stored at this point in mPadding*) 3621 mUserPaddingLeftInitial = leftPadding >= 0 ? leftPadding : mPaddingLeft; 3622 mUserPaddingRightInitial = rightPadding >= 0 ? rightPadding : mPaddingRight; 3623 internalSetPadding( 3624 mUserPaddingLeftInitial != UNDEFINED_PADDING ? mUserPaddingLeftInitial : 0, 3625 topPadding >= 0 ? topPadding : mPaddingTop, 3626 mUserPaddingRightInitial != UNDEFINED_PADDING ? mUserPaddingRightInitial : 0, 3627 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 3628 3629 if (viewFlagMasks != 0) { 3630 setFlags(viewFlagValues, viewFlagMasks); 3631 } 3632 3633 if (initializeScrollbars) { 3634 initializeScrollbars(a); 3635 } 3636 3637 a.recycle(); 3638 3639 // Needs to be called after mViewFlags is set 3640 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3641 recomputePadding(); 3642 } 3643 3644 if (x != 0 || y != 0) { 3645 scrollTo(x, y); 3646 } 3647 3648 if (transformSet) { 3649 setTranslationX(tx); 3650 setTranslationY(ty); 3651 setRotation(rotation); 3652 setRotationX(rotationX); 3653 setRotationY(rotationY); 3654 setScaleX(sx); 3655 setScaleY(sy); 3656 } 3657 3658 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 3659 setScrollContainer(true); 3660 } 3661 3662 computeOpaqueFlags(); 3663 } 3664 3665 /** 3666 * Non-public constructor for use in testing 3667 */ 3668 View() { 3669 mResources = null; 3670 } 3671 3672 public String toString() { 3673 StringBuilder out = new StringBuilder(128); 3674 out.append(getClass().getName()); 3675 out.append('{'); 3676 out.append(Integer.toHexString(System.identityHashCode(this))); 3677 out.append(' '); 3678 switch (mViewFlags&VISIBILITY_MASK) { 3679 case VISIBLE: out.append('V'); break; 3680 case INVISIBLE: out.append('I'); break; 3681 case GONE: out.append('G'); break; 3682 default: out.append('.'); break; 3683 } 3684 out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.'); 3685 out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.'); 3686 out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D'); 3687 out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.'); 3688 out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.'); 3689 out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.'); 3690 out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.'); 3691 out.append(' '); 3692 out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.'); 3693 out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.'); 3694 out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.'); 3695 if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) { 3696 out.append('p'); 3697 } else { 3698 out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.'); 3699 } 3700 out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.'); 3701 out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.'); 3702 out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.'); 3703 out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.'); 3704 out.append(' '); 3705 out.append(mLeft); 3706 out.append(','); 3707 out.append(mTop); 3708 out.append('-'); 3709 out.append(mRight); 3710 out.append(','); 3711 out.append(mBottom); 3712 final int id = getId(); 3713 if (id != NO_ID) { 3714 out.append(" #"); 3715 out.append(Integer.toHexString(id)); 3716 final Resources r = mResources; 3717 if (id != 0 && r != null) { 3718 try { 3719 String pkgname; 3720 switch (id&0xff000000) { 3721 case 0x7f000000: 3722 pkgname="app"; 3723 break; 3724 case 0x01000000: 3725 pkgname="android"; 3726 break; 3727 default: 3728 pkgname = r.getResourcePackageName(id); 3729 break; 3730 } 3731 String typename = r.getResourceTypeName(id); 3732 String entryname = r.getResourceEntryName(id); 3733 out.append(" "); 3734 out.append(pkgname); 3735 out.append(":"); 3736 out.append(typename); 3737 out.append("/"); 3738 out.append(entryname); 3739 } catch (Resources.NotFoundException e) { 3740 } 3741 } 3742 } 3743 out.append("}"); 3744 return out.toString(); 3745 } 3746 3747 /** 3748 * <p> 3749 * Initializes the fading edges from a given set of styled attributes. This 3750 * method should be called by subclasses that need fading edges and when an 3751 * instance of these subclasses is created programmatically rather than 3752 * being inflated from XML. This method is automatically called when the XML 3753 * is inflated. 3754 * </p> 3755 * 3756 * @param a the styled attributes set to initialize the fading edges from 3757 */ 3758 protected void initializeFadingEdge(TypedArray a) { 3759 initScrollCache(); 3760 3761 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 3762 R.styleable.View_fadingEdgeLength, 3763 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 3764 } 3765 3766 /** 3767 * Returns the size of the vertical faded edges used to indicate that more 3768 * content in this view is visible. 3769 * 3770 * @return The size in pixels of the vertical faded edge or 0 if vertical 3771 * faded edges are not enabled for this view. 3772 * @attr ref android.R.styleable#View_fadingEdgeLength 3773 */ 3774 public int getVerticalFadingEdgeLength() { 3775 if (isVerticalFadingEdgeEnabled()) { 3776 ScrollabilityCache cache = mScrollCache; 3777 if (cache != null) { 3778 return cache.fadingEdgeLength; 3779 } 3780 } 3781 return 0; 3782 } 3783 3784 /** 3785 * Set the size of the faded edge used to indicate that more content in this 3786 * view is available. Will not change whether the fading edge is enabled; use 3787 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 3788 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 3789 * for the vertical or horizontal fading edges. 3790 * 3791 * @param length The size in pixels of the faded edge used to indicate that more 3792 * content in this view is visible. 3793 */ 3794 public void setFadingEdgeLength(int length) { 3795 initScrollCache(); 3796 mScrollCache.fadingEdgeLength = length; 3797 } 3798 3799 /** 3800 * Returns the size of the horizontal faded edges used to indicate that more 3801 * content in this view is visible. 3802 * 3803 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 3804 * faded edges are not enabled for this view. 3805 * @attr ref android.R.styleable#View_fadingEdgeLength 3806 */ 3807 public int getHorizontalFadingEdgeLength() { 3808 if (isHorizontalFadingEdgeEnabled()) { 3809 ScrollabilityCache cache = mScrollCache; 3810 if (cache != null) { 3811 return cache.fadingEdgeLength; 3812 } 3813 } 3814 return 0; 3815 } 3816 3817 /** 3818 * Returns the width of the vertical scrollbar. 3819 * 3820 * @return The width in pixels of the vertical scrollbar or 0 if there 3821 * is no vertical scrollbar. 3822 */ 3823 public int getVerticalScrollbarWidth() { 3824 ScrollabilityCache cache = mScrollCache; 3825 if (cache != null) { 3826 ScrollBarDrawable scrollBar = cache.scrollBar; 3827 if (scrollBar != null) { 3828 int size = scrollBar.getSize(true); 3829 if (size <= 0) { 3830 size = cache.scrollBarSize; 3831 } 3832 return size; 3833 } 3834 return 0; 3835 } 3836 return 0; 3837 } 3838 3839 /** 3840 * Returns the height of the horizontal scrollbar. 3841 * 3842 * @return The height in pixels of the horizontal scrollbar or 0 if 3843 * there is no horizontal scrollbar. 3844 */ 3845 protected int getHorizontalScrollbarHeight() { 3846 ScrollabilityCache cache = mScrollCache; 3847 if (cache != null) { 3848 ScrollBarDrawable scrollBar = cache.scrollBar; 3849 if (scrollBar != null) { 3850 int size = scrollBar.getSize(false); 3851 if (size <= 0) { 3852 size = cache.scrollBarSize; 3853 } 3854 return size; 3855 } 3856 return 0; 3857 } 3858 return 0; 3859 } 3860 3861 /** 3862 * <p> 3863 * Initializes the scrollbars from a given set of styled attributes. This 3864 * method should be called by subclasses that need scrollbars and when an 3865 * instance of these subclasses is created programmatically rather than 3866 * being inflated from XML. This method is automatically called when the XML 3867 * is inflated. 3868 * </p> 3869 * 3870 * @param a the styled attributes set to initialize the scrollbars from 3871 */ 3872 protected void initializeScrollbars(TypedArray a) { 3873 initScrollCache(); 3874 3875 final ScrollabilityCache scrollabilityCache = mScrollCache; 3876 3877 if (scrollabilityCache.scrollBar == null) { 3878 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 3879 } 3880 3881 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 3882 3883 if (!fadeScrollbars) { 3884 scrollabilityCache.state = ScrollabilityCache.ON; 3885 } 3886 scrollabilityCache.fadeScrollBars = fadeScrollbars; 3887 3888 3889 scrollabilityCache.scrollBarFadeDuration = a.getInt( 3890 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 3891 .getScrollBarFadeDuration()); 3892 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 3893 R.styleable.View_scrollbarDefaultDelayBeforeFade, 3894 ViewConfiguration.getScrollDefaultDelay()); 3895 3896 3897 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 3898 com.android.internal.R.styleable.View_scrollbarSize, 3899 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 3900 3901 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 3902 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 3903 3904 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 3905 if (thumb != null) { 3906 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 3907 } 3908 3909 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 3910 false); 3911 if (alwaysDraw) { 3912 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 3913 } 3914 3915 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 3916 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 3917 3918 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 3919 if (thumb != null) { 3920 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 3921 } 3922 3923 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 3924 false); 3925 if (alwaysDraw) { 3926 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 3927 } 3928 3929 // Apply layout direction to the new Drawables if needed 3930 final int layoutDirection = getLayoutDirection(); 3931 if (track != null) { 3932 track.setLayoutDirection(layoutDirection); 3933 } 3934 if (thumb != null) { 3935 thumb.setLayoutDirection(layoutDirection); 3936 } 3937 3938 // Re-apply user/background padding so that scrollbar(s) get added 3939 resolvePadding(); 3940 } 3941 3942 /** 3943 * <p> 3944 * Initalizes the scrollability cache if necessary. 3945 * </p> 3946 */ 3947 private void initScrollCache() { 3948 if (mScrollCache == null) { 3949 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 3950 } 3951 } 3952 3953 private ScrollabilityCache getScrollCache() { 3954 initScrollCache(); 3955 return mScrollCache; 3956 } 3957 3958 /** 3959 * Set the position of the vertical scroll bar. Should be one of 3960 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 3961 * {@link #SCROLLBAR_POSITION_RIGHT}. 3962 * 3963 * @param position Where the vertical scroll bar should be positioned. 3964 */ 3965 public void setVerticalScrollbarPosition(int position) { 3966 if (mVerticalScrollbarPosition != position) { 3967 mVerticalScrollbarPosition = position; 3968 computeOpaqueFlags(); 3969 resolvePadding(); 3970 } 3971 } 3972 3973 /** 3974 * @return The position where the vertical scroll bar will show, if applicable. 3975 * @see #setVerticalScrollbarPosition(int) 3976 */ 3977 public int getVerticalScrollbarPosition() { 3978 return mVerticalScrollbarPosition; 3979 } 3980 3981 ListenerInfo getListenerInfo() { 3982 if (mListenerInfo != null) { 3983 return mListenerInfo; 3984 } 3985 mListenerInfo = new ListenerInfo(); 3986 return mListenerInfo; 3987 } 3988 3989 /** 3990 * Register a callback to be invoked when focus of this view changed. 3991 * 3992 * @param l The callback that will run. 3993 */ 3994 public void setOnFocusChangeListener(OnFocusChangeListener l) { 3995 getListenerInfo().mOnFocusChangeListener = l; 3996 } 3997 3998 /** 3999 * Add a listener that will be called when the bounds of the view change due to 4000 * layout processing. 4001 * 4002 * @param listener The listener that will be called when layout bounds change. 4003 */ 4004 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 4005 ListenerInfo li = getListenerInfo(); 4006 if (li.mOnLayoutChangeListeners == null) { 4007 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 4008 } 4009 if (!li.mOnLayoutChangeListeners.contains(listener)) { 4010 li.mOnLayoutChangeListeners.add(listener); 4011 } 4012 } 4013 4014 /** 4015 * Remove a listener for layout changes. 4016 * 4017 * @param listener The listener for layout bounds change. 4018 */ 4019 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 4020 ListenerInfo li = mListenerInfo; 4021 if (li == null || li.mOnLayoutChangeListeners == null) { 4022 return; 4023 } 4024 li.mOnLayoutChangeListeners.remove(listener); 4025 } 4026 4027 /** 4028 * Add a listener for attach state changes. 4029 * 4030 * This listener will be called whenever this view is attached or detached 4031 * from a window. Remove the listener using 4032 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 4033 * 4034 * @param listener Listener to attach 4035 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 4036 */ 4037 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4038 ListenerInfo li = getListenerInfo(); 4039 if (li.mOnAttachStateChangeListeners == null) { 4040 li.mOnAttachStateChangeListeners 4041 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 4042 } 4043 li.mOnAttachStateChangeListeners.add(listener); 4044 } 4045 4046 /** 4047 * Remove a listener for attach state changes. The listener will receive no further 4048 * notification of window attach/detach events. 4049 * 4050 * @param listener Listener to remove 4051 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 4052 */ 4053 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4054 ListenerInfo li = mListenerInfo; 4055 if (li == null || li.mOnAttachStateChangeListeners == null) { 4056 return; 4057 } 4058 li.mOnAttachStateChangeListeners.remove(listener); 4059 } 4060 4061 /** 4062 * Returns the focus-change callback registered for this view. 4063 * 4064 * @return The callback, or null if one is not registered. 4065 */ 4066 public OnFocusChangeListener getOnFocusChangeListener() { 4067 ListenerInfo li = mListenerInfo; 4068 return li != null ? li.mOnFocusChangeListener : null; 4069 } 4070 4071 /** 4072 * Register a callback to be invoked when this view is clicked. If this view is not 4073 * clickable, it becomes clickable. 4074 * 4075 * @param l The callback that will run 4076 * 4077 * @see #setClickable(boolean) 4078 */ 4079 public void setOnClickListener(OnClickListener l) { 4080 if (!isClickable()) { 4081 setClickable(true); 4082 } 4083 getListenerInfo().mOnClickListener = l; 4084 } 4085 4086 /** 4087 * Return whether this view has an attached OnClickListener. Returns 4088 * true if there is a listener, false if there is none. 4089 */ 4090 public boolean hasOnClickListeners() { 4091 ListenerInfo li = mListenerInfo; 4092 return (li != null && li.mOnClickListener != null); 4093 } 4094 4095 /** 4096 * Register a callback to be invoked when this view is clicked and held. If this view is not 4097 * long clickable, it becomes long clickable. 4098 * 4099 * @param l The callback that will run 4100 * 4101 * @see #setLongClickable(boolean) 4102 */ 4103 public void setOnLongClickListener(OnLongClickListener l) { 4104 if (!isLongClickable()) { 4105 setLongClickable(true); 4106 } 4107 getListenerInfo().mOnLongClickListener = l; 4108 } 4109 4110 /** 4111 * Register a callback to be invoked when the context menu for this view is 4112 * being built. If this view is not long clickable, it becomes long clickable. 4113 * 4114 * @param l The callback that will run 4115 * 4116 */ 4117 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 4118 if (!isLongClickable()) { 4119 setLongClickable(true); 4120 } 4121 getListenerInfo().mOnCreateContextMenuListener = l; 4122 } 4123 4124 /** 4125 * Call this view's OnClickListener, if it is defined. Performs all normal 4126 * actions associated with clicking: reporting accessibility event, playing 4127 * a sound, etc. 4128 * 4129 * @return True there was an assigned OnClickListener that was called, false 4130 * otherwise is returned. 4131 */ 4132 public boolean performClick() { 4133 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 4134 4135 ListenerInfo li = mListenerInfo; 4136 if (li != null && li.mOnClickListener != null) { 4137 playSoundEffect(SoundEffectConstants.CLICK); 4138 li.mOnClickListener.onClick(this); 4139 return true; 4140 } 4141 4142 return false; 4143 } 4144 4145 /** 4146 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 4147 * this only calls the listener, and does not do any associated clicking 4148 * actions like reporting an accessibility event. 4149 * 4150 * @return True there was an assigned OnClickListener that was called, false 4151 * otherwise is returned. 4152 */ 4153 public boolean callOnClick() { 4154 ListenerInfo li = mListenerInfo; 4155 if (li != null && li.mOnClickListener != null) { 4156 li.mOnClickListener.onClick(this); 4157 return true; 4158 } 4159 return false; 4160 } 4161 4162 /** 4163 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 4164 * OnLongClickListener did not consume the event. 4165 * 4166 * @return True if one of the above receivers consumed the event, false otherwise. 4167 */ 4168 public boolean performLongClick() { 4169 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 4170 4171 boolean handled = false; 4172 ListenerInfo li = mListenerInfo; 4173 if (li != null && li.mOnLongClickListener != null) { 4174 handled = li.mOnLongClickListener.onLongClick(View.this); 4175 } 4176 if (!handled) { 4177 handled = showContextMenu(); 4178 } 4179 if (handled) { 4180 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 4181 } 4182 return handled; 4183 } 4184 4185 /** 4186 * Performs button-related actions during a touch down event. 4187 * 4188 * @param event The event. 4189 * @return True if the down was consumed. 4190 * 4191 * @hide 4192 */ 4193 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 4194 if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 4195 if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) { 4196 return true; 4197 } 4198 } 4199 return false; 4200 } 4201 4202 /** 4203 * Bring up the context menu for this view. 4204 * 4205 * @return Whether a context menu was displayed. 4206 */ 4207 public boolean showContextMenu() { 4208 return getParent().showContextMenuForChild(this); 4209 } 4210 4211 /** 4212 * Bring up the context menu for this view, referring to the item under the specified point. 4213 * 4214 * @param x The referenced x coordinate. 4215 * @param y The referenced y coordinate. 4216 * @param metaState The keyboard modifiers that were pressed. 4217 * @return Whether a context menu was displayed. 4218 * 4219 * @hide 4220 */ 4221 public boolean showContextMenu(float x, float y, int metaState) { 4222 return showContextMenu(); 4223 } 4224 4225 /** 4226 * Start an action mode. 4227 * 4228 * @param callback Callback that will control the lifecycle of the action mode 4229 * @return The new action mode if it is started, null otherwise 4230 * 4231 * @see ActionMode 4232 */ 4233 public ActionMode startActionMode(ActionMode.Callback callback) { 4234 ViewParent parent = getParent(); 4235 if (parent == null) return null; 4236 return parent.startActionModeForChild(this, callback); 4237 } 4238 4239 /** 4240 * Register a callback to be invoked when a hardware key is pressed in this view. 4241 * Key presses in software input methods will generally not trigger the methods of 4242 * this listener. 4243 * @param l the key listener to attach to this view 4244 */ 4245 public void setOnKeyListener(OnKeyListener l) { 4246 getListenerInfo().mOnKeyListener = l; 4247 } 4248 4249 /** 4250 * Register a callback to be invoked when a touch event is sent to this view. 4251 * @param l the touch listener to attach to this view 4252 */ 4253 public void setOnTouchListener(OnTouchListener l) { 4254 getListenerInfo().mOnTouchListener = l; 4255 } 4256 4257 /** 4258 * Register a callback to be invoked when a generic motion event is sent to this view. 4259 * @param l the generic motion listener to attach to this view 4260 */ 4261 public void setOnGenericMotionListener(OnGenericMotionListener l) { 4262 getListenerInfo().mOnGenericMotionListener = l; 4263 } 4264 4265 /** 4266 * Register a callback to be invoked when a hover event is sent to this view. 4267 * @param l the hover listener to attach to this view 4268 */ 4269 public void setOnHoverListener(OnHoverListener l) { 4270 getListenerInfo().mOnHoverListener = l; 4271 } 4272 4273 /** 4274 * Register a drag event listener callback object for this View. The parameter is 4275 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 4276 * View, the system calls the 4277 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 4278 * @param l An implementation of {@link android.view.View.OnDragListener}. 4279 */ 4280 public void setOnDragListener(OnDragListener l) { 4281 getListenerInfo().mOnDragListener = l; 4282 } 4283 4284 /** 4285 * Give this view focus. This will cause 4286 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 4287 * 4288 * Note: this does not check whether this {@link View} should get focus, it just 4289 * gives it focus no matter what. It should only be called internally by framework 4290 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 4291 * 4292 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 4293 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 4294 * focus moved when requestFocus() is called. It may not always 4295 * apply, in which case use the default View.FOCUS_DOWN. 4296 * @param previouslyFocusedRect The rectangle of the view that had focus 4297 * prior in this View's coordinate system. 4298 */ 4299 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) { 4300 if (DBG) { 4301 System.out.println(this + " requestFocus()"); 4302 } 4303 4304 if ((mPrivateFlags & PFLAG_FOCUSED) == 0) { 4305 mPrivateFlags |= PFLAG_FOCUSED; 4306 4307 if (mParent != null) { 4308 mParent.requestChildFocus(this, this); 4309 } 4310 4311 onFocusChanged(true, direction, previouslyFocusedRect); 4312 refreshDrawableState(); 4313 4314 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 4315 notifyAccessibilityStateChanged(); 4316 } 4317 } 4318 } 4319 4320 /** 4321 * Request that a rectangle of this view be visible on the screen, 4322 * scrolling if necessary just enough. 4323 * 4324 * <p>A View should call this if it maintains some notion of which part 4325 * of its content is interesting. For example, a text editing view 4326 * should call this when its cursor moves. 4327 * 4328 * @param rectangle The rectangle. 4329 * @return Whether any parent scrolled. 4330 */ 4331 public boolean requestRectangleOnScreen(Rect rectangle) { 4332 return requestRectangleOnScreen(rectangle, false); 4333 } 4334 4335 /** 4336 * Request that a rectangle of this view be visible on the screen, 4337 * scrolling if necessary just enough. 4338 * 4339 * <p>A View should call this if it maintains some notion of which part 4340 * of its content is interesting. For example, a text editing view 4341 * should call this when its cursor moves. 4342 * 4343 * <p>When <code>immediate</code> is set to true, scrolling will not be 4344 * animated. 4345 * 4346 * @param rectangle The rectangle. 4347 * @param immediate True to forbid animated scrolling, false otherwise 4348 * @return Whether any parent scrolled. 4349 */ 4350 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 4351 if (mAttachInfo == null) { 4352 return false; 4353 } 4354 4355 View child = this; 4356 4357 RectF position = mAttachInfo.mTmpTransformRect; 4358 position.set(rectangle); 4359 4360 ViewParent parent = mParent; 4361 boolean scrolled = false; 4362 while (parent != null) { 4363 rectangle.set((int) position.left, (int) position.top, 4364 (int) position.right, (int) position.bottom); 4365 4366 scrolled |= parent.requestChildRectangleOnScreen(child, 4367 rectangle, immediate); 4368 4369 if (!child.hasIdentityMatrix()) { 4370 child.getMatrix().mapRect(position); 4371 } 4372 4373 position.offset(child.mLeft, child.mTop); 4374 4375 if (!(parent instanceof View)) { 4376 break; 4377 } 4378 4379 View parentView = (View) parent; 4380 4381 position.offset(-parentView.getScrollX(), -parentView.getScrollY()); 4382 4383 child = parentView; 4384 parent = child.getParent(); 4385 } 4386 4387 return scrolled; 4388 } 4389 4390 /** 4391 * Called when this view wants to give up focus. If focus is cleared 4392 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 4393 * <p> 4394 * <strong>Note:</strong> When a View clears focus the framework is trying 4395 * to give focus to the first focusable View from the top. Hence, if this 4396 * View is the first from the top that can take focus, then all callbacks 4397 * related to clearing focus will be invoked after wich the framework will 4398 * give focus to this view. 4399 * </p> 4400 */ 4401 public void clearFocus() { 4402 if (DBG) { 4403 System.out.println(this + " clearFocus()"); 4404 } 4405 4406 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 4407 mPrivateFlags &= ~PFLAG_FOCUSED; 4408 4409 if (mParent != null) { 4410 mParent.clearChildFocus(this); 4411 } 4412 4413 onFocusChanged(false, 0, null); 4414 4415 refreshDrawableState(); 4416 4417 ensureInputFocusOnFirstFocusable(); 4418 4419 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 4420 notifyAccessibilityStateChanged(); 4421 } 4422 } 4423 } 4424 4425 void ensureInputFocusOnFirstFocusable() { 4426 View root = getRootView(); 4427 if (root != null) { 4428 root.requestFocus(); 4429 } 4430 } 4431 4432 /** 4433 * Called internally by the view system when a new view is getting focus. 4434 * This is what clears the old focus. 4435 */ 4436 void unFocus() { 4437 if (DBG) { 4438 System.out.println(this + " unFocus()"); 4439 } 4440 4441 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 4442 mPrivateFlags &= ~PFLAG_FOCUSED; 4443 4444 onFocusChanged(false, 0, null); 4445 refreshDrawableState(); 4446 4447 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 4448 notifyAccessibilityStateChanged(); 4449 } 4450 } 4451 } 4452 4453 /** 4454 * Returns true if this view has focus iteself, or is the ancestor of the 4455 * view that has focus. 4456 * 4457 * @return True if this view has or contains focus, false otherwise. 4458 */ 4459 @ViewDebug.ExportedProperty(category = "focus") 4460 public boolean hasFocus() { 4461 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 4462 } 4463 4464 /** 4465 * Returns true if this view is focusable or if it contains a reachable View 4466 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 4467 * is a View whose parents do not block descendants focus. 4468 * 4469 * Only {@link #VISIBLE} views are considered focusable. 4470 * 4471 * @return True if the view is focusable or if the view contains a focusable 4472 * View, false otherwise. 4473 * 4474 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 4475 */ 4476 public boolean hasFocusable() { 4477 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 4478 } 4479 4480 /** 4481 * Called by the view system when the focus state of this view changes. 4482 * When the focus change event is caused by directional navigation, direction 4483 * and previouslyFocusedRect provide insight into where the focus is coming from. 4484 * When overriding, be sure to call up through to the super class so that 4485 * the standard focus handling will occur. 4486 * 4487 * @param gainFocus True if the View has focus; false otherwise. 4488 * @param direction The direction focus has moved when requestFocus() 4489 * is called to give this view focus. Values are 4490 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 4491 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 4492 * It may not always apply, in which case use the default. 4493 * @param previouslyFocusedRect The rectangle, in this view's coordinate 4494 * system, of the previously focused view. If applicable, this will be 4495 * passed in as finer grained information about where the focus is coming 4496 * from (in addition to direction). Will be <code>null</code> otherwise. 4497 */ 4498 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) { 4499 if (gainFocus) { 4500 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 4501 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 4502 } 4503 } 4504 4505 InputMethodManager imm = InputMethodManager.peekInstance(); 4506 if (!gainFocus) { 4507 if (isPressed()) { 4508 setPressed(false); 4509 } 4510 if (imm != null && mAttachInfo != null 4511 && mAttachInfo.mHasWindowFocus) { 4512 imm.focusOut(this); 4513 } 4514 onFocusLost(); 4515 } else if (imm != null && mAttachInfo != null 4516 && mAttachInfo.mHasWindowFocus) { 4517 imm.focusIn(this); 4518 } 4519 4520 invalidate(true); 4521 ListenerInfo li = mListenerInfo; 4522 if (li != null && li.mOnFocusChangeListener != null) { 4523 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 4524 } 4525 4526 if (mAttachInfo != null) { 4527 mAttachInfo.mKeyDispatchState.reset(this); 4528 } 4529 } 4530 4531 /** 4532 * Sends an accessibility event of the given type. If accessibility is 4533 * not enabled this method has no effect. The default implementation calls 4534 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 4535 * to populate information about the event source (this View), then calls 4536 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 4537 * populate the text content of the event source including its descendants, 4538 * and last calls 4539 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 4540 * on its parent to resuest sending of the event to interested parties. 4541 * <p> 4542 * If an {@link AccessibilityDelegate} has been specified via calling 4543 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4544 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 4545 * responsible for handling this call. 4546 * </p> 4547 * 4548 * @param eventType The type of the event to send, as defined by several types from 4549 * {@link android.view.accessibility.AccessibilityEvent}, such as 4550 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 4551 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 4552 * 4553 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 4554 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4555 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 4556 * @see AccessibilityDelegate 4557 */ 4558 public void sendAccessibilityEvent(int eventType) { 4559 if (mAccessibilityDelegate != null) { 4560 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 4561 } else { 4562 sendAccessibilityEventInternal(eventType); 4563 } 4564 } 4565 4566 /** 4567 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 4568 * {@link AccessibilityEvent} to make an announcement which is related to some 4569 * sort of a context change for which none of the events representing UI transitions 4570 * is a good fit. For example, announcing a new page in a book. If accessibility 4571 * is not enabled this method does nothing. 4572 * 4573 * @param text The announcement text. 4574 */ 4575 public void announceForAccessibility(CharSequence text) { 4576 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) { 4577 AccessibilityEvent event = AccessibilityEvent.obtain( 4578 AccessibilityEvent.TYPE_ANNOUNCEMENT); 4579 onInitializeAccessibilityEvent(event); 4580 event.getText().add(text); 4581 event.setContentDescription(null); 4582 mParent.requestSendAccessibilityEvent(this, event); 4583 } 4584 } 4585 4586 /** 4587 * @see #sendAccessibilityEvent(int) 4588 * 4589 * Note: Called from the default {@link AccessibilityDelegate}. 4590 */ 4591 void sendAccessibilityEventInternal(int eventType) { 4592 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 4593 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 4594 } 4595 } 4596 4597 /** 4598 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 4599 * takes as an argument an empty {@link AccessibilityEvent} and does not 4600 * perform a check whether accessibility is enabled. 4601 * <p> 4602 * If an {@link AccessibilityDelegate} has been specified via calling 4603 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4604 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 4605 * is responsible for handling this call. 4606 * </p> 4607 * 4608 * @param event The event to send. 4609 * 4610 * @see #sendAccessibilityEvent(int) 4611 */ 4612 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 4613 if (mAccessibilityDelegate != null) { 4614 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 4615 } else { 4616 sendAccessibilityEventUncheckedInternal(event); 4617 } 4618 } 4619 4620 /** 4621 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 4622 * 4623 * Note: Called from the default {@link AccessibilityDelegate}. 4624 */ 4625 void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 4626 if (!isShown()) { 4627 return; 4628 } 4629 onInitializeAccessibilityEvent(event); 4630 // Only a subset of accessibility events populates text content. 4631 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 4632 dispatchPopulateAccessibilityEvent(event); 4633 } 4634 // In the beginning we called #isShown(), so we know that getParent() is not null. 4635 getParent().requestSendAccessibilityEvent(this, event); 4636 } 4637 4638 /** 4639 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 4640 * to its children for adding their text content to the event. Note that the 4641 * event text is populated in a separate dispatch path since we add to the 4642 * event not only the text of the source but also the text of all its descendants. 4643 * A typical implementation will call 4644 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 4645 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 4646 * on each child. Override this method if custom population of the event text 4647 * content is required. 4648 * <p> 4649 * If an {@link AccessibilityDelegate} has been specified via calling 4650 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4651 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 4652 * is responsible for handling this call. 4653 * </p> 4654 * <p> 4655 * <em>Note:</em> Accessibility events of certain types are not dispatched for 4656 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 4657 * </p> 4658 * 4659 * @param event The event. 4660 * 4661 * @return True if the event population was completed. 4662 */ 4663 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 4664 if (mAccessibilityDelegate != null) { 4665 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 4666 } else { 4667 return dispatchPopulateAccessibilityEventInternal(event); 4668 } 4669 } 4670 4671 /** 4672 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4673 * 4674 * Note: Called from the default {@link AccessibilityDelegate}. 4675 */ 4676 boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 4677 onPopulateAccessibilityEvent(event); 4678 return false; 4679 } 4680 4681 /** 4682 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 4683 * giving a chance to this View to populate the accessibility event with its 4684 * text content. While this method is free to modify event 4685 * attributes other than text content, doing so should normally be performed in 4686 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 4687 * <p> 4688 * Example: Adding formatted date string to an accessibility event in addition 4689 * to the text added by the super implementation: 4690 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 4691 * super.onPopulateAccessibilityEvent(event); 4692 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 4693 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 4694 * mCurrentDate.getTimeInMillis(), flags); 4695 * event.getText().add(selectedDateUtterance); 4696 * }</pre> 4697 * <p> 4698 * If an {@link AccessibilityDelegate} has been specified via calling 4699 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4700 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 4701 * is responsible for handling this call. 4702 * </p> 4703 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 4704 * information to the event, in case the default implementation has basic information to add. 4705 * </p> 4706 * 4707 * @param event The accessibility event which to populate. 4708 * 4709 * @see #sendAccessibilityEvent(int) 4710 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4711 */ 4712 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 4713 if (mAccessibilityDelegate != null) { 4714 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 4715 } else { 4716 onPopulateAccessibilityEventInternal(event); 4717 } 4718 } 4719 4720 /** 4721 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 4722 * 4723 * Note: Called from the default {@link AccessibilityDelegate}. 4724 */ 4725 void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 4726 4727 } 4728 4729 /** 4730 * Initializes an {@link AccessibilityEvent} with information about 4731 * this View which is the event source. In other words, the source of 4732 * an accessibility event is the view whose state change triggered firing 4733 * the event. 4734 * <p> 4735 * Example: Setting the password property of an event in addition 4736 * to properties set by the super implementation: 4737 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 4738 * super.onInitializeAccessibilityEvent(event); 4739 * event.setPassword(true); 4740 * }</pre> 4741 * <p> 4742 * If an {@link AccessibilityDelegate} has been specified via calling 4743 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4744 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 4745 * is responsible for handling this call. 4746 * </p> 4747 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 4748 * information to the event, in case the default implementation has basic information to add. 4749 * </p> 4750 * @param event The event to initialize. 4751 * 4752 * @see #sendAccessibilityEvent(int) 4753 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4754 */ 4755 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 4756 if (mAccessibilityDelegate != null) { 4757 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 4758 } else { 4759 onInitializeAccessibilityEventInternal(event); 4760 } 4761 } 4762 4763 /** 4764 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 4765 * 4766 * Note: Called from the default {@link AccessibilityDelegate}. 4767 */ 4768 void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 4769 event.setSource(this); 4770 event.setClassName(View.class.getName()); 4771 event.setPackageName(getContext().getPackageName()); 4772 event.setEnabled(isEnabled()); 4773 event.setContentDescription(mContentDescription); 4774 4775 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) { 4776 ArrayList<View> focusablesTempList = mAttachInfo.mTempArrayList; 4777 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, 4778 FOCUSABLES_ALL); 4779 event.setItemCount(focusablesTempList.size()); 4780 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 4781 focusablesTempList.clear(); 4782 } 4783 } 4784 4785 /** 4786 * Returns an {@link AccessibilityNodeInfo} representing this view from the 4787 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 4788 * This method is responsible for obtaining an accessibility node info from a 4789 * pool of reusable instances and calling 4790 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 4791 * initialize the former. 4792 * <p> 4793 * Note: The client is responsible for recycling the obtained instance by calling 4794 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 4795 * </p> 4796 * 4797 * @return A populated {@link AccessibilityNodeInfo}. 4798 * 4799 * @see AccessibilityNodeInfo 4800 */ 4801 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 4802 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 4803 if (provider != null) { 4804 return provider.createAccessibilityNodeInfo(View.NO_ID); 4805 } else { 4806 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 4807 onInitializeAccessibilityNodeInfo(info); 4808 return info; 4809 } 4810 } 4811 4812 /** 4813 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 4814 * The base implementation sets: 4815 * <ul> 4816 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 4817 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 4818 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 4819 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 4820 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 4821 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 4822 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 4823 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 4824 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 4825 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 4826 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 4827 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 4828 * </ul> 4829 * <p> 4830 * Subclasses should override this method, call the super implementation, 4831 * and set additional attributes. 4832 * </p> 4833 * <p> 4834 * If an {@link AccessibilityDelegate} has been specified via calling 4835 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4836 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 4837 * is responsible for handling this call. 4838 * </p> 4839 * 4840 * @param info The instance to initialize. 4841 */ 4842 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 4843 if (mAccessibilityDelegate != null) { 4844 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 4845 } else { 4846 onInitializeAccessibilityNodeInfoInternal(info); 4847 } 4848 } 4849 4850 /** 4851 * Gets the location of this view in screen coordintates. 4852 * 4853 * @param outRect The output location 4854 */ 4855 private void getBoundsOnScreen(Rect outRect) { 4856 if (mAttachInfo == null) { 4857 return; 4858 } 4859 4860 RectF position = mAttachInfo.mTmpTransformRect; 4861 position.set(0, 0, mRight - mLeft, mBottom - mTop); 4862 4863 if (!hasIdentityMatrix()) { 4864 getMatrix().mapRect(position); 4865 } 4866 4867 position.offset(mLeft, mTop); 4868 4869 ViewParent parent = mParent; 4870 while (parent instanceof View) { 4871 View parentView = (View) parent; 4872 4873 position.offset(-parentView.mScrollX, -parentView.mScrollY); 4874 4875 if (!parentView.hasIdentityMatrix()) { 4876 parentView.getMatrix().mapRect(position); 4877 } 4878 4879 position.offset(parentView.mLeft, parentView.mTop); 4880 4881 parent = parentView.mParent; 4882 } 4883 4884 if (parent instanceof ViewRootImpl) { 4885 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 4886 position.offset(0, -viewRootImpl.mCurScrollY); 4887 } 4888 4889 position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 4890 4891 outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f), 4892 (int) (position.right + 0.5f), (int) (position.bottom + 0.5f)); 4893 } 4894 4895 /** 4896 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 4897 * 4898 * Note: Called from the default {@link AccessibilityDelegate}. 4899 */ 4900 void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 4901 Rect bounds = mAttachInfo.mTmpInvalRect; 4902 4903 getDrawingRect(bounds); 4904 info.setBoundsInParent(bounds); 4905 4906 getBoundsOnScreen(bounds); 4907 info.setBoundsInScreen(bounds); 4908 4909 ViewParent parent = getParentForAccessibility(); 4910 if (parent instanceof View) { 4911 info.setParent((View) parent); 4912 } 4913 4914 if (mID != View.NO_ID) { 4915 View rootView = getRootView(); 4916 if (rootView == null) { 4917 rootView = this; 4918 } 4919 View label = rootView.findLabelForView(this, mID); 4920 if (label != null) { 4921 info.setLabeledBy(label); 4922 } 4923 } 4924 4925 if (mLabelForId != View.NO_ID) { 4926 View rootView = getRootView(); 4927 if (rootView == null) { 4928 rootView = this; 4929 } 4930 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId); 4931 if (labeled != null) { 4932 info.setLabelFor(labeled); 4933 } 4934 } 4935 4936 info.setVisibleToUser(isVisibleToUser()); 4937 4938 info.setPackageName(mContext.getPackageName()); 4939 info.setClassName(View.class.getName()); 4940 info.setContentDescription(getContentDescription()); 4941 4942 info.setEnabled(isEnabled()); 4943 info.setClickable(isClickable()); 4944 info.setFocusable(isFocusable()); 4945 info.setFocused(isFocused()); 4946 info.setAccessibilityFocused(isAccessibilityFocused()); 4947 info.setSelected(isSelected()); 4948 info.setLongClickable(isLongClickable()); 4949 4950 // TODO: These make sense only if we are in an AdapterView but all 4951 // views can be selected. Maybe from accessibility perspective 4952 // we should report as selectable view in an AdapterView. 4953 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 4954 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 4955 4956 if (isFocusable()) { 4957 if (isFocused()) { 4958 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 4959 } else { 4960 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 4961 } 4962 } 4963 4964 if (!isAccessibilityFocused()) { 4965 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 4966 } else { 4967 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 4968 } 4969 4970 if (isClickable() && isEnabled()) { 4971 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 4972 } 4973 4974 if (isLongClickable() && isEnabled()) { 4975 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 4976 } 4977 4978 if (mContentDescription != null && mContentDescription.length() > 0) { 4979 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 4980 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 4981 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 4982 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 4983 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 4984 } 4985 } 4986 4987 private View findLabelForView(View view, int labeledId) { 4988 if (mMatchLabelForPredicate == null) { 4989 mMatchLabelForPredicate = new MatchLabelForPredicate(); 4990 } 4991 mMatchLabelForPredicate.mLabeledId = labeledId; 4992 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 4993 } 4994 4995 /** 4996 * Computes whether this view is visible to the user. Such a view is 4997 * attached, visible, all its predecessors are visible, it is not clipped 4998 * entirely by its predecessors, and has an alpha greater than zero. 4999 * 5000 * @return Whether the view is visible on the screen. 5001 * 5002 * @hide 5003 */ 5004 protected boolean isVisibleToUser() { 5005 return isVisibleToUser(null); 5006 } 5007 5008 /** 5009 * Computes whether the given portion of this view is visible to the user. 5010 * Such a view is attached, visible, all its predecessors are visible, 5011 * has an alpha greater than zero, and the specified portion is not 5012 * clipped entirely by its predecessors. 5013 * 5014 * @param boundInView the portion of the view to test; coordinates should be relative; may be 5015 * <code>null</code>, and the entire view will be tested in this case. 5016 * When <code>true</code> is returned by the function, the actual visible 5017 * region will be stored in this parameter; that is, if boundInView is fully 5018 * contained within the view, no modification will be made, otherwise regions 5019 * outside of the visible area of the view will be clipped. 5020 * 5021 * @return Whether the specified portion of the view is visible on the screen. 5022 * 5023 * @hide 5024 */ 5025 protected boolean isVisibleToUser(Rect boundInView) { 5026 if (mAttachInfo != null) { 5027 Rect visibleRect = mAttachInfo.mTmpInvalRect; 5028 Point offset = mAttachInfo.mPoint; 5029 // The first two checks are made also made by isShown() which 5030 // however traverses the tree up to the parent to catch that. 5031 // Therefore, we do some fail fast check to minimize the up 5032 // tree traversal. 5033 boolean isVisible = mAttachInfo.mWindowVisibility == View.VISIBLE 5034 && getAlpha() > 0 5035 && isShown() 5036 && getGlobalVisibleRect(visibleRect, offset); 5037 if (isVisible && boundInView != null) { 5038 visibleRect.offset(-offset.x, -offset.y); 5039 // isVisible is always true here, use a simple assignment 5040 isVisible = boundInView.intersect(visibleRect); 5041 } 5042 return isVisible; 5043 } 5044 5045 return false; 5046 } 5047 5048 /** 5049 * Returns the delegate for implementing accessibility support via 5050 * composition. For more details see {@link AccessibilityDelegate}. 5051 * 5052 * @return The delegate, or null if none set. 5053 * 5054 * @hide 5055 */ 5056 public AccessibilityDelegate getAccessibilityDelegate() { 5057 return mAccessibilityDelegate; 5058 } 5059 5060 /** 5061 * Sets a delegate for implementing accessibility support via composition as 5062 * opposed to inheritance. The delegate's primary use is for implementing 5063 * backwards compatible widgets. For more details see {@link AccessibilityDelegate}. 5064 * 5065 * @param delegate The delegate instance. 5066 * 5067 * @see AccessibilityDelegate 5068 */ 5069 public void setAccessibilityDelegate(AccessibilityDelegate delegate) { 5070 mAccessibilityDelegate = delegate; 5071 } 5072 5073 /** 5074 * Gets the provider for managing a virtual view hierarchy rooted at this View 5075 * and reported to {@link android.accessibilityservice.AccessibilityService}s 5076 * that explore the window content. 5077 * <p> 5078 * If this method returns an instance, this instance is responsible for managing 5079 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 5080 * View including the one representing the View itself. Similarly the returned 5081 * instance is responsible for performing accessibility actions on any virtual 5082 * view or the root view itself. 5083 * </p> 5084 * <p> 5085 * If an {@link AccessibilityDelegate} has been specified via calling 5086 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5087 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 5088 * is responsible for handling this call. 5089 * </p> 5090 * 5091 * @return The provider. 5092 * 5093 * @see AccessibilityNodeProvider 5094 */ 5095 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 5096 if (mAccessibilityDelegate != null) { 5097 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 5098 } else { 5099 return null; 5100 } 5101 } 5102 5103 /** 5104 * Gets the unique identifier of this view on the screen for accessibility purposes. 5105 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 5106 * 5107 * @return The view accessibility id. 5108 * 5109 * @hide 5110 */ 5111 public int getAccessibilityViewId() { 5112 if (mAccessibilityViewId == NO_ID) { 5113 mAccessibilityViewId = sNextAccessibilityViewId++; 5114 } 5115 return mAccessibilityViewId; 5116 } 5117 5118 /** 5119 * Gets the unique identifier of the window in which this View reseides. 5120 * 5121 * @return The window accessibility id. 5122 * 5123 * @hide 5124 */ 5125 public int getAccessibilityWindowId() { 5126 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID; 5127 } 5128 5129 /** 5130 * Gets the {@link View} description. It briefly describes the view and is 5131 * primarily used for accessibility support. Set this property to enable 5132 * better accessibility support for your application. This is especially 5133 * true for views that do not have textual representation (For example, 5134 * ImageButton). 5135 * 5136 * @return The content description. 5137 * 5138 * @attr ref android.R.styleable#View_contentDescription 5139 */ 5140 @ViewDebug.ExportedProperty(category = "accessibility") 5141 public CharSequence getContentDescription() { 5142 return mContentDescription; 5143 } 5144 5145 /** 5146 * Sets the {@link View} description. It briefly describes the view and is 5147 * primarily used for accessibility support. Set this property to enable 5148 * better accessibility support for your application. This is especially 5149 * true for views that do not have textual representation (For example, 5150 * ImageButton). 5151 * 5152 * @param contentDescription The content description. 5153 * 5154 * @attr ref android.R.styleable#View_contentDescription 5155 */ 5156 @RemotableViewMethod 5157 public void setContentDescription(CharSequence contentDescription) { 5158 mContentDescription = contentDescription; 5159 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 5160 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 5161 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 5162 } 5163 } 5164 5165 /** 5166 * Gets the id of a view for which this view serves as a label for 5167 * accessibility purposes. 5168 * 5169 * @return The labeled view id. 5170 */ 5171 @ViewDebug.ExportedProperty(category = "accessibility") 5172 public int getLabelFor() { 5173 return mLabelForId; 5174 } 5175 5176 /** 5177 * Sets the id of a view for which this view serves as a label for 5178 * accessibility purposes. 5179 * 5180 * @param id The labeled view id. 5181 */ 5182 @RemotableViewMethod 5183 public void setLabelFor(int id) { 5184 mLabelForId = id; 5185 if (mLabelForId != View.NO_ID 5186 && mID == View.NO_ID) { 5187 mID = generateViewId(); 5188 } 5189 } 5190 5191 /** 5192 * Invoked whenever this view loses focus, either by losing window focus or by losing 5193 * focus within its window. This method can be used to clear any state tied to the 5194 * focus. For instance, if a button is held pressed with the trackball and the window 5195 * loses focus, this method can be used to cancel the press. 5196 * 5197 * Subclasses of View overriding this method should always call super.onFocusLost(). 5198 * 5199 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 5200 * @see #onWindowFocusChanged(boolean) 5201 * 5202 * @hide pending API council approval 5203 */ 5204 protected void onFocusLost() { 5205 resetPressedState(); 5206 } 5207 5208 private void resetPressedState() { 5209 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 5210 return; 5211 } 5212 5213 if (isPressed()) { 5214 setPressed(false); 5215 5216 if (!mHasPerformedLongPress) { 5217 removeLongPressCallback(); 5218 } 5219 } 5220 } 5221 5222 /** 5223 * Returns true if this view has focus 5224 * 5225 * @return True if this view has focus, false otherwise. 5226 */ 5227 @ViewDebug.ExportedProperty(category = "focus") 5228 public boolean isFocused() { 5229 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 5230 } 5231 5232 /** 5233 * Find the view in the hierarchy rooted at this view that currently has 5234 * focus. 5235 * 5236 * @return The view that currently has focus, or null if no focused view can 5237 * be found. 5238 */ 5239 public View findFocus() { 5240 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 5241 } 5242 5243 /** 5244 * Indicates whether this view is one of the set of scrollable containers in 5245 * its window. 5246 * 5247 * @return whether this view is one of the set of scrollable containers in 5248 * its window 5249 * 5250 * @attr ref android.R.styleable#View_isScrollContainer 5251 */ 5252 public boolean isScrollContainer() { 5253 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 5254 } 5255 5256 /** 5257 * Change whether this view is one of the set of scrollable containers in 5258 * its window. This will be used to determine whether the window can 5259 * resize or must pan when a soft input area is open -- scrollable 5260 * containers allow the window to use resize mode since the container 5261 * will appropriately shrink. 5262 * 5263 * @attr ref android.R.styleable#View_isScrollContainer 5264 */ 5265 public void setScrollContainer(boolean isScrollContainer) { 5266 if (isScrollContainer) { 5267 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 5268 mAttachInfo.mScrollContainers.add(this); 5269 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 5270 } 5271 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 5272 } else { 5273 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 5274 mAttachInfo.mScrollContainers.remove(this); 5275 } 5276 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 5277 } 5278 } 5279 5280 /** 5281 * Returns the quality of the drawing cache. 5282 * 5283 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5284 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5285 * 5286 * @see #setDrawingCacheQuality(int) 5287 * @see #setDrawingCacheEnabled(boolean) 5288 * @see #isDrawingCacheEnabled() 5289 * 5290 * @attr ref android.R.styleable#View_drawingCacheQuality 5291 */ 5292 public int getDrawingCacheQuality() { 5293 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 5294 } 5295 5296 /** 5297 * Set the drawing cache quality of this view. This value is used only when the 5298 * drawing cache is enabled 5299 * 5300 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5301 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5302 * 5303 * @see #getDrawingCacheQuality() 5304 * @see #setDrawingCacheEnabled(boolean) 5305 * @see #isDrawingCacheEnabled() 5306 * 5307 * @attr ref android.R.styleable#View_drawingCacheQuality 5308 */ 5309 public void setDrawingCacheQuality(int quality) { 5310 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 5311 } 5312 5313 /** 5314 * Returns whether the screen should remain on, corresponding to the current 5315 * value of {@link #KEEP_SCREEN_ON}. 5316 * 5317 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 5318 * 5319 * @see #setKeepScreenOn(boolean) 5320 * 5321 * @attr ref android.R.styleable#View_keepScreenOn 5322 */ 5323 public boolean getKeepScreenOn() { 5324 return (mViewFlags & KEEP_SCREEN_ON) != 0; 5325 } 5326 5327 /** 5328 * Controls whether the screen should remain on, modifying the 5329 * value of {@link #KEEP_SCREEN_ON}. 5330 * 5331 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 5332 * 5333 * @see #getKeepScreenOn() 5334 * 5335 * @attr ref android.R.styleable#View_keepScreenOn 5336 */ 5337 public void setKeepScreenOn(boolean keepScreenOn) { 5338 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 5339 } 5340 5341 /** 5342 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5343 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5344 * 5345 * @attr ref android.R.styleable#View_nextFocusLeft 5346 */ 5347 public int getNextFocusLeftId() { 5348 return mNextFocusLeftId; 5349 } 5350 5351 /** 5352 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5353 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 5354 * decide automatically. 5355 * 5356 * @attr ref android.R.styleable#View_nextFocusLeft 5357 */ 5358 public void setNextFocusLeftId(int nextFocusLeftId) { 5359 mNextFocusLeftId = nextFocusLeftId; 5360 } 5361 5362 /** 5363 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5364 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5365 * 5366 * @attr ref android.R.styleable#View_nextFocusRight 5367 */ 5368 public int getNextFocusRightId() { 5369 return mNextFocusRightId; 5370 } 5371 5372 /** 5373 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5374 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 5375 * decide automatically. 5376 * 5377 * @attr ref android.R.styleable#View_nextFocusRight 5378 */ 5379 public void setNextFocusRightId(int nextFocusRightId) { 5380 mNextFocusRightId = nextFocusRightId; 5381 } 5382 5383 /** 5384 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 5385 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5386 * 5387 * @attr ref android.R.styleable#View_nextFocusUp 5388 */ 5389 public int getNextFocusUpId() { 5390 return mNextFocusUpId; 5391 } 5392 5393 /** 5394 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 5395 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 5396 * decide automatically. 5397 * 5398 * @attr ref android.R.styleable#View_nextFocusUp 5399 */ 5400 public void setNextFocusUpId(int nextFocusUpId) { 5401 mNextFocusUpId = nextFocusUpId; 5402 } 5403 5404 /** 5405 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 5406 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5407 * 5408 * @attr ref android.R.styleable#View_nextFocusDown 5409 */ 5410 public int getNextFocusDownId() { 5411 return mNextFocusDownId; 5412 } 5413 5414 /** 5415 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 5416 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 5417 * decide automatically. 5418 * 5419 * @attr ref android.R.styleable#View_nextFocusDown 5420 */ 5421 public void setNextFocusDownId(int nextFocusDownId) { 5422 mNextFocusDownId = nextFocusDownId; 5423 } 5424 5425 /** 5426 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 5427 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5428 * 5429 * @attr ref android.R.styleable#View_nextFocusForward 5430 */ 5431 public int getNextFocusForwardId() { 5432 return mNextFocusForwardId; 5433 } 5434 5435 /** 5436 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 5437 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 5438 * decide automatically. 5439 * 5440 * @attr ref android.R.styleable#View_nextFocusForward 5441 */ 5442 public void setNextFocusForwardId(int nextFocusForwardId) { 5443 mNextFocusForwardId = nextFocusForwardId; 5444 } 5445 5446 /** 5447 * Returns the visibility of this view and all of its ancestors 5448 * 5449 * @return True if this view and all of its ancestors are {@link #VISIBLE} 5450 */ 5451 public boolean isShown() { 5452 View current = this; 5453 //noinspection ConstantConditions 5454 do { 5455 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 5456 return false; 5457 } 5458 ViewParent parent = current.mParent; 5459 if (parent == null) { 5460 return false; // We are not attached to the view root 5461 } 5462 if (!(parent instanceof View)) { 5463 return true; 5464 } 5465 current = (View) parent; 5466 } while (current != null); 5467 5468 return false; 5469 } 5470 5471 /** 5472 * Called by the view hierarchy when the content insets for a window have 5473 * changed, to allow it to adjust its content to fit within those windows. 5474 * The content insets tell you the space that the status bar, input method, 5475 * and other system windows infringe on the application's window. 5476 * 5477 * <p>You do not normally need to deal with this function, since the default 5478 * window decoration given to applications takes care of applying it to the 5479 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 5480 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 5481 * and your content can be placed under those system elements. You can then 5482 * use this method within your view hierarchy if you have parts of your UI 5483 * which you would like to ensure are not being covered. 5484 * 5485 * <p>The default implementation of this method simply applies the content 5486 * inset's to the view's padding, consuming that content (modifying the 5487 * insets to be 0), and returning true. This behavior is off by default, but can 5488 * be enabled through {@link #setFitsSystemWindows(boolean)}. 5489 * 5490 * <p>This function's traversal down the hierarchy is depth-first. The same content 5491 * insets object is propagated down the hierarchy, so any changes made to it will 5492 * be seen by all following views (including potentially ones above in 5493 * the hierarchy since this is a depth-first traversal). The first view 5494 * that returns true will abort the entire traversal. 5495 * 5496 * <p>The default implementation works well for a situation where it is 5497 * used with a container that covers the entire window, allowing it to 5498 * apply the appropriate insets to its content on all edges. If you need 5499 * a more complicated layout (such as two different views fitting system 5500 * windows, one on the top of the window, and one on the bottom), 5501 * you can override the method and handle the insets however you would like. 5502 * Note that the insets provided by the framework are always relative to the 5503 * far edges of the window, not accounting for the location of the called view 5504 * within that window. (In fact when this method is called you do not yet know 5505 * where the layout will place the view, as it is done before layout happens.) 5506 * 5507 * <p>Note: unlike many View methods, there is no dispatch phase to this 5508 * call. If you are overriding it in a ViewGroup and want to allow the 5509 * call to continue to your children, you must be sure to call the super 5510 * implementation. 5511 * 5512 * <p>Here is a sample layout that makes use of fitting system windows 5513 * to have controls for a video view placed inside of the window decorations 5514 * that it hides and shows. This can be used with code like the second 5515 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 5516 * 5517 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 5518 * 5519 * @param insets Current content insets of the window. Prior to 5520 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 5521 * the insets or else you and Android will be unhappy. 5522 * 5523 * @return Return true if this view applied the insets and it should not 5524 * continue propagating further down the hierarchy, false otherwise. 5525 * @see #getFitsSystemWindows() 5526 * @see #setFitsSystemWindows(boolean) 5527 * @see #setSystemUiVisibility(int) 5528 */ 5529 protected boolean fitSystemWindows(Rect insets) { 5530 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 5531 mUserPaddingStart = UNDEFINED_PADDING; 5532 mUserPaddingEnd = UNDEFINED_PADDING; 5533 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 5534 || mAttachInfo == null 5535 || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) { 5536 internalSetPadding(insets.left, insets.top, insets.right, insets.bottom); 5537 return true; 5538 } else { 5539 internalSetPadding(0, 0, 0, 0); 5540 return false; 5541 } 5542 } 5543 return false; 5544 } 5545 5546 /** 5547 * Sets whether or not this view should account for system screen decorations 5548 * such as the status bar and inset its content; that is, controlling whether 5549 * the default implementation of {@link #fitSystemWindows(Rect)} will be 5550 * executed. See that method for more details. 5551 * 5552 * <p>Note that if you are providing your own implementation of 5553 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 5554 * flag to true -- your implementation will be overriding the default 5555 * implementation that checks this flag. 5556 * 5557 * @param fitSystemWindows If true, then the default implementation of 5558 * {@link #fitSystemWindows(Rect)} will be executed. 5559 * 5560 * @attr ref android.R.styleable#View_fitsSystemWindows 5561 * @see #getFitsSystemWindows() 5562 * @see #fitSystemWindows(Rect) 5563 * @see #setSystemUiVisibility(int) 5564 */ 5565 public void setFitsSystemWindows(boolean fitSystemWindows) { 5566 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 5567 } 5568 5569 /** 5570 * Check for state of {@link #setFitsSystemWindows(boolean). If this method 5571 * returns true, the default implementation of {@link #fitSystemWindows(Rect)} 5572 * will be executed. 5573 * 5574 * @return Returns true if the default implementation of 5575 * {@link #fitSystemWindows(Rect)} will be executed. 5576 * 5577 * @attr ref android.R.styleable#View_fitsSystemWindows 5578 * @see #setFitsSystemWindows() 5579 * @see #fitSystemWindows(Rect) 5580 * @see #setSystemUiVisibility(int) 5581 */ 5582 public boolean getFitsSystemWindows() { 5583 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 5584 } 5585 5586 /** @hide */ 5587 public boolean fitsSystemWindows() { 5588 return getFitsSystemWindows(); 5589 } 5590 5591 /** 5592 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 5593 */ 5594 public void requestFitSystemWindows() { 5595 if (mParent != null) { 5596 mParent.requestFitSystemWindows(); 5597 } 5598 } 5599 5600 /** 5601 * For use by PhoneWindow to make its own system window fitting optional. 5602 * @hide 5603 */ 5604 public void makeOptionalFitsSystemWindows() { 5605 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 5606 } 5607 5608 /** 5609 * Returns the visibility status for this view. 5610 * 5611 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 5612 * @attr ref android.R.styleable#View_visibility 5613 */ 5614 @ViewDebug.ExportedProperty(mapping = { 5615 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 5616 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 5617 @ViewDebug.IntToString(from = GONE, to = "GONE") 5618 }) 5619 public int getVisibility() { 5620 return mViewFlags & VISIBILITY_MASK; 5621 } 5622 5623 /** 5624 * Set the enabled state of this view. 5625 * 5626 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 5627 * @attr ref android.R.styleable#View_visibility 5628 */ 5629 @RemotableViewMethod 5630 public void setVisibility(int visibility) { 5631 setFlags(visibility, VISIBILITY_MASK); 5632 if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false); 5633 } 5634 5635 /** 5636 * Returns the enabled status for this view. The interpretation of the 5637 * enabled state varies by subclass. 5638 * 5639 * @return True if this view is enabled, false otherwise. 5640 */ 5641 @ViewDebug.ExportedProperty 5642 public boolean isEnabled() { 5643 return (mViewFlags & ENABLED_MASK) == ENABLED; 5644 } 5645 5646 /** 5647 * Set the enabled state of this view. The interpretation of the enabled 5648 * state varies by subclass. 5649 * 5650 * @param enabled True if this view is enabled, false otherwise. 5651 */ 5652 @RemotableViewMethod 5653 public void setEnabled(boolean enabled) { 5654 if (enabled == isEnabled()) return; 5655 5656 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 5657 5658 /* 5659 * The View most likely has to change its appearance, so refresh 5660 * the drawable state. 5661 */ 5662 refreshDrawableState(); 5663 5664 // Invalidate too, since the default behavior for views is to be 5665 // be drawn at 50% alpha rather than to change the drawable. 5666 invalidate(true); 5667 } 5668 5669 /** 5670 * Set whether this view can receive the focus. 5671 * 5672 * Setting this to false will also ensure that this view is not focusable 5673 * in touch mode. 5674 * 5675 * @param focusable If true, this view can receive the focus. 5676 * 5677 * @see #setFocusableInTouchMode(boolean) 5678 * @attr ref android.R.styleable#View_focusable 5679 */ 5680 public void setFocusable(boolean focusable) { 5681 if (!focusable) { 5682 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 5683 } 5684 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 5685 } 5686 5687 /** 5688 * Set whether this view can receive focus while in touch mode. 5689 * 5690 * Setting this to true will also ensure that this view is focusable. 5691 * 5692 * @param focusableInTouchMode If true, this view can receive the focus while 5693 * in touch mode. 5694 * 5695 * @see #setFocusable(boolean) 5696 * @attr ref android.R.styleable#View_focusableInTouchMode 5697 */ 5698 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 5699 // Focusable in touch mode should always be set before the focusable flag 5700 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 5701 // which, in touch mode, will not successfully request focus on this view 5702 // because the focusable in touch mode flag is not set 5703 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 5704 if (focusableInTouchMode) { 5705 setFlags(FOCUSABLE, FOCUSABLE_MASK); 5706 } 5707 } 5708 5709 /** 5710 * Set whether this view should have sound effects enabled for events such as 5711 * clicking and touching. 5712 * 5713 * <p>You may wish to disable sound effects for a view if you already play sounds, 5714 * for instance, a dial key that plays dtmf tones. 5715 * 5716 * @param soundEffectsEnabled whether sound effects are enabled for this view. 5717 * @see #isSoundEffectsEnabled() 5718 * @see #playSoundEffect(int) 5719 * @attr ref android.R.styleable#View_soundEffectsEnabled 5720 */ 5721 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 5722 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 5723 } 5724 5725 /** 5726 * @return whether this view should have sound effects enabled for events such as 5727 * clicking and touching. 5728 * 5729 * @see #setSoundEffectsEnabled(boolean) 5730 * @see #playSoundEffect(int) 5731 * @attr ref android.R.styleable#View_soundEffectsEnabled 5732 */ 5733 @ViewDebug.ExportedProperty 5734 public boolean isSoundEffectsEnabled() { 5735 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 5736 } 5737 5738 /** 5739 * Set whether this view should have haptic feedback for events such as 5740 * long presses. 5741 * 5742 * <p>You may wish to disable haptic feedback if your view already controls 5743 * its own haptic feedback. 5744 * 5745 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 5746 * @see #isHapticFeedbackEnabled() 5747 * @see #performHapticFeedback(int) 5748 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 5749 */ 5750 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 5751 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 5752 } 5753 5754 /** 5755 * @return whether this view should have haptic feedback enabled for events 5756 * long presses. 5757 * 5758 * @see #setHapticFeedbackEnabled(boolean) 5759 * @see #performHapticFeedback(int) 5760 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 5761 */ 5762 @ViewDebug.ExportedProperty 5763 public boolean isHapticFeedbackEnabled() { 5764 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 5765 } 5766 5767 /** 5768 * Returns the layout direction for this view. 5769 * 5770 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 5771 * {@link #LAYOUT_DIRECTION_RTL}, 5772 * {@link #LAYOUT_DIRECTION_INHERIT} or 5773 * {@link #LAYOUT_DIRECTION_LOCALE}. 5774 * @attr ref android.R.styleable#View_layoutDirection 5775 */ 5776 @ViewDebug.ExportedProperty(category = "layout", mapping = { 5777 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 5778 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 5779 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 5780 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 5781 }) 5782 private int getRawLayoutDirection() { 5783 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 5784 } 5785 5786 /** 5787 * Set the layout direction for this view. This will propagate a reset of layout direction 5788 * resolution to the view's children and resolve layout direction for this view. 5789 * 5790 * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR}, 5791 * {@link #LAYOUT_DIRECTION_RTL}, 5792 * {@link #LAYOUT_DIRECTION_INHERIT} or 5793 * {@link #LAYOUT_DIRECTION_LOCALE}. 5794 * 5795 * @attr ref android.R.styleable#View_layoutDirection 5796 */ 5797 @RemotableViewMethod 5798 public void setLayoutDirection(int layoutDirection) { 5799 if (getRawLayoutDirection() != layoutDirection) { 5800 // Reset the current layout direction and the resolved one 5801 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 5802 resetRtlProperties(); 5803 // Set the new layout direction (filtered) 5804 mPrivateFlags2 |= 5805 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 5806 resolveRtlProperties(); 5807 // Notify changes 5808 onRtlPropertiesChanged(); 5809 // ... and ask for a layout pass 5810 requestLayout(); 5811 } 5812 } 5813 5814 /** 5815 * Returns the resolved layout direction for this view. 5816 * 5817 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 5818 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 5819 */ 5820 @ViewDebug.ExportedProperty(category = "layout", mapping = { 5821 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 5822 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 5823 }) 5824 public int getLayoutDirection() { 5825 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 5826 if (targetSdkVersion < JELLY_BEAN_MR1) { 5827 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 5828 return LAYOUT_DIRECTION_LTR; 5829 } 5830 // The layout direction will be resolved only if needed 5831 if ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) != PFLAG2_LAYOUT_DIRECTION_RESOLVED) { 5832 resolveLayoutDirection(); 5833 } 5834 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? 5835 LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 5836 } 5837 5838 /** 5839 * Indicates whether or not this view's layout is right-to-left. This is resolved from 5840 * layout attribute and/or the inherited value from the parent 5841 * 5842 * @return true if the layout is right-to-left. 5843 */ 5844 @ViewDebug.ExportedProperty(category = "layout") 5845 public boolean isLayoutRtl() { 5846 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 5847 } 5848 5849 /** 5850 * Indicates whether the view is currently tracking transient state that the 5851 * app should not need to concern itself with saving and restoring, but that 5852 * the framework should take special note to preserve when possible. 5853 * 5854 * <p>A view with transient state cannot be trivially rebound from an external 5855 * data source, such as an adapter binding item views in a list. This may be 5856 * because the view is performing an animation, tracking user selection 5857 * of content, or similar.</p> 5858 * 5859 * @return true if the view has transient state 5860 */ 5861 @ViewDebug.ExportedProperty(category = "layout") 5862 public boolean hasTransientState() { 5863 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 5864 } 5865 5866 /** 5867 * Set whether this view is currently tracking transient state that the 5868 * framework should attempt to preserve when possible. This flag is reference counted, 5869 * so every call to setHasTransientState(true) should be paired with a later call 5870 * to setHasTransientState(false). 5871 * 5872 * <p>A view with transient state cannot be trivially rebound from an external 5873 * data source, such as an adapter binding item views in a list. This may be 5874 * because the view is performing an animation, tracking user selection 5875 * of content, or similar.</p> 5876 * 5877 * @param hasTransientState true if this view has transient state 5878 */ 5879 public void setHasTransientState(boolean hasTransientState) { 5880 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 5881 mTransientStateCount - 1; 5882 if (mTransientStateCount < 0) { 5883 mTransientStateCount = 0; 5884 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 5885 "unmatched pair of setHasTransientState calls"); 5886 } 5887 if ((hasTransientState && mTransientStateCount == 1) || 5888 (!hasTransientState && mTransientStateCount == 0)) { 5889 // update flag if we've just incremented up from 0 or decremented down to 0 5890 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 5891 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 5892 if (mParent != null) { 5893 try { 5894 mParent.childHasTransientStateChanged(this, hasTransientState); 5895 } catch (AbstractMethodError e) { 5896 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 5897 " does not fully implement ViewParent", e); 5898 } 5899 } 5900 } 5901 } 5902 5903 /** 5904 * If this view doesn't do any drawing on its own, set this flag to 5905 * allow further optimizations. By default, this flag is not set on 5906 * View, but could be set on some View subclasses such as ViewGroup. 5907 * 5908 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 5909 * you should clear this flag. 5910 * 5911 * @param willNotDraw whether or not this View draw on its own 5912 */ 5913 public void setWillNotDraw(boolean willNotDraw) { 5914 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 5915 } 5916 5917 /** 5918 * Returns whether or not this View draws on its own. 5919 * 5920 * @return true if this view has nothing to draw, false otherwise 5921 */ 5922 @ViewDebug.ExportedProperty(category = "drawing") 5923 public boolean willNotDraw() { 5924 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 5925 } 5926 5927 /** 5928 * When a View's drawing cache is enabled, drawing is redirected to an 5929 * offscreen bitmap. Some views, like an ImageView, must be able to 5930 * bypass this mechanism if they already draw a single bitmap, to avoid 5931 * unnecessary usage of the memory. 5932 * 5933 * @param willNotCacheDrawing true if this view does not cache its 5934 * drawing, false otherwise 5935 */ 5936 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 5937 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 5938 } 5939 5940 /** 5941 * Returns whether or not this View can cache its drawing or not. 5942 * 5943 * @return true if this view does not cache its drawing, false otherwise 5944 */ 5945 @ViewDebug.ExportedProperty(category = "drawing") 5946 public boolean willNotCacheDrawing() { 5947 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 5948 } 5949 5950 /** 5951 * Indicates whether this view reacts to click events or not. 5952 * 5953 * @return true if the view is clickable, false otherwise 5954 * 5955 * @see #setClickable(boolean) 5956 * @attr ref android.R.styleable#View_clickable 5957 */ 5958 @ViewDebug.ExportedProperty 5959 public boolean isClickable() { 5960 return (mViewFlags & CLICKABLE) == CLICKABLE; 5961 } 5962 5963 /** 5964 * Enables or disables click events for this view. When a view 5965 * is clickable it will change its state to "pressed" on every click. 5966 * Subclasses should set the view clickable to visually react to 5967 * user's clicks. 5968 * 5969 * @param clickable true to make the view clickable, false otherwise 5970 * 5971 * @see #isClickable() 5972 * @attr ref android.R.styleable#View_clickable 5973 */ 5974 public void setClickable(boolean clickable) { 5975 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 5976 } 5977 5978 /** 5979 * Indicates whether this view reacts to long click events or not. 5980 * 5981 * @return true if the view is long clickable, false otherwise 5982 * 5983 * @see #setLongClickable(boolean) 5984 * @attr ref android.R.styleable#View_longClickable 5985 */ 5986 public boolean isLongClickable() { 5987 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 5988 } 5989 5990 /** 5991 * Enables or disables long click events for this view. When a view is long 5992 * clickable it reacts to the user holding down the button for a longer 5993 * duration than a tap. This event can either launch the listener or a 5994 * context menu. 5995 * 5996 * @param longClickable true to make the view long clickable, false otherwise 5997 * @see #isLongClickable() 5998 * @attr ref android.R.styleable#View_longClickable 5999 */ 6000 public void setLongClickable(boolean longClickable) { 6001 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 6002 } 6003 6004 /** 6005 * Sets the pressed state for this view. 6006 * 6007 * @see #isClickable() 6008 * @see #setClickable(boolean) 6009 * 6010 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 6011 * the View's internal state from a previously set "pressed" state. 6012 */ 6013 public void setPressed(boolean pressed) { 6014 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 6015 6016 if (pressed) { 6017 mPrivateFlags |= PFLAG_PRESSED; 6018 } else { 6019 mPrivateFlags &= ~PFLAG_PRESSED; 6020 } 6021 6022 if (needsRefresh) { 6023 refreshDrawableState(); 6024 } 6025 dispatchSetPressed(pressed); 6026 } 6027 6028 /** 6029 * Dispatch setPressed to all of this View's children. 6030 * 6031 * @see #setPressed(boolean) 6032 * 6033 * @param pressed The new pressed state 6034 */ 6035 protected void dispatchSetPressed(boolean pressed) { 6036 } 6037 6038 /** 6039 * Indicates whether the view is currently in pressed state. Unless 6040 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 6041 * the pressed state. 6042 * 6043 * @see #setPressed(boolean) 6044 * @see #isClickable() 6045 * @see #setClickable(boolean) 6046 * 6047 * @return true if the view is currently pressed, false otherwise 6048 */ 6049 public boolean isPressed() { 6050 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 6051 } 6052 6053 /** 6054 * Indicates whether this view will save its state (that is, 6055 * whether its {@link #onSaveInstanceState} method will be called). 6056 * 6057 * @return Returns true if the view state saving is enabled, else false. 6058 * 6059 * @see #setSaveEnabled(boolean) 6060 * @attr ref android.R.styleable#View_saveEnabled 6061 */ 6062 public boolean isSaveEnabled() { 6063 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 6064 } 6065 6066 /** 6067 * Controls whether the saving of this view's state is 6068 * enabled (that is, whether its {@link #onSaveInstanceState} method 6069 * will be called). Note that even if freezing is enabled, the 6070 * view still must have an id assigned to it (via {@link #setId(int)}) 6071 * for its state to be saved. This flag can only disable the 6072 * saving of this view; any child views may still have their state saved. 6073 * 6074 * @param enabled Set to false to <em>disable</em> state saving, or true 6075 * (the default) to allow it. 6076 * 6077 * @see #isSaveEnabled() 6078 * @see #setId(int) 6079 * @see #onSaveInstanceState() 6080 * @attr ref android.R.styleable#View_saveEnabled 6081 */ 6082 public void setSaveEnabled(boolean enabled) { 6083 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 6084 } 6085 6086 /** 6087 * Gets whether the framework should discard touches when the view's 6088 * window is obscured by another visible window. 6089 * Refer to the {@link View} security documentation for more details. 6090 * 6091 * @return True if touch filtering is enabled. 6092 * 6093 * @see #setFilterTouchesWhenObscured(boolean) 6094 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6095 */ 6096 @ViewDebug.ExportedProperty 6097 public boolean getFilterTouchesWhenObscured() { 6098 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 6099 } 6100 6101 /** 6102 * Sets whether the framework should discard touches when the view's 6103 * window is obscured by another visible window. 6104 * Refer to the {@link View} security documentation for more details. 6105 * 6106 * @param enabled True if touch filtering should be enabled. 6107 * 6108 * @see #getFilterTouchesWhenObscured 6109 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6110 */ 6111 public void setFilterTouchesWhenObscured(boolean enabled) { 6112 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED, 6113 FILTER_TOUCHES_WHEN_OBSCURED); 6114 } 6115 6116 /** 6117 * Indicates whether the entire hierarchy under this view will save its 6118 * state when a state saving traversal occurs from its parent. The default 6119 * is true; if false, these views will not be saved unless 6120 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6121 * 6122 * @return Returns true if the view state saving from parent is enabled, else false. 6123 * 6124 * @see #setSaveFromParentEnabled(boolean) 6125 */ 6126 public boolean isSaveFromParentEnabled() { 6127 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 6128 } 6129 6130 /** 6131 * Controls whether the entire hierarchy under this view will save its 6132 * state when a state saving traversal occurs from its parent. The default 6133 * is true; if false, these views will not be saved unless 6134 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6135 * 6136 * @param enabled Set to false to <em>disable</em> state saving, or true 6137 * (the default) to allow it. 6138 * 6139 * @see #isSaveFromParentEnabled() 6140 * @see #setId(int) 6141 * @see #onSaveInstanceState() 6142 */ 6143 public void setSaveFromParentEnabled(boolean enabled) { 6144 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 6145 } 6146 6147 6148 /** 6149 * Returns whether this View is able to take focus. 6150 * 6151 * @return True if this view can take focus, or false otherwise. 6152 * @attr ref android.R.styleable#View_focusable 6153 */ 6154 @ViewDebug.ExportedProperty(category = "focus") 6155 public final boolean isFocusable() { 6156 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 6157 } 6158 6159 /** 6160 * When a view is focusable, it may not want to take focus when in touch mode. 6161 * For example, a button would like focus when the user is navigating via a D-pad 6162 * so that the user can click on it, but once the user starts touching the screen, 6163 * the button shouldn't take focus 6164 * @return Whether the view is focusable in touch mode. 6165 * @attr ref android.R.styleable#View_focusableInTouchMode 6166 */ 6167 @ViewDebug.ExportedProperty 6168 public final boolean isFocusableInTouchMode() { 6169 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 6170 } 6171 6172 /** 6173 * Find the nearest view in the specified direction that can take focus. 6174 * This does not actually give focus to that view. 6175 * 6176 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 6177 * 6178 * @return The nearest focusable in the specified direction, or null if none 6179 * can be found. 6180 */ 6181 public View focusSearch(int direction) { 6182 if (mParent != null) { 6183 return mParent.focusSearch(this, direction); 6184 } else { 6185 return null; 6186 } 6187 } 6188 6189 /** 6190 * This method is the last chance for the focused view and its ancestors to 6191 * respond to an arrow key. This is called when the focused view did not 6192 * consume the key internally, nor could the view system find a new view in 6193 * the requested direction to give focus to. 6194 * 6195 * @param focused The currently focused view. 6196 * @param direction The direction focus wants to move. One of FOCUS_UP, 6197 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 6198 * @return True if the this view consumed this unhandled move. 6199 */ 6200 public boolean dispatchUnhandledMove(View focused, int direction) { 6201 return false; 6202 } 6203 6204 /** 6205 * If a user manually specified the next view id for a particular direction, 6206 * use the root to look up the view. 6207 * @param root The root view of the hierarchy containing this view. 6208 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 6209 * or FOCUS_BACKWARD. 6210 * @return The user specified next view, or null if there is none. 6211 */ 6212 View findUserSetNextFocus(View root, int direction) { 6213 switch (direction) { 6214 case FOCUS_LEFT: 6215 if (mNextFocusLeftId == View.NO_ID) return null; 6216 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 6217 case FOCUS_RIGHT: 6218 if (mNextFocusRightId == View.NO_ID) return null; 6219 return findViewInsideOutShouldExist(root, mNextFocusRightId); 6220 case FOCUS_UP: 6221 if (mNextFocusUpId == View.NO_ID) return null; 6222 return findViewInsideOutShouldExist(root, mNextFocusUpId); 6223 case FOCUS_DOWN: 6224 if (mNextFocusDownId == View.NO_ID) return null; 6225 return findViewInsideOutShouldExist(root, mNextFocusDownId); 6226 case FOCUS_FORWARD: 6227 if (mNextFocusForwardId == View.NO_ID) return null; 6228 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 6229 case FOCUS_BACKWARD: { 6230 if (mID == View.NO_ID) return null; 6231 final int id = mID; 6232 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 6233 @Override 6234 public boolean apply(View t) { 6235 return t.mNextFocusForwardId == id; 6236 } 6237 }); 6238 } 6239 } 6240 return null; 6241 } 6242 6243 private View findViewInsideOutShouldExist(View root, int id) { 6244 if (mMatchIdPredicate == null) { 6245 mMatchIdPredicate = new MatchIdPredicate(); 6246 } 6247 mMatchIdPredicate.mId = id; 6248 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 6249 if (result == null) { 6250 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 6251 } 6252 return result; 6253 } 6254 6255 /** 6256 * Find and return all focusable views that are descendants of this view, 6257 * possibly including this view if it is focusable itself. 6258 * 6259 * @param direction The direction of the focus 6260 * @return A list of focusable views 6261 */ 6262 public ArrayList<View> getFocusables(int direction) { 6263 ArrayList<View> result = new ArrayList<View>(24); 6264 addFocusables(result, direction); 6265 return result; 6266 } 6267 6268 /** 6269 * Add any focusable views that are descendants of this view (possibly 6270 * including this view if it is focusable itself) to views. If we are in touch mode, 6271 * only add views that are also focusable in touch mode. 6272 * 6273 * @param views Focusable views found so far 6274 * @param direction The direction of the focus 6275 */ 6276 public void addFocusables(ArrayList<View> views, int direction) { 6277 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 6278 } 6279 6280 /** 6281 * Adds any focusable views that are descendants of this view (possibly 6282 * including this view if it is focusable itself) to views. This method 6283 * adds all focusable views regardless if we are in touch mode or 6284 * only views focusable in touch mode if we are in touch mode or 6285 * only views that can take accessibility focus if accessibility is enabeld 6286 * depending on the focusable mode paramater. 6287 * 6288 * @param views Focusable views found so far or null if all we are interested is 6289 * the number of focusables. 6290 * @param direction The direction of the focus. 6291 * @param focusableMode The type of focusables to be added. 6292 * 6293 * @see #FOCUSABLES_ALL 6294 * @see #FOCUSABLES_TOUCH_MODE 6295 */ 6296 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { 6297 if (views == null) { 6298 return; 6299 } 6300 if (!isFocusable()) { 6301 return; 6302 } 6303 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 6304 && isInTouchMode() && !isFocusableInTouchMode()) { 6305 return; 6306 } 6307 views.add(this); 6308 } 6309 6310 /** 6311 * Finds the Views that contain given text. The containment is case insensitive. 6312 * The search is performed by either the text that the View renders or the content 6313 * description that describes the view for accessibility purposes and the view does 6314 * not render or both. Clients can specify how the search is to be performed via 6315 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 6316 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 6317 * 6318 * @param outViews The output list of matching Views. 6319 * @param searched The text to match against. 6320 * 6321 * @see #FIND_VIEWS_WITH_TEXT 6322 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 6323 * @see #setContentDescription(CharSequence) 6324 */ 6325 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) { 6326 if (getAccessibilityNodeProvider() != null) { 6327 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 6328 outViews.add(this); 6329 } 6330 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 6331 && (searched != null && searched.length() > 0) 6332 && (mContentDescription != null && mContentDescription.length() > 0)) { 6333 String searchedLowerCase = searched.toString().toLowerCase(); 6334 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 6335 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 6336 outViews.add(this); 6337 } 6338 } 6339 } 6340 6341 /** 6342 * Find and return all touchable views that are descendants of this view, 6343 * possibly including this view if it is touchable itself. 6344 * 6345 * @return A list of touchable views 6346 */ 6347 public ArrayList<View> getTouchables() { 6348 ArrayList<View> result = new ArrayList<View>(); 6349 addTouchables(result); 6350 return result; 6351 } 6352 6353 /** 6354 * Add any touchable views that are descendants of this view (possibly 6355 * including this view if it is touchable itself) to views. 6356 * 6357 * @param views Touchable views found so far 6358 */ 6359 public void addTouchables(ArrayList<View> views) { 6360 final int viewFlags = mViewFlags; 6361 6362 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 6363 && (viewFlags & ENABLED_MASK) == ENABLED) { 6364 views.add(this); 6365 } 6366 } 6367 6368 /** 6369 * Returns whether this View is accessibility focused. 6370 * 6371 * @return True if this View is accessibility focused. 6372 */ 6373 boolean isAccessibilityFocused() { 6374 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 6375 } 6376 6377 /** 6378 * Call this to try to give accessibility focus to this view. 6379 * 6380 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 6381 * returns false or the view is no visible or the view already has accessibility 6382 * focus. 6383 * 6384 * See also {@link #focusSearch(int)}, which is what you call to say that you 6385 * have focus, and you want your parent to look for the next one. 6386 * 6387 * @return Whether this view actually took accessibility focus. 6388 * 6389 * @hide 6390 */ 6391 public boolean requestAccessibilityFocus() { 6392 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 6393 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 6394 return false; 6395 } 6396 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 6397 return false; 6398 } 6399 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 6400 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 6401 ViewRootImpl viewRootImpl = getViewRootImpl(); 6402 if (viewRootImpl != null) { 6403 viewRootImpl.setAccessibilityFocus(this, null); 6404 } 6405 if (mAttachInfo != null) { 6406 Rect rectangle = mAttachInfo.mTmpInvalRect; 6407 getDrawingRect(rectangle); 6408 requestRectangleOnScreen(rectangle); 6409 } 6410 invalidate(); 6411 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 6412 notifyAccessibilityStateChanged(); 6413 return true; 6414 } 6415 return false; 6416 } 6417 6418 /** 6419 * Call this to try to clear accessibility focus of this view. 6420 * 6421 * See also {@link #focusSearch(int)}, which is what you call to say that you 6422 * have focus, and you want your parent to look for the next one. 6423 * 6424 * @hide 6425 */ 6426 public void clearAccessibilityFocus() { 6427 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 6428 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 6429 invalidate(); 6430 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 6431 notifyAccessibilityStateChanged(); 6432 } 6433 // Clear the global reference of accessibility focus if this 6434 // view or any of its descendants had accessibility focus. 6435 ViewRootImpl viewRootImpl = getViewRootImpl(); 6436 if (viewRootImpl != null) { 6437 View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 6438 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 6439 viewRootImpl.setAccessibilityFocus(null, null); 6440 } 6441 } 6442 } 6443 6444 private void sendAccessibilityHoverEvent(int eventType) { 6445 // Since we are not delivering to a client accessibility events from not 6446 // important views (unless the clinet request that) we need to fire the 6447 // event from the deepest view exposed to the client. As a consequence if 6448 // the user crosses a not exposed view the client will see enter and exit 6449 // of the exposed predecessor followed by and enter and exit of that same 6450 // predecessor when entering and exiting the not exposed descendant. This 6451 // is fine since the client has a clear idea which view is hovered at the 6452 // price of a couple more events being sent. This is a simple and 6453 // working solution. 6454 View source = this; 6455 while (true) { 6456 if (source.includeForAccessibility()) { 6457 source.sendAccessibilityEvent(eventType); 6458 return; 6459 } 6460 ViewParent parent = source.getParent(); 6461 if (parent instanceof View) { 6462 source = (View) parent; 6463 } else { 6464 return; 6465 } 6466 } 6467 } 6468 6469 /** 6470 * Clears accessibility focus without calling any callback methods 6471 * normally invoked in {@link #clearAccessibilityFocus()}. This method 6472 * is used for clearing accessibility focus when giving this focus to 6473 * another view. 6474 */ 6475 void clearAccessibilityFocusNoCallbacks() { 6476 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 6477 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 6478 invalidate(); 6479 } 6480 } 6481 6482 /** 6483 * Call this to try to give focus to a specific view or to one of its 6484 * descendants. 6485 * 6486 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 6487 * false), or if it is focusable and it is not focusable in touch mode 6488 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 6489 * 6490 * See also {@link #focusSearch(int)}, which is what you call to say that you 6491 * have focus, and you want your parent to look for the next one. 6492 * 6493 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 6494 * {@link #FOCUS_DOWN} and <code>null</code>. 6495 * 6496 * @return Whether this view or one of its descendants actually took focus. 6497 */ 6498 public final boolean requestFocus() { 6499 return requestFocus(View.FOCUS_DOWN); 6500 } 6501 6502 /** 6503 * Call this to try to give focus to a specific view or to one of its 6504 * descendants and give it a hint about what direction focus is heading. 6505 * 6506 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 6507 * false), or if it is focusable and it is not focusable in touch mode 6508 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 6509 * 6510 * See also {@link #focusSearch(int)}, which is what you call to say that you 6511 * have focus, and you want your parent to look for the next one. 6512 * 6513 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 6514 * <code>null</code> set for the previously focused rectangle. 6515 * 6516 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 6517 * @return Whether this view or one of its descendants actually took focus. 6518 */ 6519 public final boolean requestFocus(int direction) { 6520 return requestFocus(direction, null); 6521 } 6522 6523 /** 6524 * Call this to try to give focus to a specific view or to one of its descendants 6525 * and give it hints about the direction and a specific rectangle that the focus 6526 * is coming from. The rectangle can help give larger views a finer grained hint 6527 * about where focus is coming from, and therefore, where to show selection, or 6528 * forward focus change internally. 6529 * 6530 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 6531 * false), or if it is focusable and it is not focusable in touch mode 6532 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 6533 * 6534 * A View will not take focus if it is not visible. 6535 * 6536 * A View will not take focus if one of its parents has 6537 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 6538 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 6539 * 6540 * See also {@link #focusSearch(int)}, which is what you call to say that you 6541 * have focus, and you want your parent to look for the next one. 6542 * 6543 * You may wish to override this method if your custom {@link View} has an internal 6544 * {@link View} that it wishes to forward the request to. 6545 * 6546 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 6547 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 6548 * to give a finer grained hint about where focus is coming from. May be null 6549 * if there is no hint. 6550 * @return Whether this view or one of its descendants actually took focus. 6551 */ 6552 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 6553 return requestFocusNoSearch(direction, previouslyFocusedRect); 6554 } 6555 6556 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 6557 // need to be focusable 6558 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 6559 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 6560 return false; 6561 } 6562 6563 // need to be focusable in touch mode if in touch mode 6564 if (isInTouchMode() && 6565 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 6566 return false; 6567 } 6568 6569 // need to not have any parents blocking us 6570 if (hasAncestorThatBlocksDescendantFocus()) { 6571 return false; 6572 } 6573 6574 handleFocusGainInternal(direction, previouslyFocusedRect); 6575 return true; 6576 } 6577 6578 /** 6579 * Call this to try to give focus to a specific view or to one of its descendants. This is a 6580 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 6581 * touch mode to request focus when they are touched. 6582 * 6583 * @return Whether this view or one of its descendants actually took focus. 6584 * 6585 * @see #isInTouchMode() 6586 * 6587 */ 6588 public final boolean requestFocusFromTouch() { 6589 // Leave touch mode if we need to 6590 if (isInTouchMode()) { 6591 ViewRootImpl viewRoot = getViewRootImpl(); 6592 if (viewRoot != null) { 6593 viewRoot.ensureTouchMode(false); 6594 } 6595 } 6596 return requestFocus(View.FOCUS_DOWN); 6597 } 6598 6599 /** 6600 * @return Whether any ancestor of this view blocks descendant focus. 6601 */ 6602 private boolean hasAncestorThatBlocksDescendantFocus() { 6603 ViewParent ancestor = mParent; 6604 while (ancestor instanceof ViewGroup) { 6605 final ViewGroup vgAncestor = (ViewGroup) ancestor; 6606 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) { 6607 return true; 6608 } else { 6609 ancestor = vgAncestor.getParent(); 6610 } 6611 } 6612 return false; 6613 } 6614 6615 /** 6616 * Gets the mode for determining whether this View is important for accessibility 6617 * which is if it fires accessibility events and if it is reported to 6618 * accessibility services that query the screen. 6619 * 6620 * @return The mode for determining whether a View is important for accessibility. 6621 * 6622 * @attr ref android.R.styleable#View_importantForAccessibility 6623 * 6624 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 6625 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 6626 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 6627 */ 6628 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 6629 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 6630 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 6631 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no") 6632 }) 6633 public int getImportantForAccessibility() { 6634 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 6635 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 6636 } 6637 6638 /** 6639 * Sets how to determine whether this view is important for accessibility 6640 * which is if it fires accessibility events and if it is reported to 6641 * accessibility services that query the screen. 6642 * 6643 * @param mode How to determine whether this view is important for accessibility. 6644 * 6645 * @attr ref android.R.styleable#View_importantForAccessibility 6646 * 6647 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 6648 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 6649 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 6650 */ 6651 public void setImportantForAccessibility(int mode) { 6652 if (mode != getImportantForAccessibility()) { 6653 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 6654 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 6655 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 6656 notifyAccessibilityStateChanged(); 6657 } 6658 } 6659 6660 /** 6661 * Gets whether this view should be exposed for accessibility. 6662 * 6663 * @return Whether the view is exposed for accessibility. 6664 * 6665 * @hide 6666 */ 6667 public boolean isImportantForAccessibility() { 6668 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 6669 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 6670 switch (mode) { 6671 case IMPORTANT_FOR_ACCESSIBILITY_YES: 6672 return true; 6673 case IMPORTANT_FOR_ACCESSIBILITY_NO: 6674 return false; 6675 case IMPORTANT_FOR_ACCESSIBILITY_AUTO: 6676 return isActionableForAccessibility() || hasListenersForAccessibility() 6677 || getAccessibilityNodeProvider() != null; 6678 default: 6679 throw new IllegalArgumentException("Unknow important for accessibility mode: " 6680 + mode); 6681 } 6682 } 6683 6684 /** 6685 * Gets the parent for accessibility purposes. Note that the parent for 6686 * accessibility is not necessary the immediate parent. It is the first 6687 * predecessor that is important for accessibility. 6688 * 6689 * @return The parent for accessibility purposes. 6690 */ 6691 public ViewParent getParentForAccessibility() { 6692 if (mParent instanceof View) { 6693 View parentView = (View) mParent; 6694 if (parentView.includeForAccessibility()) { 6695 return mParent; 6696 } else { 6697 return mParent.getParentForAccessibility(); 6698 } 6699 } 6700 return null; 6701 } 6702 6703 /** 6704 * Adds the children of a given View for accessibility. Since some Views are 6705 * not important for accessibility the children for accessibility are not 6706 * necessarily direct children of the riew, rather they are the first level of 6707 * descendants important for accessibility. 6708 * 6709 * @param children The list of children for accessibility. 6710 */ 6711 public void addChildrenForAccessibility(ArrayList<View> children) { 6712 if (includeForAccessibility()) { 6713 children.add(this); 6714 } 6715 } 6716 6717 /** 6718 * Whether to regard this view for accessibility. A view is regarded for 6719 * accessibility if it is important for accessibility or the querying 6720 * accessibility service has explicitly requested that view not 6721 * important for accessibility are regarded. 6722 * 6723 * @return Whether to regard the view for accessibility. 6724 * 6725 * @hide 6726 */ 6727 public boolean includeForAccessibility() { 6728 if (mAttachInfo != null) { 6729 return mAttachInfo.mIncludeNotImportantViews || isImportantForAccessibility(); 6730 } 6731 return false; 6732 } 6733 6734 /** 6735 * Returns whether the View is considered actionable from 6736 * accessibility perspective. Such view are important for 6737 * accessibility. 6738 * 6739 * @return True if the view is actionable for accessibility. 6740 * 6741 * @hide 6742 */ 6743 public boolean isActionableForAccessibility() { 6744 return (isClickable() || isLongClickable() || isFocusable()); 6745 } 6746 6747 /** 6748 * Returns whether the View has registered callbacks wich makes it 6749 * important for accessibility. 6750 * 6751 * @return True if the view is actionable for accessibility. 6752 */ 6753 private boolean hasListenersForAccessibility() { 6754 ListenerInfo info = getListenerInfo(); 6755 return mTouchDelegate != null || info.mOnKeyListener != null 6756 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 6757 || info.mOnHoverListener != null || info.mOnDragListener != null; 6758 } 6759 6760 /** 6761 * Notifies accessibility services that some view's important for 6762 * accessibility state has changed. Note that such notifications 6763 * are made at most once every 6764 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 6765 * to avoid unnecessary load to the system. Also once a view has 6766 * made a notifucation this method is a NOP until the notification has 6767 * been sent to clients. 6768 * 6769 * @hide 6770 * 6771 * TODO: Makse sure this method is called for any view state change 6772 * that is interesting for accessilility purposes. 6773 */ 6774 public void notifyAccessibilityStateChanged() { 6775 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 6776 return; 6777 } 6778 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_STATE_CHANGED) == 0) { 6779 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_STATE_CHANGED; 6780 if (mParent != null) { 6781 mParent.childAccessibilityStateChanged(this); 6782 } 6783 } 6784 } 6785 6786 /** 6787 * Reset the state indicating the this view has requested clients 6788 * interested in its accessibility state to be notified. 6789 * 6790 * @hide 6791 */ 6792 public void resetAccessibilityStateChanged() { 6793 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_STATE_CHANGED; 6794 } 6795 6796 /** 6797 * Performs the specified accessibility action on the view. For 6798 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 6799 * <p> 6800 * If an {@link AccessibilityDelegate} has been specified via calling 6801 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6802 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 6803 * is responsible for handling this call. 6804 * </p> 6805 * 6806 * @param action The action to perform. 6807 * @param arguments Optional action arguments. 6808 * @return Whether the action was performed. 6809 */ 6810 public boolean performAccessibilityAction(int action, Bundle arguments) { 6811 if (mAccessibilityDelegate != null) { 6812 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 6813 } else { 6814 return performAccessibilityActionInternal(action, arguments); 6815 } 6816 } 6817 6818 /** 6819 * @see #performAccessibilityAction(int, Bundle) 6820 * 6821 * Note: Called from the default {@link AccessibilityDelegate}. 6822 */ 6823 boolean performAccessibilityActionInternal(int action, Bundle arguments) { 6824 switch (action) { 6825 case AccessibilityNodeInfo.ACTION_CLICK: { 6826 if (isClickable()) { 6827 return performClick(); 6828 } 6829 } break; 6830 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 6831 if (isLongClickable()) { 6832 return performLongClick(); 6833 } 6834 } break; 6835 case AccessibilityNodeInfo.ACTION_FOCUS: { 6836 if (!hasFocus()) { 6837 // Get out of touch mode since accessibility 6838 // wants to move focus around. 6839 getViewRootImpl().ensureTouchMode(false); 6840 return requestFocus(); 6841 } 6842 } break; 6843 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 6844 if (hasFocus()) { 6845 clearFocus(); 6846 return !isFocused(); 6847 } 6848 } break; 6849 case AccessibilityNodeInfo.ACTION_SELECT: { 6850 if (!isSelected()) { 6851 setSelected(true); 6852 return isSelected(); 6853 } 6854 } break; 6855 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 6856 if (isSelected()) { 6857 setSelected(false); 6858 return !isSelected(); 6859 } 6860 } break; 6861 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 6862 if (!isAccessibilityFocused()) { 6863 return requestAccessibilityFocus(); 6864 } 6865 } break; 6866 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 6867 if (isAccessibilityFocused()) { 6868 clearAccessibilityFocus(); 6869 return true; 6870 } 6871 } break; 6872 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 6873 if (arguments != null) { 6874 final int granularity = arguments.getInt( 6875 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 6876 return nextAtGranularity(granularity); 6877 } 6878 } break; 6879 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 6880 if (arguments != null) { 6881 final int granularity = arguments.getInt( 6882 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 6883 return previousAtGranularity(granularity); 6884 } 6885 } break; 6886 } 6887 return false; 6888 } 6889 6890 private boolean nextAtGranularity(int granularity) { 6891 CharSequence text = getIterableTextForAccessibility(); 6892 if (text == null || text.length() == 0) { 6893 return false; 6894 } 6895 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 6896 if (iterator == null) { 6897 return false; 6898 } 6899 final int current = getAccessibilityCursorPosition(); 6900 final int[] range = iterator.following(current); 6901 if (range == null) { 6902 return false; 6903 } 6904 final int start = range[0]; 6905 final int end = range[1]; 6906 setAccessibilityCursorPosition(end); 6907 sendViewTextTraversedAtGranularityEvent( 6908 AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY, 6909 granularity, start, end); 6910 return true; 6911 } 6912 6913 private boolean previousAtGranularity(int granularity) { 6914 CharSequence text = getIterableTextForAccessibility(); 6915 if (text == null || text.length() == 0) { 6916 return false; 6917 } 6918 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 6919 if (iterator == null) { 6920 return false; 6921 } 6922 int current = getAccessibilityCursorPosition(); 6923 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 6924 current = text.length(); 6925 } else if (granularity == AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER) { 6926 // When traversing by character we always put the cursor after the character 6927 // to ease edit and have to compensate before asking the for previous segment. 6928 current--; 6929 } 6930 final int[] range = iterator.preceding(current); 6931 if (range == null) { 6932 return false; 6933 } 6934 final int start = range[0]; 6935 final int end = range[1]; 6936 // Always put the cursor after the character to ease edit. 6937 if (granularity == AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER) { 6938 setAccessibilityCursorPosition(end); 6939 } else { 6940 setAccessibilityCursorPosition(start); 6941 } 6942 sendViewTextTraversedAtGranularityEvent( 6943 AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY, 6944 granularity, start, end); 6945 return true; 6946 } 6947 6948 /** 6949 * Gets the text reported for accessibility purposes. 6950 * 6951 * @return The accessibility text. 6952 * 6953 * @hide 6954 */ 6955 public CharSequence getIterableTextForAccessibility() { 6956 return getContentDescription(); 6957 } 6958 6959 /** 6960 * @hide 6961 */ 6962 public int getAccessibilityCursorPosition() { 6963 return mAccessibilityCursorPosition; 6964 } 6965 6966 /** 6967 * @hide 6968 */ 6969 public void setAccessibilityCursorPosition(int position) { 6970 mAccessibilityCursorPosition = position; 6971 } 6972 6973 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 6974 int fromIndex, int toIndex) { 6975 if (mParent == null) { 6976 return; 6977 } 6978 AccessibilityEvent event = AccessibilityEvent.obtain( 6979 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 6980 onInitializeAccessibilityEvent(event); 6981 onPopulateAccessibilityEvent(event); 6982 event.setFromIndex(fromIndex); 6983 event.setToIndex(toIndex); 6984 event.setAction(action); 6985 event.setMovementGranularity(granularity); 6986 mParent.requestSendAccessibilityEvent(this, event); 6987 } 6988 6989 /** 6990 * @hide 6991 */ 6992 public TextSegmentIterator getIteratorForGranularity(int granularity) { 6993 switch (granularity) { 6994 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 6995 CharSequence text = getIterableTextForAccessibility(); 6996 if (text != null && text.length() > 0) { 6997 CharacterTextSegmentIterator iterator = 6998 CharacterTextSegmentIterator.getInstance( 6999 mContext.getResources().getConfiguration().locale); 7000 iterator.initialize(text.toString()); 7001 return iterator; 7002 } 7003 } break; 7004 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 7005 CharSequence text = getIterableTextForAccessibility(); 7006 if (text != null && text.length() > 0) { 7007 WordTextSegmentIterator iterator = 7008 WordTextSegmentIterator.getInstance( 7009 mContext.getResources().getConfiguration().locale); 7010 iterator.initialize(text.toString()); 7011 return iterator; 7012 } 7013 } break; 7014 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 7015 CharSequence text = getIterableTextForAccessibility(); 7016 if (text != null && text.length() > 0) { 7017 ParagraphTextSegmentIterator iterator = 7018 ParagraphTextSegmentIterator.getInstance(); 7019 iterator.initialize(text.toString()); 7020 return iterator; 7021 } 7022 } break; 7023 } 7024 return null; 7025 } 7026 7027 /** 7028 * @hide 7029 */ 7030 public void dispatchStartTemporaryDetach() { 7031 clearAccessibilityFocus(); 7032 clearDisplayList(); 7033 7034 onStartTemporaryDetach(); 7035 } 7036 7037 /** 7038 * This is called when a container is going to temporarily detach a child, with 7039 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 7040 * It will either be followed by {@link #onFinishTemporaryDetach()} or 7041 * {@link #onDetachedFromWindow()} when the container is done. 7042 */ 7043 public void onStartTemporaryDetach() { 7044 removeUnsetPressCallback(); 7045 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 7046 } 7047 7048 /** 7049 * @hide 7050 */ 7051 public void dispatchFinishTemporaryDetach() { 7052 onFinishTemporaryDetach(); 7053 } 7054 7055 /** 7056 * Called after {@link #onStartTemporaryDetach} when the container is done 7057 * changing the view. 7058 */ 7059 public void onFinishTemporaryDetach() { 7060 } 7061 7062 /** 7063 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 7064 * for this view's window. Returns null if the view is not currently attached 7065 * to the window. Normally you will not need to use this directly, but 7066 * just use the standard high-level event callbacks like 7067 * {@link #onKeyDown(int, KeyEvent)}. 7068 */ 7069 public KeyEvent.DispatcherState getKeyDispatcherState() { 7070 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 7071 } 7072 7073 /** 7074 * Dispatch a key event before it is processed by any input method 7075 * associated with the view hierarchy. This can be used to intercept 7076 * key events in special situations before the IME consumes them; a 7077 * typical example would be handling the BACK key to update the application's 7078 * UI instead of allowing the IME to see it and close itself. 7079 * 7080 * @param event The key event to be dispatched. 7081 * @return True if the event was handled, false otherwise. 7082 */ 7083 public boolean dispatchKeyEventPreIme(KeyEvent event) { 7084 return onKeyPreIme(event.getKeyCode(), event); 7085 } 7086 7087 /** 7088 * Dispatch a key event to the next view on the focus path. This path runs 7089 * from the top of the view tree down to the currently focused view. If this 7090 * view has focus, it will dispatch to itself. Otherwise it will dispatch 7091 * the next node down the focus path. This method also fires any key 7092 * listeners. 7093 * 7094 * @param event The key event to be dispatched. 7095 * @return True if the event was handled, false otherwise. 7096 */ 7097 public boolean dispatchKeyEvent(KeyEvent event) { 7098 if (mInputEventConsistencyVerifier != null) { 7099 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 7100 } 7101 7102 // Give any attached key listener a first crack at the event. 7103 //noinspection SimplifiableIfStatement 7104 ListenerInfo li = mListenerInfo; 7105 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 7106 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 7107 return true; 7108 } 7109 7110 if (event.dispatch(this, mAttachInfo != null 7111 ? mAttachInfo.mKeyDispatchState : null, this)) { 7112 return true; 7113 } 7114 7115 if (mInputEventConsistencyVerifier != null) { 7116 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7117 } 7118 return false; 7119 } 7120 7121 /** 7122 * Dispatches a key shortcut event. 7123 * 7124 * @param event The key event to be dispatched. 7125 * @return True if the event was handled by the view, false otherwise. 7126 */ 7127 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 7128 return onKeyShortcut(event.getKeyCode(), event); 7129 } 7130 7131 /** 7132 * Pass the touch screen motion event down to the target view, or this 7133 * view if it is the target. 7134 * 7135 * @param event The motion event to be dispatched. 7136 * @return True if the event was handled by the view, false otherwise. 7137 */ 7138 public boolean dispatchTouchEvent(MotionEvent event) { 7139 if (mInputEventConsistencyVerifier != null) { 7140 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 7141 } 7142 7143 if (onFilterTouchEventForSecurity(event)) { 7144 //noinspection SimplifiableIfStatement 7145 ListenerInfo li = mListenerInfo; 7146 if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 7147 && li.mOnTouchListener.onTouch(this, event)) { 7148 return true; 7149 } 7150 7151 if (onTouchEvent(event)) { 7152 return true; 7153 } 7154 } 7155 7156 if (mInputEventConsistencyVerifier != null) { 7157 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7158 } 7159 return false; 7160 } 7161 7162 /** 7163 * Filter the touch event to apply security policies. 7164 * 7165 * @param event The motion event to be filtered. 7166 * @return True if the event should be dispatched, false if the event should be dropped. 7167 * 7168 * @see #getFilterTouchesWhenObscured 7169 */ 7170 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 7171 //noinspection RedundantIfStatement 7172 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 7173 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 7174 // Window is obscured, drop this touch. 7175 return false; 7176 } 7177 return true; 7178 } 7179 7180 /** 7181 * Pass a trackball motion event down to the focused view. 7182 * 7183 * @param event The motion event to be dispatched. 7184 * @return True if the event was handled by the view, false otherwise. 7185 */ 7186 public boolean dispatchTrackballEvent(MotionEvent event) { 7187 if (mInputEventConsistencyVerifier != null) { 7188 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 7189 } 7190 7191 return onTrackballEvent(event); 7192 } 7193 7194 /** 7195 * Dispatch a generic motion event. 7196 * <p> 7197 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 7198 * are delivered to the view under the pointer. All other generic motion events are 7199 * delivered to the focused view. Hover events are handled specially and are delivered 7200 * to {@link #onHoverEvent(MotionEvent)}. 7201 * </p> 7202 * 7203 * @param event The motion event to be dispatched. 7204 * @return True if the event was handled by the view, false otherwise. 7205 */ 7206 public boolean dispatchGenericMotionEvent(MotionEvent event) { 7207 if (mInputEventConsistencyVerifier != null) { 7208 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 7209 } 7210 7211 final int source = event.getSource(); 7212 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 7213 final int action = event.getAction(); 7214 if (action == MotionEvent.ACTION_HOVER_ENTER 7215 || action == MotionEvent.ACTION_HOVER_MOVE 7216 || action == MotionEvent.ACTION_HOVER_EXIT) { 7217 if (dispatchHoverEvent(event)) { 7218 return true; 7219 } 7220 } else if (dispatchGenericPointerEvent(event)) { 7221 return true; 7222 } 7223 } else if (dispatchGenericFocusedEvent(event)) { 7224 return true; 7225 } 7226 7227 if (dispatchGenericMotionEventInternal(event)) { 7228 return true; 7229 } 7230 7231 if (mInputEventConsistencyVerifier != null) { 7232 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7233 } 7234 return false; 7235 } 7236 7237 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 7238 //noinspection SimplifiableIfStatement 7239 ListenerInfo li = mListenerInfo; 7240 if (li != null && li.mOnGenericMotionListener != null 7241 && (mViewFlags & ENABLED_MASK) == ENABLED 7242 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 7243 return true; 7244 } 7245 7246 if (onGenericMotionEvent(event)) { 7247 return true; 7248 } 7249 7250 if (mInputEventConsistencyVerifier != null) { 7251 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7252 } 7253 return false; 7254 } 7255 7256 /** 7257 * Dispatch a hover event. 7258 * <p> 7259 * Do not call this method directly. 7260 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 7261 * </p> 7262 * 7263 * @param event The motion event to be dispatched. 7264 * @return True if the event was handled by the view, false otherwise. 7265 */ 7266 protected boolean dispatchHoverEvent(MotionEvent event) { 7267 //noinspection SimplifiableIfStatement 7268 ListenerInfo li = mListenerInfo; 7269 if (li != null && li.mOnHoverListener != null 7270 && (mViewFlags & ENABLED_MASK) == ENABLED 7271 && li.mOnHoverListener.onHover(this, event)) { 7272 return true; 7273 } 7274 7275 return onHoverEvent(event); 7276 } 7277 7278 /** 7279 * Returns true if the view has a child to which it has recently sent 7280 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 7281 * it does not have a hovered child, then it must be the innermost hovered view. 7282 * @hide 7283 */ 7284 protected boolean hasHoveredChild() { 7285 return false; 7286 } 7287 7288 /** 7289 * Dispatch a generic motion event to the view under the first pointer. 7290 * <p> 7291 * Do not call this method directly. 7292 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 7293 * </p> 7294 * 7295 * @param event The motion event to be dispatched. 7296 * @return True if the event was handled by the view, false otherwise. 7297 */ 7298 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 7299 return false; 7300 } 7301 7302 /** 7303 * Dispatch a generic motion event to the currently focused view. 7304 * <p> 7305 * Do not call this method directly. 7306 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 7307 * </p> 7308 * 7309 * @param event The motion event to be dispatched. 7310 * @return True if the event was handled by the view, false otherwise. 7311 */ 7312 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 7313 return false; 7314 } 7315 7316 /** 7317 * Dispatch a pointer event. 7318 * <p> 7319 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 7320 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 7321 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 7322 * and should not be expected to handle other pointing device features. 7323 * </p> 7324 * 7325 * @param event The motion event to be dispatched. 7326 * @return True if the event was handled by the view, false otherwise. 7327 * @hide 7328 */ 7329 public final boolean dispatchPointerEvent(MotionEvent event) { 7330 if (event.isTouchEvent()) { 7331 return dispatchTouchEvent(event); 7332 } else { 7333 return dispatchGenericMotionEvent(event); 7334 } 7335 } 7336 7337 /** 7338 * Called when the window containing this view gains or loses window focus. 7339 * ViewGroups should override to route to their children. 7340 * 7341 * @param hasFocus True if the window containing this view now has focus, 7342 * false otherwise. 7343 */ 7344 public void dispatchWindowFocusChanged(boolean hasFocus) { 7345 onWindowFocusChanged(hasFocus); 7346 } 7347 7348 /** 7349 * Called when the window containing this view gains or loses focus. Note 7350 * that this is separate from view focus: to receive key events, both 7351 * your view and its window must have focus. If a window is displayed 7352 * on top of yours that takes input focus, then your own window will lose 7353 * focus but the view focus will remain unchanged. 7354 * 7355 * @param hasWindowFocus True if the window containing this view now has 7356 * focus, false otherwise. 7357 */ 7358 public void onWindowFocusChanged(boolean hasWindowFocus) { 7359 InputMethodManager imm = InputMethodManager.peekInstance(); 7360 if (!hasWindowFocus) { 7361 if (isPressed()) { 7362 setPressed(false); 7363 } 7364 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 7365 imm.focusOut(this); 7366 } 7367 removeLongPressCallback(); 7368 removeTapCallback(); 7369 onFocusLost(); 7370 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 7371 imm.focusIn(this); 7372 } 7373 refreshDrawableState(); 7374 } 7375 7376 /** 7377 * Returns true if this view is in a window that currently has window focus. 7378 * Note that this is not the same as the view itself having focus. 7379 * 7380 * @return True if this view is in a window that currently has window focus. 7381 */ 7382 public boolean hasWindowFocus() { 7383 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 7384 } 7385 7386 /** 7387 * Dispatch a view visibility change down the view hierarchy. 7388 * ViewGroups should override to route to their children. 7389 * @param changedView The view whose visibility changed. Could be 'this' or 7390 * an ancestor view. 7391 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 7392 * {@link #INVISIBLE} or {@link #GONE}. 7393 */ 7394 protected void dispatchVisibilityChanged(View changedView, int visibility) { 7395 onVisibilityChanged(changedView, visibility); 7396 } 7397 7398 /** 7399 * Called when the visibility of the view or an ancestor of the view is changed. 7400 * @param changedView The view whose visibility changed. Could be 'this' or 7401 * an ancestor view. 7402 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 7403 * {@link #INVISIBLE} or {@link #GONE}. 7404 */ 7405 protected void onVisibilityChanged(View changedView, int visibility) { 7406 if (visibility == VISIBLE) { 7407 if (mAttachInfo != null) { 7408 initialAwakenScrollBars(); 7409 } else { 7410 mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 7411 } 7412 } 7413 } 7414 7415 /** 7416 * Dispatch a hint about whether this view is displayed. For instance, when 7417 * a View moves out of the screen, it might receives a display hint indicating 7418 * the view is not displayed. Applications should not <em>rely</em> on this hint 7419 * as there is no guarantee that they will receive one. 7420 * 7421 * @param hint A hint about whether or not this view is displayed: 7422 * {@link #VISIBLE} or {@link #INVISIBLE}. 7423 */ 7424 public void dispatchDisplayHint(int hint) { 7425 onDisplayHint(hint); 7426 } 7427 7428 /** 7429 * Gives this view a hint about whether is displayed or not. For instance, when 7430 * a View moves out of the screen, it might receives a display hint indicating 7431 * the view is not displayed. Applications should not <em>rely</em> on this hint 7432 * as there is no guarantee that they will receive one. 7433 * 7434 * @param hint A hint about whether or not this view is displayed: 7435 * {@link #VISIBLE} or {@link #INVISIBLE}. 7436 */ 7437 protected void onDisplayHint(int hint) { 7438 } 7439 7440 /** 7441 * Dispatch a window visibility change down the view hierarchy. 7442 * ViewGroups should override to route to their children. 7443 * 7444 * @param visibility The new visibility of the window. 7445 * 7446 * @see #onWindowVisibilityChanged(int) 7447 */ 7448 public void dispatchWindowVisibilityChanged(int visibility) { 7449 onWindowVisibilityChanged(visibility); 7450 } 7451 7452 /** 7453 * Called when the window containing has change its visibility 7454 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 7455 * that this tells you whether or not your window is being made visible 7456 * to the window manager; this does <em>not</em> tell you whether or not 7457 * your window is obscured by other windows on the screen, even if it 7458 * is itself visible. 7459 * 7460 * @param visibility The new visibility of the window. 7461 */ 7462 protected void onWindowVisibilityChanged(int visibility) { 7463 if (visibility == VISIBLE) { 7464 initialAwakenScrollBars(); 7465 } 7466 } 7467 7468 /** 7469 * Returns the current visibility of the window this view is attached to 7470 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 7471 * 7472 * @return Returns the current visibility of the view's window. 7473 */ 7474 public int getWindowVisibility() { 7475 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 7476 } 7477 7478 /** 7479 * Retrieve the overall visible display size in which the window this view is 7480 * attached to has been positioned in. This takes into account screen 7481 * decorations above the window, for both cases where the window itself 7482 * is being position inside of them or the window is being placed under 7483 * then and covered insets are used for the window to position its content 7484 * inside. In effect, this tells you the available area where content can 7485 * be placed and remain visible to users. 7486 * 7487 * <p>This function requires an IPC back to the window manager to retrieve 7488 * the requested information, so should not be used in performance critical 7489 * code like drawing. 7490 * 7491 * @param outRect Filled in with the visible display frame. If the view 7492 * is not attached to a window, this is simply the raw display size. 7493 */ 7494 public void getWindowVisibleDisplayFrame(Rect outRect) { 7495 if (mAttachInfo != null) { 7496 try { 7497 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 7498 } catch (RemoteException e) { 7499 return; 7500 } 7501 // XXX This is really broken, and probably all needs to be done 7502 // in the window manager, and we need to know more about whether 7503 // we want the area behind or in front of the IME. 7504 final Rect insets = mAttachInfo.mVisibleInsets; 7505 outRect.left += insets.left; 7506 outRect.top += insets.top; 7507 outRect.right -= insets.right; 7508 outRect.bottom -= insets.bottom; 7509 return; 7510 } 7511 // The view is not attached to a display so we don't have a context. 7512 // Make a best guess about the display size. 7513 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 7514 d.getRectSize(outRect); 7515 } 7516 7517 /** 7518 * Dispatch a notification about a resource configuration change down 7519 * the view hierarchy. 7520 * ViewGroups should override to route to their children. 7521 * 7522 * @param newConfig The new resource configuration. 7523 * 7524 * @see #onConfigurationChanged(android.content.res.Configuration) 7525 */ 7526 public void dispatchConfigurationChanged(Configuration newConfig) { 7527 onConfigurationChanged(newConfig); 7528 } 7529 7530 /** 7531 * Called when the current configuration of the resources being used 7532 * by the application have changed. You can use this to decide when 7533 * to reload resources that can changed based on orientation and other 7534 * configuration characterstics. You only need to use this if you are 7535 * not relying on the normal {@link android.app.Activity} mechanism of 7536 * recreating the activity instance upon a configuration change. 7537 * 7538 * @param newConfig The new resource configuration. 7539 */ 7540 protected void onConfigurationChanged(Configuration newConfig) { 7541 } 7542 7543 /** 7544 * Private function to aggregate all per-view attributes in to the view 7545 * root. 7546 */ 7547 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 7548 performCollectViewAttributes(attachInfo, visibility); 7549 } 7550 7551 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 7552 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 7553 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 7554 attachInfo.mKeepScreenOn = true; 7555 } 7556 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 7557 ListenerInfo li = mListenerInfo; 7558 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 7559 attachInfo.mHasSystemUiListeners = true; 7560 } 7561 } 7562 } 7563 7564 void needGlobalAttributesUpdate(boolean force) { 7565 final AttachInfo ai = mAttachInfo; 7566 if (ai != null && !ai.mRecomputeGlobalAttributes) { 7567 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 7568 || ai.mHasSystemUiListeners) { 7569 ai.mRecomputeGlobalAttributes = true; 7570 } 7571 } 7572 } 7573 7574 /** 7575 * Returns whether the device is currently in touch mode. Touch mode is entered 7576 * once the user begins interacting with the device by touch, and affects various 7577 * things like whether focus is always visible to the user. 7578 * 7579 * @return Whether the device is in touch mode. 7580 */ 7581 @ViewDebug.ExportedProperty 7582 public boolean isInTouchMode() { 7583 if (mAttachInfo != null) { 7584 return mAttachInfo.mInTouchMode; 7585 } else { 7586 return ViewRootImpl.isInTouchMode(); 7587 } 7588 } 7589 7590 /** 7591 * Returns the context the view is running in, through which it can 7592 * access the current theme, resources, etc. 7593 * 7594 * @return The view's Context. 7595 */ 7596 @ViewDebug.CapturedViewProperty 7597 public final Context getContext() { 7598 return mContext; 7599 } 7600 7601 /** 7602 * Handle a key event before it is processed by any input method 7603 * associated with the view hierarchy. This can be used to intercept 7604 * key events in special situations before the IME consumes them; a 7605 * typical example would be handling the BACK key to update the application's 7606 * UI instead of allowing the IME to see it and close itself. 7607 * 7608 * @param keyCode The value in event.getKeyCode(). 7609 * @param event Description of the key event. 7610 * @return If you handled the event, return true. If you want to allow the 7611 * event to be handled by the next receiver, return false. 7612 */ 7613 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 7614 return false; 7615 } 7616 7617 /** 7618 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 7619 * KeyEvent.Callback.onKeyDown()}: perform press of the view 7620 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 7621 * is released, if the view is enabled and clickable. 7622 * 7623 * <p>Key presses in software keyboards will generally NOT trigger this listener, 7624 * although some may elect to do so in some situations. Do not rely on this to 7625 * catch software key presses. 7626 * 7627 * @param keyCode A key code that represents the button pressed, from 7628 * {@link android.view.KeyEvent}. 7629 * @param event The KeyEvent object that defines the button action. 7630 */ 7631 public boolean onKeyDown(int keyCode, KeyEvent event) { 7632 boolean result = false; 7633 7634 switch (keyCode) { 7635 case KeyEvent.KEYCODE_DPAD_CENTER: 7636 case KeyEvent.KEYCODE_ENTER: { 7637 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 7638 return true; 7639 } 7640 // Long clickable items don't necessarily have to be clickable 7641 if (((mViewFlags & CLICKABLE) == CLICKABLE || 7642 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 7643 (event.getRepeatCount() == 0)) { 7644 setPressed(true); 7645 checkForLongClick(0); 7646 return true; 7647 } 7648 break; 7649 } 7650 } 7651 return result; 7652 } 7653 7654 /** 7655 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 7656 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 7657 * the event). 7658 * <p>Key presses in software keyboards will generally NOT trigger this listener, 7659 * although some may elect to do so in some situations. Do not rely on this to 7660 * catch software key presses. 7661 */ 7662 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 7663 return false; 7664 } 7665 7666 /** 7667 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 7668 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 7669 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 7670 * {@link KeyEvent#KEYCODE_ENTER} is released. 7671 * <p>Key presses in software keyboards will generally NOT trigger this listener, 7672 * although some may elect to do so in some situations. Do not rely on this to 7673 * catch software key presses. 7674 * 7675 * @param keyCode A key code that represents the button pressed, from 7676 * {@link android.view.KeyEvent}. 7677 * @param event The KeyEvent object that defines the button action. 7678 */ 7679 public boolean onKeyUp(int keyCode, KeyEvent event) { 7680 boolean result = false; 7681 7682 switch (keyCode) { 7683 case KeyEvent.KEYCODE_DPAD_CENTER: 7684 case KeyEvent.KEYCODE_ENTER: { 7685 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 7686 return true; 7687 } 7688 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 7689 setPressed(false); 7690 7691 if (!mHasPerformedLongPress) { 7692 // This is a tap, so remove the longpress check 7693 removeLongPressCallback(); 7694 7695 result = performClick(); 7696 } 7697 } 7698 break; 7699 } 7700 } 7701 return result; 7702 } 7703 7704 /** 7705 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 7706 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 7707 * the event). 7708 * <p>Key presses in software keyboards will generally NOT trigger this listener, 7709 * although some may elect to do so in some situations. Do not rely on this to 7710 * catch software key presses. 7711 * 7712 * @param keyCode A key code that represents the button pressed, from 7713 * {@link android.view.KeyEvent}. 7714 * @param repeatCount The number of times the action was made. 7715 * @param event The KeyEvent object that defines the button action. 7716 */ 7717 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 7718 return false; 7719 } 7720 7721 /** 7722 * Called on the focused view when a key shortcut event is not handled. 7723 * Override this method to implement local key shortcuts for the View. 7724 * Key shortcuts can also be implemented by setting the 7725 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 7726 * 7727 * @param keyCode The value in event.getKeyCode(). 7728 * @param event Description of the key event. 7729 * @return If you handled the event, return true. If you want to allow the 7730 * event to be handled by the next receiver, return false. 7731 */ 7732 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 7733 return false; 7734 } 7735 7736 /** 7737 * Check whether the called view is a text editor, in which case it 7738 * would make sense to automatically display a soft input window for 7739 * it. Subclasses should override this if they implement 7740 * {@link #onCreateInputConnection(EditorInfo)} to return true if 7741 * a call on that method would return a non-null InputConnection, and 7742 * they are really a first-class editor that the user would normally 7743 * start typing on when the go into a window containing your view. 7744 * 7745 * <p>The default implementation always returns false. This does 7746 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 7747 * will not be called or the user can not otherwise perform edits on your 7748 * view; it is just a hint to the system that this is not the primary 7749 * purpose of this view. 7750 * 7751 * @return Returns true if this view is a text editor, else false. 7752 */ 7753 public boolean onCheckIsTextEditor() { 7754 return false; 7755 } 7756 7757 /** 7758 * Create a new InputConnection for an InputMethod to interact 7759 * with the view. The default implementation returns null, since it doesn't 7760 * support input methods. You can override this to implement such support. 7761 * This is only needed for views that take focus and text input. 7762 * 7763 * <p>When implementing this, you probably also want to implement 7764 * {@link #onCheckIsTextEditor()} to indicate you will return a 7765 * non-null InputConnection. 7766 * 7767 * @param outAttrs Fill in with attribute information about the connection. 7768 */ 7769 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 7770 return null; 7771 } 7772 7773 /** 7774 * Called by the {@link android.view.inputmethod.InputMethodManager} 7775 * when a view who is not the current 7776 * input connection target is trying to make a call on the manager. The 7777 * default implementation returns false; you can override this to return 7778 * true for certain views if you are performing InputConnection proxying 7779 * to them. 7780 * @param view The View that is making the InputMethodManager call. 7781 * @return Return true to allow the call, false to reject. 7782 */ 7783 public boolean checkInputConnectionProxy(View view) { 7784 return false; 7785 } 7786 7787 /** 7788 * Show the context menu for this view. It is not safe to hold on to the 7789 * menu after returning from this method. 7790 * 7791 * You should normally not overload this method. Overload 7792 * {@link #onCreateContextMenu(ContextMenu)} or define an 7793 * {@link OnCreateContextMenuListener} to add items to the context menu. 7794 * 7795 * @param menu The context menu to populate 7796 */ 7797 public void createContextMenu(ContextMenu menu) { 7798 ContextMenuInfo menuInfo = getContextMenuInfo(); 7799 7800 // Sets the current menu info so all items added to menu will have 7801 // my extra info set. 7802 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 7803 7804 onCreateContextMenu(menu); 7805 ListenerInfo li = mListenerInfo; 7806 if (li != null && li.mOnCreateContextMenuListener != null) { 7807 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 7808 } 7809 7810 // Clear the extra information so subsequent items that aren't mine don't 7811 // have my extra info. 7812 ((MenuBuilder)menu).setCurrentMenuInfo(null); 7813 7814 if (mParent != null) { 7815 mParent.createContextMenu(menu); 7816 } 7817 } 7818 7819 /** 7820 * Views should implement this if they have extra information to associate 7821 * with the context menu. The return result is supplied as a parameter to 7822 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 7823 * callback. 7824 * 7825 * @return Extra information about the item for which the context menu 7826 * should be shown. This information will vary across different 7827 * subclasses of View. 7828 */ 7829 protected ContextMenuInfo getContextMenuInfo() { 7830 return null; 7831 } 7832 7833 /** 7834 * Views should implement this if the view itself is going to add items to 7835 * the context menu. 7836 * 7837 * @param menu the context menu to populate 7838 */ 7839 protected void onCreateContextMenu(ContextMenu menu) { 7840 } 7841 7842 /** 7843 * Implement this method to handle trackball motion events. The 7844 * <em>relative</em> movement of the trackball since the last event 7845 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 7846 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 7847 * that a movement of 1 corresponds to the user pressing one DPAD key (so 7848 * they will often be fractional values, representing the more fine-grained 7849 * movement information available from a trackball). 7850 * 7851 * @param event The motion event. 7852 * @return True if the event was handled, false otherwise. 7853 */ 7854 public boolean onTrackballEvent(MotionEvent event) { 7855 return false; 7856 } 7857 7858 /** 7859 * Implement this method to handle generic motion events. 7860 * <p> 7861 * Generic motion events describe joystick movements, mouse hovers, track pad 7862 * touches, scroll wheel movements and other input events. The 7863 * {@link MotionEvent#getSource() source} of the motion event specifies 7864 * the class of input that was received. Implementations of this method 7865 * must examine the bits in the source before processing the event. 7866 * The following code example shows how this is done. 7867 * </p><p> 7868 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 7869 * are delivered to the view under the pointer. All other generic motion events are 7870 * delivered to the focused view. 7871 * </p> 7872 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 7873 * if ((event.getSource() & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) { 7874 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 7875 * // process the joystick movement... 7876 * return true; 7877 * } 7878 * } 7879 * if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) { 7880 * switch (event.getAction()) { 7881 * case MotionEvent.ACTION_HOVER_MOVE: 7882 * // process the mouse hover movement... 7883 * return true; 7884 * case MotionEvent.ACTION_SCROLL: 7885 * // process the scroll wheel movement... 7886 * return true; 7887 * } 7888 * } 7889 * return super.onGenericMotionEvent(event); 7890 * }</pre> 7891 * 7892 * @param event The generic motion event being processed. 7893 * @return True if the event was handled, false otherwise. 7894 */ 7895 public boolean onGenericMotionEvent(MotionEvent event) { 7896 return false; 7897 } 7898 7899 /** 7900 * Implement this method to handle hover events. 7901 * <p> 7902 * This method is called whenever a pointer is hovering into, over, or out of the 7903 * bounds of a view and the view is not currently being touched. 7904 * Hover events are represented as pointer events with action 7905 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 7906 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 7907 * </p> 7908 * <ul> 7909 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 7910 * when the pointer enters the bounds of the view.</li> 7911 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 7912 * when the pointer has already entered the bounds of the view and has moved.</li> 7913 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 7914 * when the pointer has exited the bounds of the view or when the pointer is 7915 * about to go down due to a button click, tap, or similar user action that 7916 * causes the view to be touched.</li> 7917 * </ul> 7918 * <p> 7919 * The view should implement this method to return true to indicate that it is 7920 * handling the hover event, such as by changing its drawable state. 7921 * </p><p> 7922 * The default implementation calls {@link #setHovered} to update the hovered state 7923 * of the view when a hover enter or hover exit event is received, if the view 7924 * is enabled and is clickable. The default implementation also sends hover 7925 * accessibility events. 7926 * </p> 7927 * 7928 * @param event The motion event that describes the hover. 7929 * @return True if the view handled the hover event. 7930 * 7931 * @see #isHovered 7932 * @see #setHovered 7933 * @see #onHoverChanged 7934 */ 7935 public boolean onHoverEvent(MotionEvent event) { 7936 // The root view may receive hover (or touch) events that are outside the bounds of 7937 // the window. This code ensures that we only send accessibility events for 7938 // hovers that are actually within the bounds of the root view. 7939 final int action = event.getActionMasked(); 7940 if (!mSendingHoverAccessibilityEvents) { 7941 if ((action == MotionEvent.ACTION_HOVER_ENTER 7942 || action == MotionEvent.ACTION_HOVER_MOVE) 7943 && !hasHoveredChild() 7944 && pointInView(event.getX(), event.getY())) { 7945 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 7946 mSendingHoverAccessibilityEvents = true; 7947 } 7948 } else { 7949 if (action == MotionEvent.ACTION_HOVER_EXIT 7950 || (action == MotionEvent.ACTION_MOVE 7951 && !pointInView(event.getX(), event.getY()))) { 7952 mSendingHoverAccessibilityEvents = false; 7953 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 7954 // If the window does not have input focus we take away accessibility 7955 // focus as soon as the user stop hovering over the view. 7956 if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) { 7957 getViewRootImpl().setAccessibilityFocus(null, null); 7958 } 7959 } 7960 } 7961 7962 if (isHoverable()) { 7963 switch (action) { 7964 case MotionEvent.ACTION_HOVER_ENTER: 7965 setHovered(true); 7966 break; 7967 case MotionEvent.ACTION_HOVER_EXIT: 7968 setHovered(false); 7969 break; 7970 } 7971 7972 // Dispatch the event to onGenericMotionEvent before returning true. 7973 // This is to provide compatibility with existing applications that 7974 // handled HOVER_MOVE events in onGenericMotionEvent and that would 7975 // break because of the new default handling for hoverable views 7976 // in onHoverEvent. 7977 // Note that onGenericMotionEvent will be called by default when 7978 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 7979 dispatchGenericMotionEventInternal(event); 7980 return true; 7981 } 7982 7983 return false; 7984 } 7985 7986 /** 7987 * Returns true if the view should handle {@link #onHoverEvent} 7988 * by calling {@link #setHovered} to change its hovered state. 7989 * 7990 * @return True if the view is hoverable. 7991 */ 7992 private boolean isHoverable() { 7993 final int viewFlags = mViewFlags; 7994 if ((viewFlags & ENABLED_MASK) == DISABLED) { 7995 return false; 7996 } 7997 7998 return (viewFlags & CLICKABLE) == CLICKABLE 7999 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 8000 } 8001 8002 /** 8003 * Returns true if the view is currently hovered. 8004 * 8005 * @return True if the view is currently hovered. 8006 * 8007 * @see #setHovered 8008 * @see #onHoverChanged 8009 */ 8010 @ViewDebug.ExportedProperty 8011 public boolean isHovered() { 8012 return (mPrivateFlags & PFLAG_HOVERED) != 0; 8013 } 8014 8015 /** 8016 * Sets whether the view is currently hovered. 8017 * <p> 8018 * Calling this method also changes the drawable state of the view. This 8019 * enables the view to react to hover by using different drawable resources 8020 * to change its appearance. 8021 * </p><p> 8022 * The {@link #onHoverChanged} method is called when the hovered state changes. 8023 * </p> 8024 * 8025 * @param hovered True if the view is hovered. 8026 * 8027 * @see #isHovered 8028 * @see #onHoverChanged 8029 */ 8030 public void setHovered(boolean hovered) { 8031 if (hovered) { 8032 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 8033 mPrivateFlags |= PFLAG_HOVERED; 8034 refreshDrawableState(); 8035 onHoverChanged(true); 8036 } 8037 } else { 8038 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 8039 mPrivateFlags &= ~PFLAG_HOVERED; 8040 refreshDrawableState(); 8041 onHoverChanged(false); 8042 } 8043 } 8044 } 8045 8046 /** 8047 * Implement this method to handle hover state changes. 8048 * <p> 8049 * This method is called whenever the hover state changes as a result of a 8050 * call to {@link #setHovered}. 8051 * </p> 8052 * 8053 * @param hovered The current hover state, as returned by {@link #isHovered}. 8054 * 8055 * @see #isHovered 8056 * @see #setHovered 8057 */ 8058 public void onHoverChanged(boolean hovered) { 8059 } 8060 8061 /** 8062 * Implement this method to handle touch screen motion events. 8063 * 8064 * @param event The motion event. 8065 * @return True if the event was handled, false otherwise. 8066 */ 8067 public boolean onTouchEvent(MotionEvent event) { 8068 final int viewFlags = mViewFlags; 8069 8070 if ((viewFlags & ENABLED_MASK) == DISABLED) { 8071 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 8072 setPressed(false); 8073 } 8074 // A disabled view that is clickable still consumes the touch 8075 // events, it just doesn't respond to them. 8076 return (((viewFlags & CLICKABLE) == CLICKABLE || 8077 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 8078 } 8079 8080 if (mTouchDelegate != null) { 8081 if (mTouchDelegate.onTouchEvent(event)) { 8082 return true; 8083 } 8084 } 8085 8086 if (((viewFlags & CLICKABLE) == CLICKABLE || 8087 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 8088 switch (event.getAction()) { 8089 case MotionEvent.ACTION_UP: 8090 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 8091 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 8092 // take focus if we don't have it already and we should in 8093 // touch mode. 8094 boolean focusTaken = false; 8095 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 8096 focusTaken = requestFocus(); 8097 } 8098 8099 if (prepressed) { 8100 // The button is being released before we actually 8101 // showed it as pressed. Make it show the pressed 8102 // state now (before scheduling the click) to ensure 8103 // the user sees it. 8104 setPressed(true); 8105 } 8106 8107 if (!mHasPerformedLongPress) { 8108 // This is a tap, so remove the longpress check 8109 removeLongPressCallback(); 8110 8111 // Only perform take click actions if we were in the pressed state 8112 if (!focusTaken) { 8113 // Use a Runnable and post this rather than calling 8114 // performClick directly. This lets other visual state 8115 // of the view update before click actions start. 8116 if (mPerformClick == null) { 8117 mPerformClick = new PerformClick(); 8118 } 8119 if (!post(mPerformClick)) { 8120 performClick(); 8121 } 8122 } 8123 } 8124 8125 if (mUnsetPressedState == null) { 8126 mUnsetPressedState = new UnsetPressedState(); 8127 } 8128 8129 if (prepressed) { 8130 postDelayed(mUnsetPressedState, 8131 ViewConfiguration.getPressedStateDuration()); 8132 } else if (!post(mUnsetPressedState)) { 8133 // If the post failed, unpress right now 8134 mUnsetPressedState.run(); 8135 } 8136 removeTapCallback(); 8137 } 8138 break; 8139 8140 case MotionEvent.ACTION_DOWN: 8141 mHasPerformedLongPress = false; 8142 8143 if (performButtonActionOnTouchDown(event)) { 8144 break; 8145 } 8146 8147 // Walk up the hierarchy to determine if we're inside a scrolling container. 8148 boolean isInScrollingContainer = isInScrollingContainer(); 8149 8150 // For views inside a scrolling container, delay the pressed feedback for 8151 // a short period in case this is a scroll. 8152 if (isInScrollingContainer) { 8153 mPrivateFlags |= PFLAG_PREPRESSED; 8154 if (mPendingCheckForTap == null) { 8155 mPendingCheckForTap = new CheckForTap(); 8156 } 8157 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 8158 } else { 8159 // Not inside a scrolling container, so show the feedback right away 8160 setPressed(true); 8161 checkForLongClick(0); 8162 } 8163 break; 8164 8165 case MotionEvent.ACTION_CANCEL: 8166 setPressed(false); 8167 removeTapCallback(); 8168 break; 8169 8170 case MotionEvent.ACTION_MOVE: 8171 final int x = (int) event.getX(); 8172 final int y = (int) event.getY(); 8173 8174 // Be lenient about moving outside of buttons 8175 if (!pointInView(x, y, mTouchSlop)) { 8176 // Outside button 8177 removeTapCallback(); 8178 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 8179 // Remove any future long press/tap checks 8180 removeLongPressCallback(); 8181 8182 setPressed(false); 8183 } 8184 } 8185 break; 8186 } 8187 return true; 8188 } 8189 8190 return false; 8191 } 8192 8193 /** 8194 * @hide 8195 */ 8196 public boolean isInScrollingContainer() { 8197 ViewParent p = getParent(); 8198 while (p != null && p instanceof ViewGroup) { 8199 if (((ViewGroup) p).shouldDelayChildPressedState()) { 8200 return true; 8201 } 8202 p = p.getParent(); 8203 } 8204 return false; 8205 } 8206 8207 /** 8208 * Remove the longpress detection timer. 8209 */ 8210 private void removeLongPressCallback() { 8211 if (mPendingCheckForLongPress != null) { 8212 removeCallbacks(mPendingCheckForLongPress); 8213 } 8214 } 8215 8216 /** 8217 * Remove the pending click action 8218 */ 8219 private void removePerformClickCallback() { 8220 if (mPerformClick != null) { 8221 removeCallbacks(mPerformClick); 8222 } 8223 } 8224 8225 /** 8226 * Remove the prepress detection timer. 8227 */ 8228 private void removeUnsetPressCallback() { 8229 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 8230 setPressed(false); 8231 removeCallbacks(mUnsetPressedState); 8232 } 8233 } 8234 8235 /** 8236 * Remove the tap detection timer. 8237 */ 8238 private void removeTapCallback() { 8239 if (mPendingCheckForTap != null) { 8240 mPrivateFlags &= ~PFLAG_PREPRESSED; 8241 removeCallbacks(mPendingCheckForTap); 8242 } 8243 } 8244 8245 /** 8246 * Cancels a pending long press. Your subclass can use this if you 8247 * want the context menu to come up if the user presses and holds 8248 * at the same place, but you don't want it to come up if they press 8249 * and then move around enough to cause scrolling. 8250 */ 8251 public void cancelLongPress() { 8252 removeLongPressCallback(); 8253 8254 /* 8255 * The prepressed state handled by the tap callback is a display 8256 * construct, but the tap callback will post a long press callback 8257 * less its own timeout. Remove it here. 8258 */ 8259 removeTapCallback(); 8260 } 8261 8262 /** 8263 * Remove the pending callback for sending a 8264 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 8265 */ 8266 private void removeSendViewScrolledAccessibilityEventCallback() { 8267 if (mSendViewScrolledAccessibilityEvent != null) { 8268 removeCallbacks(mSendViewScrolledAccessibilityEvent); 8269 mSendViewScrolledAccessibilityEvent.mIsPending = false; 8270 } 8271 } 8272 8273 /** 8274 * Sets the TouchDelegate for this View. 8275 */ 8276 public void setTouchDelegate(TouchDelegate delegate) { 8277 mTouchDelegate = delegate; 8278 } 8279 8280 /** 8281 * Gets the TouchDelegate for this View. 8282 */ 8283 public TouchDelegate getTouchDelegate() { 8284 return mTouchDelegate; 8285 } 8286 8287 /** 8288 * Set flags controlling behavior of this view. 8289 * 8290 * @param flags Constant indicating the value which should be set 8291 * @param mask Constant indicating the bit range that should be changed 8292 */ 8293 void setFlags(int flags, int mask) { 8294 int old = mViewFlags; 8295 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 8296 8297 int changed = mViewFlags ^ old; 8298 if (changed == 0) { 8299 return; 8300 } 8301 int privateFlags = mPrivateFlags; 8302 8303 /* Check if the FOCUSABLE bit has changed */ 8304 if (((changed & FOCUSABLE_MASK) != 0) && 8305 ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) { 8306 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 8307 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 8308 /* Give up focus if we are no longer focusable */ 8309 clearFocus(); 8310 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 8311 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 8312 /* 8313 * Tell the view system that we are now available to take focus 8314 * if no one else already has it. 8315 */ 8316 if (mParent != null) mParent.focusableViewAvailable(this); 8317 } 8318 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 8319 notifyAccessibilityStateChanged(); 8320 } 8321 } 8322 8323 if ((flags & VISIBILITY_MASK) == VISIBLE) { 8324 if ((changed & VISIBILITY_MASK) != 0) { 8325 /* 8326 * If this view is becoming visible, invalidate it in case it changed while 8327 * it was not visible. Marking it drawn ensures that the invalidation will 8328 * go through. 8329 */ 8330 mPrivateFlags |= PFLAG_DRAWN; 8331 invalidate(true); 8332 8333 needGlobalAttributesUpdate(true); 8334 8335 // a view becoming visible is worth notifying the parent 8336 // about in case nothing has focus. even if this specific view 8337 // isn't focusable, it may contain something that is, so let 8338 // the root view try to give this focus if nothing else does. 8339 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 8340 mParent.focusableViewAvailable(this); 8341 } 8342 } 8343 } 8344 8345 /* Check if the GONE bit has changed */ 8346 if ((changed & GONE) != 0) { 8347 needGlobalAttributesUpdate(false); 8348 requestLayout(); 8349 8350 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 8351 if (hasFocus()) clearFocus(); 8352 clearAccessibilityFocus(); 8353 destroyDrawingCache(); 8354 if (mParent instanceof View) { 8355 // GONE views noop invalidation, so invalidate the parent 8356 ((View) mParent).invalidate(true); 8357 } 8358 // Mark the view drawn to ensure that it gets invalidated properly the next 8359 // time it is visible and gets invalidated 8360 mPrivateFlags |= PFLAG_DRAWN; 8361 } 8362 if (mAttachInfo != null) { 8363 mAttachInfo.mViewVisibilityChanged = true; 8364 } 8365 } 8366 8367 /* Check if the VISIBLE bit has changed */ 8368 if ((changed & INVISIBLE) != 0) { 8369 needGlobalAttributesUpdate(false); 8370 /* 8371 * If this view is becoming invisible, set the DRAWN flag so that 8372 * the next invalidate() will not be skipped. 8373 */ 8374 mPrivateFlags |= PFLAG_DRAWN; 8375 8376 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) { 8377 // root view becoming invisible shouldn't clear focus and accessibility focus 8378 if (getRootView() != this) { 8379 clearFocus(); 8380 clearAccessibilityFocus(); 8381 } 8382 } 8383 if (mAttachInfo != null) { 8384 mAttachInfo.mViewVisibilityChanged = true; 8385 } 8386 } 8387 8388 if ((changed & VISIBILITY_MASK) != 0) { 8389 if (mParent instanceof ViewGroup) { 8390 ((ViewGroup) mParent).onChildVisibilityChanged(this, 8391 (changed & VISIBILITY_MASK), (flags & VISIBILITY_MASK)); 8392 ((View) mParent).invalidate(true); 8393 } else if (mParent != null) { 8394 mParent.invalidateChild(this, null); 8395 } 8396 dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK)); 8397 } 8398 8399 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 8400 destroyDrawingCache(); 8401 } 8402 8403 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 8404 destroyDrawingCache(); 8405 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 8406 invalidateParentCaches(); 8407 } 8408 8409 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 8410 destroyDrawingCache(); 8411 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 8412 } 8413 8414 if ((changed & DRAW_MASK) != 0) { 8415 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 8416 if (mBackground != null) { 8417 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 8418 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 8419 } else { 8420 mPrivateFlags |= PFLAG_SKIP_DRAW; 8421 } 8422 } else { 8423 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 8424 } 8425 requestLayout(); 8426 invalidate(true); 8427 } 8428 8429 if ((changed & KEEP_SCREEN_ON) != 0) { 8430 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 8431 mParent.recomputeViewAttributes(this); 8432 } 8433 } 8434 8435 if (AccessibilityManager.getInstance(mContext).isEnabled() 8436 && ((changed & FOCUSABLE) != 0 || (changed & CLICKABLE) != 0 8437 || (changed & LONG_CLICKABLE) != 0 || (changed & ENABLED) != 0)) { 8438 notifyAccessibilityStateChanged(); 8439 } 8440 } 8441 8442 /** 8443 * Change the view's z order in the tree, so it's on top of other sibling 8444 * views 8445 */ 8446 public void bringToFront() { 8447 if (mParent != null) { 8448 mParent.bringChildToFront(this); 8449 } 8450 } 8451 8452 /** 8453 * This is called in response to an internal scroll in this view (i.e., the 8454 * view scrolled its own contents). This is typically as a result of 8455 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 8456 * called. 8457 * 8458 * @param l Current horizontal scroll origin. 8459 * @param t Current vertical scroll origin. 8460 * @param oldl Previous horizontal scroll origin. 8461 * @param oldt Previous vertical scroll origin. 8462 */ 8463 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 8464 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 8465 postSendViewScrolledAccessibilityEventCallback(); 8466 } 8467 8468 mBackgroundSizeChanged = true; 8469 8470 final AttachInfo ai = mAttachInfo; 8471 if (ai != null) { 8472 ai.mViewScrollChanged = true; 8473 } 8474 } 8475 8476 /** 8477 * Interface definition for a callback to be invoked when the layout bounds of a view 8478 * changes due to layout processing. 8479 */ 8480 public interface OnLayoutChangeListener { 8481 /** 8482 * Called when the focus state of a view has changed. 8483 * 8484 * @param v The view whose state has changed. 8485 * @param left The new value of the view's left property. 8486 * @param top The new value of the view's top property. 8487 * @param right The new value of the view's right property. 8488 * @param bottom The new value of the view's bottom property. 8489 * @param oldLeft The previous value of the view's left property. 8490 * @param oldTop The previous value of the view's top property. 8491 * @param oldRight The previous value of the view's right property. 8492 * @param oldBottom The previous value of the view's bottom property. 8493 */ 8494 void onLayoutChange(View v, int left, int top, int right, int bottom, 8495 int oldLeft, int oldTop, int oldRight, int oldBottom); 8496 } 8497 8498 /** 8499 * This is called during layout when the size of this view has changed. If 8500 * you were just added to the view hierarchy, you're called with the old 8501 * values of 0. 8502 * 8503 * @param w Current width of this view. 8504 * @param h Current height of this view. 8505 * @param oldw Old width of this view. 8506 * @param oldh Old height of this view. 8507 */ 8508 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 8509 } 8510 8511 /** 8512 * Called by draw to draw the child views. This may be overridden 8513 * by derived classes to gain control just before its children are drawn 8514 * (but after its own view has been drawn). 8515 * @param canvas the canvas on which to draw the view 8516 */ 8517 protected void dispatchDraw(Canvas canvas) { 8518 8519 } 8520 8521 /** 8522 * Gets the parent of this view. Note that the parent is a 8523 * ViewParent and not necessarily a View. 8524 * 8525 * @return Parent of this view. 8526 */ 8527 public final ViewParent getParent() { 8528 return mParent; 8529 } 8530 8531 /** 8532 * Set the horizontal scrolled position of your view. This will cause a call to 8533 * {@link #onScrollChanged(int, int, int, int)} and the view will be 8534 * invalidated. 8535 * @param value the x position to scroll to 8536 */ 8537 public void setScrollX(int value) { 8538 scrollTo(value, mScrollY); 8539 } 8540 8541 /** 8542 * Set the vertical scrolled position of your view. This will cause a call to 8543 * {@link #onScrollChanged(int, int, int, int)} and the view will be 8544 * invalidated. 8545 * @param value the y position to scroll to 8546 */ 8547 public void setScrollY(int value) { 8548 scrollTo(mScrollX, value); 8549 } 8550 8551 /** 8552 * Return the scrolled left position of this view. This is the left edge of 8553 * the displayed part of your view. You do not need to draw any pixels 8554 * farther left, since those are outside of the frame of your view on 8555 * screen. 8556 * 8557 * @return The left edge of the displayed part of your view, in pixels. 8558 */ 8559 public final int getScrollX() { 8560 return mScrollX; 8561 } 8562 8563 /** 8564 * Return the scrolled top position of this view. This is the top edge of 8565 * the displayed part of your view. You do not need to draw any pixels above 8566 * it, since those are outside of the frame of your view on screen. 8567 * 8568 * @return The top edge of the displayed part of your view, in pixels. 8569 */ 8570 public final int getScrollY() { 8571 return mScrollY; 8572 } 8573 8574 /** 8575 * Return the width of the your view. 8576 * 8577 * @return The width of your view, in pixels. 8578 */ 8579 @ViewDebug.ExportedProperty(category = "layout") 8580 public final int getWidth() { 8581 return mRight - mLeft; 8582 } 8583 8584 /** 8585 * Return the height of your view. 8586 * 8587 * @return The height of your view, in pixels. 8588 */ 8589 @ViewDebug.ExportedProperty(category = "layout") 8590 public final int getHeight() { 8591 return mBottom - mTop; 8592 } 8593 8594 /** 8595 * Return the visible drawing bounds of your view. Fills in the output 8596 * rectangle with the values from getScrollX(), getScrollY(), 8597 * getWidth(), and getHeight(). 8598 * 8599 * @param outRect The (scrolled) drawing bounds of the view. 8600 */ 8601 public void getDrawingRect(Rect outRect) { 8602 outRect.left = mScrollX; 8603 outRect.top = mScrollY; 8604 outRect.right = mScrollX + (mRight - mLeft); 8605 outRect.bottom = mScrollY + (mBottom - mTop); 8606 } 8607 8608 /** 8609 * Like {@link #getMeasuredWidthAndState()}, but only returns the 8610 * raw width component (that is the result is masked by 8611 * {@link #MEASURED_SIZE_MASK}). 8612 * 8613 * @return The raw measured width of this view. 8614 */ 8615 public final int getMeasuredWidth() { 8616 return mMeasuredWidth & MEASURED_SIZE_MASK; 8617 } 8618 8619 /** 8620 * Return the full width measurement information for this view as computed 8621 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 8622 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 8623 * This should be used during measurement and layout calculations only. Use 8624 * {@link #getWidth()} to see how wide a view is after layout. 8625 * 8626 * @return The measured width of this view as a bit mask. 8627 */ 8628 public final int getMeasuredWidthAndState() { 8629 return mMeasuredWidth; 8630 } 8631 8632 /** 8633 * Like {@link #getMeasuredHeightAndState()}, but only returns the 8634 * raw width component (that is the result is masked by 8635 * {@link #MEASURED_SIZE_MASK}). 8636 * 8637 * @return The raw measured height of this view. 8638 */ 8639 public final int getMeasuredHeight() { 8640 return mMeasuredHeight & MEASURED_SIZE_MASK; 8641 } 8642 8643 /** 8644 * Return the full height measurement information for this view as computed 8645 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 8646 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 8647 * This should be used during measurement and layout calculations only. Use 8648 * {@link #getHeight()} to see how wide a view is after layout. 8649 * 8650 * @return The measured width of this view as a bit mask. 8651 */ 8652 public final int getMeasuredHeightAndState() { 8653 return mMeasuredHeight; 8654 } 8655 8656 /** 8657 * Return only the state bits of {@link #getMeasuredWidthAndState()} 8658 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 8659 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 8660 * and the height component is at the shifted bits 8661 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 8662 */ 8663 public final int getMeasuredState() { 8664 return (mMeasuredWidth&MEASURED_STATE_MASK) 8665 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 8666 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 8667 } 8668 8669 /** 8670 * The transform matrix of this view, which is calculated based on the current 8671 * roation, scale, and pivot properties. 8672 * 8673 * @see #getRotation() 8674 * @see #getScaleX() 8675 * @see #getScaleY() 8676 * @see #getPivotX() 8677 * @see #getPivotY() 8678 * @return The current transform matrix for the view 8679 */ 8680 public Matrix getMatrix() { 8681 if (mTransformationInfo != null) { 8682 updateMatrix(); 8683 return mTransformationInfo.mMatrix; 8684 } 8685 return Matrix.IDENTITY_MATRIX; 8686 } 8687 8688 /** 8689 * Utility function to determine if the value is far enough away from zero to be 8690 * considered non-zero. 8691 * @param value A floating point value to check for zero-ness 8692 * @return whether the passed-in value is far enough away from zero to be considered non-zero 8693 */ 8694 private static boolean nonzero(float value) { 8695 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON); 8696 } 8697 8698 /** 8699 * Returns true if the transform matrix is the identity matrix. 8700 * Recomputes the matrix if necessary. 8701 * 8702 * @return True if the transform matrix is the identity matrix, false otherwise. 8703 */ 8704 final boolean hasIdentityMatrix() { 8705 if (mTransformationInfo != null) { 8706 updateMatrix(); 8707 return mTransformationInfo.mMatrixIsIdentity; 8708 } 8709 return true; 8710 } 8711 8712 void ensureTransformationInfo() { 8713 if (mTransformationInfo == null) { 8714 mTransformationInfo = new TransformationInfo(); 8715 } 8716 } 8717 8718 /** 8719 * Recomputes the transform matrix if necessary. 8720 */ 8721 private void updateMatrix() { 8722 final TransformationInfo info = mTransformationInfo; 8723 if (info == null) { 8724 return; 8725 } 8726 if (info.mMatrixDirty) { 8727 // transform-related properties have changed since the last time someone 8728 // asked for the matrix; recalculate it with the current values 8729 8730 // Figure out if we need to update the pivot point 8731 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 8732 if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) { 8733 info.mPrevWidth = mRight - mLeft; 8734 info.mPrevHeight = mBottom - mTop; 8735 info.mPivotX = info.mPrevWidth / 2f; 8736 info.mPivotY = info.mPrevHeight / 2f; 8737 } 8738 } 8739 info.mMatrix.reset(); 8740 if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) { 8741 info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY); 8742 info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY); 8743 info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY); 8744 } else { 8745 if (info.mCamera == null) { 8746 info.mCamera = new Camera(); 8747 info.matrix3D = new Matrix(); 8748 } 8749 info.mCamera.save(); 8750 info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY); 8751 info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation); 8752 info.mCamera.getMatrix(info.matrix3D); 8753 info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY); 8754 info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX, 8755 info.mPivotY + info.mTranslationY); 8756 info.mMatrix.postConcat(info.matrix3D); 8757 info.mCamera.restore(); 8758 } 8759 info.mMatrixDirty = false; 8760 info.mMatrixIsIdentity = info.mMatrix.isIdentity(); 8761 info.mInverseMatrixDirty = true; 8762 } 8763 } 8764 8765 /** 8766 * Utility method to retrieve the inverse of the current mMatrix property. 8767 * We cache the matrix to avoid recalculating it when transform properties 8768 * have not changed. 8769 * 8770 * @return The inverse of the current matrix of this view. 8771 */ 8772 final Matrix getInverseMatrix() { 8773 final TransformationInfo info = mTransformationInfo; 8774 if (info != null) { 8775 updateMatrix(); 8776 if (info.mInverseMatrixDirty) { 8777 if (info.mInverseMatrix == null) { 8778 info.mInverseMatrix = new Matrix(); 8779 } 8780 info.mMatrix.invert(info.mInverseMatrix); 8781 info.mInverseMatrixDirty = false; 8782 } 8783 return info.mInverseMatrix; 8784 } 8785 return Matrix.IDENTITY_MATRIX; 8786 } 8787 8788 /** 8789 * Gets the distance along the Z axis from the camera to this view. 8790 * 8791 * @see #setCameraDistance(float) 8792 * 8793 * @return The distance along the Z axis. 8794 */ 8795 public float getCameraDistance() { 8796 ensureTransformationInfo(); 8797 final float dpi = mResources.getDisplayMetrics().densityDpi; 8798 final TransformationInfo info = mTransformationInfo; 8799 if (info.mCamera == null) { 8800 info.mCamera = new Camera(); 8801 info.matrix3D = new Matrix(); 8802 } 8803 return -(info.mCamera.getLocationZ() * dpi); 8804 } 8805 8806 /** 8807 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 8808 * views are drawn) from the camera to this view. The camera's distance 8809 * affects 3D transformations, for instance rotations around the X and Y 8810 * axis. If the rotationX or rotationY properties are changed and this view is 8811 * large (more than half the size of the screen), it is recommended to always 8812 * use a camera distance that's greater than the height (X axis rotation) or 8813 * the width (Y axis rotation) of this view.</p> 8814 * 8815 * <p>The distance of the camera from the view plane can have an affect on the 8816 * perspective distortion of the view when it is rotated around the x or y axis. 8817 * For example, a large distance will result in a large viewing angle, and there 8818 * will not be much perspective distortion of the view as it rotates. A short 8819 * distance may cause much more perspective distortion upon rotation, and can 8820 * also result in some drawing artifacts if the rotated view ends up partially 8821 * behind the camera (which is why the recommendation is to use a distance at 8822 * least as far as the size of the view, if the view is to be rotated.)</p> 8823 * 8824 * <p>The distance is expressed in "depth pixels." The default distance depends 8825 * on the screen density. For instance, on a medium density display, the 8826 * default distance is 1280. On a high density display, the default distance 8827 * is 1920.</p> 8828 * 8829 * <p>If you want to specify a distance that leads to visually consistent 8830 * results across various densities, use the following formula:</p> 8831 * <pre> 8832 * float scale = context.getResources().getDisplayMetrics().density; 8833 * view.setCameraDistance(distance * scale); 8834 * </pre> 8835 * 8836 * <p>The density scale factor of a high density display is 1.5, 8837 * and 1920 = 1280 * 1.5.</p> 8838 * 8839 * @param distance The distance in "depth pixels", if negative the opposite 8840 * value is used 8841 * 8842 * @see #setRotationX(float) 8843 * @see #setRotationY(float) 8844 */ 8845 public void setCameraDistance(float distance) { 8846 invalidateViewProperty(true, false); 8847 8848 ensureTransformationInfo(); 8849 final float dpi = mResources.getDisplayMetrics().densityDpi; 8850 final TransformationInfo info = mTransformationInfo; 8851 if (info.mCamera == null) { 8852 info.mCamera = new Camera(); 8853 info.matrix3D = new Matrix(); 8854 } 8855 8856 info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi); 8857 info.mMatrixDirty = true; 8858 8859 invalidateViewProperty(false, false); 8860 if (mDisplayList != null) { 8861 mDisplayList.setCameraDistance(-Math.abs(distance) / dpi); 8862 } 8863 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 8864 // View was rejected last time it was drawn by its parent; this may have changed 8865 invalidateParentIfNeeded(); 8866 } 8867 } 8868 8869 /** 8870 * The degrees that the view is rotated around the pivot point. 8871 * 8872 * @see #setRotation(float) 8873 * @see #getPivotX() 8874 * @see #getPivotY() 8875 * 8876 * @return The degrees of rotation. 8877 */ 8878 @ViewDebug.ExportedProperty(category = "drawing") 8879 public float getRotation() { 8880 return mTransformationInfo != null ? mTransformationInfo.mRotation : 0; 8881 } 8882 8883 /** 8884 * Sets the degrees that the view is rotated around the pivot point. Increasing values 8885 * result in clockwise rotation. 8886 * 8887 * @param rotation The degrees of rotation. 8888 * 8889 * @see #getRotation() 8890 * @see #getPivotX() 8891 * @see #getPivotY() 8892 * @see #setRotationX(float) 8893 * @see #setRotationY(float) 8894 * 8895 * @attr ref android.R.styleable#View_rotation 8896 */ 8897 public void setRotation(float rotation) { 8898 ensureTransformationInfo(); 8899 final TransformationInfo info = mTransformationInfo; 8900 if (info.mRotation != rotation) { 8901 // Double-invalidation is necessary to capture view's old and new areas 8902 invalidateViewProperty(true, false); 8903 info.mRotation = rotation; 8904 info.mMatrixDirty = true; 8905 invalidateViewProperty(false, true); 8906 if (mDisplayList != null) { 8907 mDisplayList.setRotation(rotation); 8908 } 8909 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 8910 // View was rejected last time it was drawn by its parent; this may have changed 8911 invalidateParentIfNeeded(); 8912 } 8913 } 8914 } 8915 8916 /** 8917 * The degrees that the view is rotated around the vertical axis through the pivot point. 8918 * 8919 * @see #getPivotX() 8920 * @see #getPivotY() 8921 * @see #setRotationY(float) 8922 * 8923 * @return The degrees of Y rotation. 8924 */ 8925 @ViewDebug.ExportedProperty(category = "drawing") 8926 public float getRotationY() { 8927 return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0; 8928 } 8929 8930 /** 8931 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 8932 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 8933 * down the y axis. 8934 * 8935 * When rotating large views, it is recommended to adjust the camera distance 8936 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 8937 * 8938 * @param rotationY The degrees of Y rotation. 8939 * 8940 * @see #getRotationY() 8941 * @see #getPivotX() 8942 * @see #getPivotY() 8943 * @see #setRotation(float) 8944 * @see #setRotationX(float) 8945 * @see #setCameraDistance(float) 8946 * 8947 * @attr ref android.R.styleable#View_rotationY 8948 */ 8949 public void setRotationY(float rotationY) { 8950 ensureTransformationInfo(); 8951 final TransformationInfo info = mTransformationInfo; 8952 if (info.mRotationY != rotationY) { 8953 invalidateViewProperty(true, false); 8954 info.mRotationY = rotationY; 8955 info.mMatrixDirty = true; 8956 invalidateViewProperty(false, true); 8957 if (mDisplayList != null) { 8958 mDisplayList.setRotationY(rotationY); 8959 } 8960 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 8961 // View was rejected last time it was drawn by its parent; this may have changed 8962 invalidateParentIfNeeded(); 8963 } 8964 } 8965 } 8966 8967 /** 8968 * The degrees that the view is rotated around the horizontal axis through the pivot point. 8969 * 8970 * @see #getPivotX() 8971 * @see #getPivotY() 8972 * @see #setRotationX(float) 8973 * 8974 * @return The degrees of X rotation. 8975 */ 8976 @ViewDebug.ExportedProperty(category = "drawing") 8977 public float getRotationX() { 8978 return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0; 8979 } 8980 8981 /** 8982 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 8983 * Increasing values result in clockwise rotation from the viewpoint of looking down the 8984 * x axis. 8985 * 8986 * When rotating large views, it is recommended to adjust the camera distance 8987 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 8988 * 8989 * @param rotationX The degrees of X rotation. 8990 * 8991 * @see #getRotationX() 8992 * @see #getPivotX() 8993 * @see #getPivotY() 8994 * @see #setRotation(float) 8995 * @see #setRotationY(float) 8996 * @see #setCameraDistance(float) 8997 * 8998 * @attr ref android.R.styleable#View_rotationX 8999 */ 9000 public void setRotationX(float rotationX) { 9001 ensureTransformationInfo(); 9002 final TransformationInfo info = mTransformationInfo; 9003 if (info.mRotationX != rotationX) { 9004 invalidateViewProperty(true, false); 9005 info.mRotationX = rotationX; 9006 info.mMatrixDirty = true; 9007 invalidateViewProperty(false, true); 9008 if (mDisplayList != null) { 9009 mDisplayList.setRotationX(rotationX); 9010 } 9011 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9012 // View was rejected last time it was drawn by its parent; this may have changed 9013 invalidateParentIfNeeded(); 9014 } 9015 } 9016 } 9017 9018 /** 9019 * The amount that the view is scaled in x around the pivot point, as a proportion of 9020 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 9021 * 9022 * <p>By default, this is 1.0f. 9023 * 9024 * @see #getPivotX() 9025 * @see #getPivotY() 9026 * @return The scaling factor. 9027 */ 9028 @ViewDebug.ExportedProperty(category = "drawing") 9029 public float getScaleX() { 9030 return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1; 9031 } 9032 9033 /** 9034 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 9035 * the view's unscaled width. A value of 1 means that no scaling is applied. 9036 * 9037 * @param scaleX The scaling factor. 9038 * @see #getPivotX() 9039 * @see #getPivotY() 9040 * 9041 * @attr ref android.R.styleable#View_scaleX 9042 */ 9043 public void setScaleX(float scaleX) { 9044 ensureTransformationInfo(); 9045 final TransformationInfo info = mTransformationInfo; 9046 if (info.mScaleX != scaleX) { 9047 invalidateViewProperty(true, false); 9048 info.mScaleX = scaleX; 9049 info.mMatrixDirty = true; 9050 invalidateViewProperty(false, true); 9051 if (mDisplayList != null) { 9052 mDisplayList.setScaleX(scaleX); 9053 } 9054 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9055 // View was rejected last time it was drawn by its parent; this may have changed 9056 invalidateParentIfNeeded(); 9057 } 9058 } 9059 } 9060 9061 /** 9062 * The amount that the view is scaled in y around the pivot point, as a proportion of 9063 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 9064 * 9065 * <p>By default, this is 1.0f. 9066 * 9067 * @see #getPivotX() 9068 * @see #getPivotY() 9069 * @return The scaling factor. 9070 */ 9071 @ViewDebug.ExportedProperty(category = "drawing") 9072 public float getScaleY() { 9073 return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1; 9074 } 9075 9076 /** 9077 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 9078 * the view's unscaled width. A value of 1 means that no scaling is applied. 9079 * 9080 * @param scaleY The scaling factor. 9081 * @see #getPivotX() 9082 * @see #getPivotY() 9083 * 9084 * @attr ref android.R.styleable#View_scaleY 9085 */ 9086 public void setScaleY(float scaleY) { 9087 ensureTransformationInfo(); 9088 final TransformationInfo info = mTransformationInfo; 9089 if (info.mScaleY != scaleY) { 9090 invalidateViewProperty(true, false); 9091 info.mScaleY = scaleY; 9092 info.mMatrixDirty = true; 9093 invalidateViewProperty(false, true); 9094 if (mDisplayList != null) { 9095 mDisplayList.setScaleY(scaleY); 9096 } 9097 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9098 // View was rejected last time it was drawn by its parent; this may have changed 9099 invalidateParentIfNeeded(); 9100 } 9101 } 9102 } 9103 9104 /** 9105 * The x location of the point around which the view is {@link #setRotation(float) rotated} 9106 * and {@link #setScaleX(float) scaled}. 9107 * 9108 * @see #getRotation() 9109 * @see #getScaleX() 9110 * @see #getScaleY() 9111 * @see #getPivotY() 9112 * @return The x location of the pivot point. 9113 * 9114 * @attr ref android.R.styleable#View_transformPivotX 9115 */ 9116 @ViewDebug.ExportedProperty(category = "drawing") 9117 public float getPivotX() { 9118 return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0; 9119 } 9120 9121 /** 9122 * Sets the x location of the point around which the view is 9123 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 9124 * By default, the pivot point is centered on the object. 9125 * Setting this property disables this behavior and causes the view to use only the 9126 * explicitly set pivotX and pivotY values. 9127 * 9128 * @param pivotX The x location of the pivot point. 9129 * @see #getRotation() 9130 * @see #getScaleX() 9131 * @see #getScaleY() 9132 * @see #getPivotY() 9133 * 9134 * @attr ref android.R.styleable#View_transformPivotX 9135 */ 9136 public void setPivotX(float pivotX) { 9137 ensureTransformationInfo(); 9138 mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET; 9139 final TransformationInfo info = mTransformationInfo; 9140 if (info.mPivotX != pivotX) { 9141 invalidateViewProperty(true, false); 9142 info.mPivotX = pivotX; 9143 info.mMatrixDirty = true; 9144 invalidateViewProperty(false, true); 9145 if (mDisplayList != null) { 9146 mDisplayList.setPivotX(pivotX); 9147 } 9148 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9149 // View was rejected last time it was drawn by its parent; this may have changed 9150 invalidateParentIfNeeded(); 9151 } 9152 } 9153 } 9154 9155 /** 9156 * The y location of the point around which the view is {@link #setRotation(float) rotated} 9157 * and {@link #setScaleY(float) scaled}. 9158 * 9159 * @see #getRotation() 9160 * @see #getScaleX() 9161 * @see #getScaleY() 9162 * @see #getPivotY() 9163 * @return The y location of the pivot point. 9164 * 9165 * @attr ref android.R.styleable#View_transformPivotY 9166 */ 9167 @ViewDebug.ExportedProperty(category = "drawing") 9168 public float getPivotY() { 9169 return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0; 9170 } 9171 9172 /** 9173 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 9174 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 9175 * Setting this property disables this behavior and causes the view to use only the 9176 * explicitly set pivotX and pivotY values. 9177 * 9178 * @param pivotY The y location of the pivot point. 9179 * @see #getRotation() 9180 * @see #getScaleX() 9181 * @see #getScaleY() 9182 * @see #getPivotY() 9183 * 9184 * @attr ref android.R.styleable#View_transformPivotY 9185 */ 9186 public void setPivotY(float pivotY) { 9187 ensureTransformationInfo(); 9188 mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET; 9189 final TransformationInfo info = mTransformationInfo; 9190 if (info.mPivotY != pivotY) { 9191 invalidateViewProperty(true, false); 9192 info.mPivotY = pivotY; 9193 info.mMatrixDirty = true; 9194 invalidateViewProperty(false, true); 9195 if (mDisplayList != null) { 9196 mDisplayList.setPivotY(pivotY); 9197 } 9198 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9199 // View was rejected last time it was drawn by its parent; this may have changed 9200 invalidateParentIfNeeded(); 9201 } 9202 } 9203 } 9204 9205 /** 9206 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 9207 * completely transparent and 1 means the view is completely opaque. 9208 * 9209 * <p>By default this is 1.0f. 9210 * @return The opacity of the view. 9211 */ 9212 @ViewDebug.ExportedProperty(category = "drawing") 9213 public float getAlpha() { 9214 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 9215 } 9216 9217 /** 9218 * Returns whether this View has content which overlaps. This function, intended to be 9219 * overridden by specific View types, is an optimization when alpha is set on a view. If 9220 * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer 9221 * and then composited it into place, which can be expensive. If the view has no overlapping 9222 * rendering, the view can draw each primitive with the appropriate alpha value directly. 9223 * An example of overlapping rendering is a TextView with a background image, such as a 9224 * Button. An example of non-overlapping rendering is a TextView with no background, or 9225 * an ImageView with only the foreground image. The default implementation returns true; 9226 * subclasses should override if they have cases which can be optimized. 9227 * 9228 * @return true if the content in this view might overlap, false otherwise. 9229 */ 9230 public boolean hasOverlappingRendering() { 9231 return true; 9232 } 9233 9234 /** 9235 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 9236 * completely transparent and 1 means the view is completely opaque.</p> 9237 * 9238 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 9239 * responsible for applying the opacity itself. Otherwise, calling this method is 9240 * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and 9241 * setting a hardware layer.</p> 9242 * 9243 * <p>Note that setting alpha to a translucent value (0 < alpha < 1) may have 9244 * performance implications. It is generally best to use the alpha property sparingly and 9245 * transiently, as in the case of fading animations.</p> 9246 * 9247 * @param alpha The opacity of the view. 9248 * 9249 * @see #setLayerType(int, android.graphics.Paint) 9250 * 9251 * @attr ref android.R.styleable#View_alpha 9252 */ 9253 public void setAlpha(float alpha) { 9254 ensureTransformationInfo(); 9255 if (mTransformationInfo.mAlpha != alpha) { 9256 mTransformationInfo.mAlpha = alpha; 9257 if (onSetAlpha((int) (alpha * 255))) { 9258 mPrivateFlags |= PFLAG_ALPHA_SET; 9259 // subclass is handling alpha - don't optimize rendering cache invalidation 9260 invalidateParentCaches(); 9261 invalidate(true); 9262 } else { 9263 mPrivateFlags &= ~PFLAG_ALPHA_SET; 9264 invalidateViewProperty(true, false); 9265 if (mDisplayList != null) { 9266 mDisplayList.setAlpha(alpha); 9267 } 9268 } 9269 } 9270 } 9271 9272 /** 9273 * Faster version of setAlpha() which performs the same steps except there are 9274 * no calls to invalidate(). The caller of this function should perform proper invalidation 9275 * on the parent and this object. The return value indicates whether the subclass handles 9276 * alpha (the return value for onSetAlpha()). 9277 * 9278 * @param alpha The new value for the alpha property 9279 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 9280 * the new value for the alpha property is different from the old value 9281 */ 9282 boolean setAlphaNoInvalidation(float alpha) { 9283 ensureTransformationInfo(); 9284 if (mTransformationInfo.mAlpha != alpha) { 9285 mTransformationInfo.mAlpha = alpha; 9286 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 9287 if (subclassHandlesAlpha) { 9288 mPrivateFlags |= PFLAG_ALPHA_SET; 9289 return true; 9290 } else { 9291 mPrivateFlags &= ~PFLAG_ALPHA_SET; 9292 if (mDisplayList != null) { 9293 mDisplayList.setAlpha(alpha); 9294 } 9295 } 9296 } 9297 return false; 9298 } 9299 9300 /** 9301 * Top position of this view relative to its parent. 9302 * 9303 * @return The top of this view, in pixels. 9304 */ 9305 @ViewDebug.CapturedViewProperty 9306 public final int getTop() { 9307 return mTop; 9308 } 9309 9310 /** 9311 * Sets the top position of this view relative to its parent. This method is meant to be called 9312 * by the layout system and should not generally be called otherwise, because the property 9313 * may be changed at any time by the layout. 9314 * 9315 * @param top The top of this view, in pixels. 9316 */ 9317 public final void setTop(int top) { 9318 if (top != mTop) { 9319 updateMatrix(); 9320 final boolean matrixIsIdentity = mTransformationInfo == null 9321 || mTransformationInfo.mMatrixIsIdentity; 9322 if (matrixIsIdentity) { 9323 if (mAttachInfo != null) { 9324 int minTop; 9325 int yLoc; 9326 if (top < mTop) { 9327 minTop = top; 9328 yLoc = top - mTop; 9329 } else { 9330 minTop = mTop; 9331 yLoc = 0; 9332 } 9333 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 9334 } 9335 } else { 9336 // Double-invalidation is necessary to capture view's old and new areas 9337 invalidate(true); 9338 } 9339 9340 int width = mRight - mLeft; 9341 int oldHeight = mBottom - mTop; 9342 9343 mTop = top; 9344 if (mDisplayList != null) { 9345 mDisplayList.setTop(mTop); 9346 } 9347 9348 onSizeChanged(width, mBottom - mTop, width, oldHeight); 9349 9350 if (!matrixIsIdentity) { 9351 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 9352 // A change in dimension means an auto-centered pivot point changes, too 9353 mTransformationInfo.mMatrixDirty = true; 9354 } 9355 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 9356 invalidate(true); 9357 } 9358 mBackgroundSizeChanged = true; 9359 invalidateParentIfNeeded(); 9360 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9361 // View was rejected last time it was drawn by its parent; this may have changed 9362 invalidateParentIfNeeded(); 9363 } 9364 } 9365 } 9366 9367 /** 9368 * Bottom position of this view relative to its parent. 9369 * 9370 * @return The bottom of this view, in pixels. 9371 */ 9372 @ViewDebug.CapturedViewProperty 9373 public final int getBottom() { 9374 return mBottom; 9375 } 9376 9377 /** 9378 * True if this view has changed since the last time being drawn. 9379 * 9380 * @return The dirty state of this view. 9381 */ 9382 public boolean isDirty() { 9383 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 9384 } 9385 9386 /** 9387 * Sets the bottom position of this view relative to its parent. This method is meant to be 9388 * called by the layout system and should not generally be called otherwise, because the 9389 * property may be changed at any time by the layout. 9390 * 9391 * @param bottom The bottom of this view, in pixels. 9392 */ 9393 public final void setBottom(int bottom) { 9394 if (bottom != mBottom) { 9395 updateMatrix(); 9396 final boolean matrixIsIdentity = mTransformationInfo == null 9397 || mTransformationInfo.mMatrixIsIdentity; 9398 if (matrixIsIdentity) { 9399 if (mAttachInfo != null) { 9400 int maxBottom; 9401 if (bottom < mBottom) { 9402 maxBottom = mBottom; 9403 } else { 9404 maxBottom = bottom; 9405 } 9406 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 9407 } 9408 } else { 9409 // Double-invalidation is necessary to capture view's old and new areas 9410 invalidate(true); 9411 } 9412 9413 int width = mRight - mLeft; 9414 int oldHeight = mBottom - mTop; 9415 9416 mBottom = bottom; 9417 if (mDisplayList != null) { 9418 mDisplayList.setBottom(mBottom); 9419 } 9420 9421 onSizeChanged(width, mBottom - mTop, width, oldHeight); 9422 9423 if (!matrixIsIdentity) { 9424 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 9425 // A change in dimension means an auto-centered pivot point changes, too 9426 mTransformationInfo.mMatrixDirty = true; 9427 } 9428 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 9429 invalidate(true); 9430 } 9431 mBackgroundSizeChanged = true; 9432 invalidateParentIfNeeded(); 9433 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9434 // View was rejected last time it was drawn by its parent; this may have changed 9435 invalidateParentIfNeeded(); 9436 } 9437 } 9438 } 9439 9440 /** 9441 * Left position of this view relative to its parent. 9442 * 9443 * @return The left edge of this view, in pixels. 9444 */ 9445 @ViewDebug.CapturedViewProperty 9446 public final int getLeft() { 9447 return mLeft; 9448 } 9449 9450 /** 9451 * Sets the left position of this view relative to its parent. This method is meant to be called 9452 * by the layout system and should not generally be called otherwise, because the property 9453 * may be changed at any time by the layout. 9454 * 9455 * @param left The bottom of this view, in pixels. 9456 */ 9457 public final void setLeft(int left) { 9458 if (left != mLeft) { 9459 updateMatrix(); 9460 final boolean matrixIsIdentity = mTransformationInfo == null 9461 || mTransformationInfo.mMatrixIsIdentity; 9462 if (matrixIsIdentity) { 9463 if (mAttachInfo != null) { 9464 int minLeft; 9465 int xLoc; 9466 if (left < mLeft) { 9467 minLeft = left; 9468 xLoc = left - mLeft; 9469 } else { 9470 minLeft = mLeft; 9471 xLoc = 0; 9472 } 9473 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 9474 } 9475 } else { 9476 // Double-invalidation is necessary to capture view's old and new areas 9477 invalidate(true); 9478 } 9479 9480 int oldWidth = mRight - mLeft; 9481 int height = mBottom - mTop; 9482 9483 mLeft = left; 9484 if (mDisplayList != null) { 9485 mDisplayList.setLeft(left); 9486 } 9487 9488 onSizeChanged(mRight - mLeft, height, oldWidth, height); 9489 9490 if (!matrixIsIdentity) { 9491 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 9492 // A change in dimension means an auto-centered pivot point changes, too 9493 mTransformationInfo.mMatrixDirty = true; 9494 } 9495 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 9496 invalidate(true); 9497 } 9498 mBackgroundSizeChanged = true; 9499 invalidateParentIfNeeded(); 9500 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9501 // View was rejected last time it was drawn by its parent; this may have changed 9502 invalidateParentIfNeeded(); 9503 } 9504 } 9505 } 9506 9507 /** 9508 * Right position of this view relative to its parent. 9509 * 9510 * @return The right edge of this view, in pixels. 9511 */ 9512 @ViewDebug.CapturedViewProperty 9513 public final int getRight() { 9514 return mRight; 9515 } 9516 9517 /** 9518 * Sets the right position of this view relative to its parent. This method is meant to be called 9519 * by the layout system and should not generally be called otherwise, because the property 9520 * may be changed at any time by the layout. 9521 * 9522 * @param right The bottom of this view, in pixels. 9523 */ 9524 public final void setRight(int right) { 9525 if (right != mRight) { 9526 updateMatrix(); 9527 final boolean matrixIsIdentity = mTransformationInfo == null 9528 || mTransformationInfo.mMatrixIsIdentity; 9529 if (matrixIsIdentity) { 9530 if (mAttachInfo != null) { 9531 int maxRight; 9532 if (right < mRight) { 9533 maxRight = mRight; 9534 } else { 9535 maxRight = right; 9536 } 9537 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 9538 } 9539 } else { 9540 // Double-invalidation is necessary to capture view's old and new areas 9541 invalidate(true); 9542 } 9543 9544 int oldWidth = mRight - mLeft; 9545 int height = mBottom - mTop; 9546 9547 mRight = right; 9548 if (mDisplayList != null) { 9549 mDisplayList.setRight(mRight); 9550 } 9551 9552 onSizeChanged(mRight - mLeft, height, oldWidth, height); 9553 9554 if (!matrixIsIdentity) { 9555 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 9556 // A change in dimension means an auto-centered pivot point changes, too 9557 mTransformationInfo.mMatrixDirty = true; 9558 } 9559 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 9560 invalidate(true); 9561 } 9562 mBackgroundSizeChanged = true; 9563 invalidateParentIfNeeded(); 9564 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9565 // View was rejected last time it was drawn by its parent; this may have changed 9566 invalidateParentIfNeeded(); 9567 } 9568 } 9569 } 9570 9571 /** 9572 * The visual x position of this view, in pixels. This is equivalent to the 9573 * {@link #setTranslationX(float) translationX} property plus the current 9574 * {@link #getLeft() left} property. 9575 * 9576 * @return The visual x position of this view, in pixels. 9577 */ 9578 @ViewDebug.ExportedProperty(category = "drawing") 9579 public float getX() { 9580 return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0); 9581 } 9582 9583 /** 9584 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 9585 * {@link #setTranslationX(float) translationX} property to be the difference between 9586 * the x value passed in and the current {@link #getLeft() left} property. 9587 * 9588 * @param x The visual x position of this view, in pixels. 9589 */ 9590 public void setX(float x) { 9591 setTranslationX(x - mLeft); 9592 } 9593 9594 /** 9595 * The visual y position of this view, in pixels. This is equivalent to the 9596 * {@link #setTranslationY(float) translationY} property plus the current 9597 * {@link #getTop() top} property. 9598 * 9599 * @return The visual y position of this view, in pixels. 9600 */ 9601 @ViewDebug.ExportedProperty(category = "drawing") 9602 public float getY() { 9603 return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0); 9604 } 9605 9606 /** 9607 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 9608 * {@link #setTranslationY(float) translationY} property to be the difference between 9609 * the y value passed in and the current {@link #getTop() top} property. 9610 * 9611 * @param y The visual y position of this view, in pixels. 9612 */ 9613 public void setY(float y) { 9614 setTranslationY(y - mTop); 9615 } 9616 9617 9618 /** 9619 * The horizontal location of this view relative to its {@link #getLeft() left} position. 9620 * This position is post-layout, in addition to wherever the object's 9621 * layout placed it. 9622 * 9623 * @return The horizontal position of this view relative to its left position, in pixels. 9624 */ 9625 @ViewDebug.ExportedProperty(category = "drawing") 9626 public float getTranslationX() { 9627 return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0; 9628 } 9629 9630 /** 9631 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 9632 * This effectively positions the object post-layout, in addition to wherever the object's 9633 * layout placed it. 9634 * 9635 * @param translationX The horizontal position of this view relative to its left position, 9636 * in pixels. 9637 * 9638 * @attr ref android.R.styleable#View_translationX 9639 */ 9640 public void setTranslationX(float translationX) { 9641 ensureTransformationInfo(); 9642 final TransformationInfo info = mTransformationInfo; 9643 if (info.mTranslationX != translationX) { 9644 // Double-invalidation is necessary to capture view's old and new areas 9645 invalidateViewProperty(true, false); 9646 info.mTranslationX = translationX; 9647 info.mMatrixDirty = true; 9648 invalidateViewProperty(false, true); 9649 if (mDisplayList != null) { 9650 mDisplayList.setTranslationX(translationX); 9651 } 9652 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9653 // View was rejected last time it was drawn by its parent; this may have changed 9654 invalidateParentIfNeeded(); 9655 } 9656 } 9657 } 9658 9659 /** 9660 * The horizontal location of this view relative to its {@link #getTop() top} position. 9661 * This position is post-layout, in addition to wherever the object's 9662 * layout placed it. 9663 * 9664 * @return The vertical position of this view relative to its top position, 9665 * in pixels. 9666 */ 9667 @ViewDebug.ExportedProperty(category = "drawing") 9668 public float getTranslationY() { 9669 return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0; 9670 } 9671 9672 /** 9673 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 9674 * This effectively positions the object post-layout, in addition to wherever the object's 9675 * layout placed it. 9676 * 9677 * @param translationY The vertical position of this view relative to its top position, 9678 * in pixels. 9679 * 9680 * @attr ref android.R.styleable#View_translationY 9681 */ 9682 public void setTranslationY(float translationY) { 9683 ensureTransformationInfo(); 9684 final TransformationInfo info = mTransformationInfo; 9685 if (info.mTranslationY != translationY) { 9686 invalidateViewProperty(true, false); 9687 info.mTranslationY = translationY; 9688 info.mMatrixDirty = true; 9689 invalidateViewProperty(false, true); 9690 if (mDisplayList != null) { 9691 mDisplayList.setTranslationY(translationY); 9692 } 9693 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9694 // View was rejected last time it was drawn by its parent; this may have changed 9695 invalidateParentIfNeeded(); 9696 } 9697 } 9698 } 9699 9700 /** 9701 * Hit rectangle in parent's coordinates 9702 * 9703 * @param outRect The hit rectangle of the view. 9704 */ 9705 public void getHitRect(Rect outRect) { 9706 updateMatrix(); 9707 final TransformationInfo info = mTransformationInfo; 9708 if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) { 9709 outRect.set(mLeft, mTop, mRight, mBottom); 9710 } else { 9711 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 9712 tmpRect.set(-info.mPivotX, -info.mPivotY, 9713 getWidth() - info.mPivotX, getHeight() - info.mPivotY); 9714 info.mMatrix.mapRect(tmpRect); 9715 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 9716 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 9717 } 9718 } 9719 9720 /** 9721 * Determines whether the given point, in local coordinates is inside the view. 9722 */ 9723 /*package*/ final boolean pointInView(float localX, float localY) { 9724 return localX >= 0 && localX < (mRight - mLeft) 9725 && localY >= 0 && localY < (mBottom - mTop); 9726 } 9727 9728 /** 9729 * Utility method to determine whether the given point, in local coordinates, 9730 * is inside the view, where the area of the view is expanded by the slop factor. 9731 * This method is called while processing touch-move events to determine if the event 9732 * is still within the view. 9733 */ 9734 private boolean pointInView(float localX, float localY, float slop) { 9735 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 9736 localY < ((mBottom - mTop) + slop); 9737 } 9738 9739 /** 9740 * When a view has focus and the user navigates away from it, the next view is searched for 9741 * starting from the rectangle filled in by this method. 9742 * 9743 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 9744 * of the view. However, if your view maintains some idea of internal selection, 9745 * such as a cursor, or a selected row or column, you should override this method and 9746 * fill in a more specific rectangle. 9747 * 9748 * @param r The rectangle to fill in, in this view's coordinates. 9749 */ 9750 public void getFocusedRect(Rect r) { 9751 getDrawingRect(r); 9752 } 9753 9754 /** 9755 * If some part of this view is not clipped by any of its parents, then 9756 * return that area in r in global (root) coordinates. To convert r to local 9757 * coordinates (without taking possible View rotations into account), offset 9758 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 9759 * If the view is completely clipped or translated out, return false. 9760 * 9761 * @param r If true is returned, r holds the global coordinates of the 9762 * visible portion of this view. 9763 * @param globalOffset If true is returned, globalOffset holds the dx,dy 9764 * between this view and its root. globalOffet may be null. 9765 * @return true if r is non-empty (i.e. part of the view is visible at the 9766 * root level. 9767 */ 9768 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 9769 int width = mRight - mLeft; 9770 int height = mBottom - mTop; 9771 if (width > 0 && height > 0) { 9772 r.set(0, 0, width, height); 9773 if (globalOffset != null) { 9774 globalOffset.set(-mScrollX, -mScrollY); 9775 } 9776 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 9777 } 9778 return false; 9779 } 9780 9781 public final boolean getGlobalVisibleRect(Rect r) { 9782 return getGlobalVisibleRect(r, null); 9783 } 9784 9785 public final boolean getLocalVisibleRect(Rect r) { 9786 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 9787 if (getGlobalVisibleRect(r, offset)) { 9788 r.offset(-offset.x, -offset.y); // make r local 9789 return true; 9790 } 9791 return false; 9792 } 9793 9794 /** 9795 * Offset this view's vertical location by the specified number of pixels. 9796 * 9797 * @param offset the number of pixels to offset the view by 9798 */ 9799 public void offsetTopAndBottom(int offset) { 9800 if (offset != 0) { 9801 updateMatrix(); 9802 final boolean matrixIsIdentity = mTransformationInfo == null 9803 || mTransformationInfo.mMatrixIsIdentity; 9804 if (matrixIsIdentity) { 9805 if (mDisplayList != null) { 9806 invalidateViewProperty(false, false); 9807 } else { 9808 final ViewParent p = mParent; 9809 if (p != null && mAttachInfo != null) { 9810 final Rect r = mAttachInfo.mTmpInvalRect; 9811 int minTop; 9812 int maxBottom; 9813 int yLoc; 9814 if (offset < 0) { 9815 minTop = mTop + offset; 9816 maxBottom = mBottom; 9817 yLoc = offset; 9818 } else { 9819 minTop = mTop; 9820 maxBottom = mBottom + offset; 9821 yLoc = 0; 9822 } 9823 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 9824 p.invalidateChild(this, r); 9825 } 9826 } 9827 } else { 9828 invalidateViewProperty(false, false); 9829 } 9830 9831 mTop += offset; 9832 mBottom += offset; 9833 if (mDisplayList != null) { 9834 mDisplayList.offsetTopBottom(offset); 9835 invalidateViewProperty(false, false); 9836 } else { 9837 if (!matrixIsIdentity) { 9838 invalidateViewProperty(false, true); 9839 } 9840 invalidateParentIfNeeded(); 9841 } 9842 } 9843 } 9844 9845 /** 9846 * Offset this view's horizontal location by the specified amount of pixels. 9847 * 9848 * @param offset the numer of pixels to offset the view by 9849 */ 9850 public void offsetLeftAndRight(int offset) { 9851 if (offset != 0) { 9852 updateMatrix(); 9853 final boolean matrixIsIdentity = mTransformationInfo == null 9854 || mTransformationInfo.mMatrixIsIdentity; 9855 if (matrixIsIdentity) { 9856 if (mDisplayList != null) { 9857 invalidateViewProperty(false, false); 9858 } else { 9859 final ViewParent p = mParent; 9860 if (p != null && mAttachInfo != null) { 9861 final Rect r = mAttachInfo.mTmpInvalRect; 9862 int minLeft; 9863 int maxRight; 9864 if (offset < 0) { 9865 minLeft = mLeft + offset; 9866 maxRight = mRight; 9867 } else { 9868 minLeft = mLeft; 9869 maxRight = mRight + offset; 9870 } 9871 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 9872 p.invalidateChild(this, r); 9873 } 9874 } 9875 } else { 9876 invalidateViewProperty(false, false); 9877 } 9878 9879 mLeft += offset; 9880 mRight += offset; 9881 if (mDisplayList != null) { 9882 mDisplayList.offsetLeftRight(offset); 9883 invalidateViewProperty(false, false); 9884 } else { 9885 if (!matrixIsIdentity) { 9886 invalidateViewProperty(false, true); 9887 } 9888 invalidateParentIfNeeded(); 9889 } 9890 } 9891 } 9892 9893 /** 9894 * Get the LayoutParams associated with this view. All views should have 9895 * layout parameters. These supply parameters to the <i>parent</i> of this 9896 * view specifying how it should be arranged. There are many subclasses of 9897 * ViewGroup.LayoutParams, and these correspond to the different subclasses 9898 * of ViewGroup that are responsible for arranging their children. 9899 * 9900 * This method may return null if this View is not attached to a parent 9901 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 9902 * was not invoked successfully. When a View is attached to a parent 9903 * ViewGroup, this method must not return null. 9904 * 9905 * @return The LayoutParams associated with this view, or null if no 9906 * parameters have been set yet 9907 */ 9908 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 9909 public ViewGroup.LayoutParams getLayoutParams() { 9910 return mLayoutParams; 9911 } 9912 9913 /** 9914 * Set the layout parameters associated with this view. These supply 9915 * parameters to the <i>parent</i> of this view specifying how it should be 9916 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 9917 * correspond to the different subclasses of ViewGroup that are responsible 9918 * for arranging their children. 9919 * 9920 * @param params The layout parameters for this view, cannot be null 9921 */ 9922 public void setLayoutParams(ViewGroup.LayoutParams params) { 9923 if (params == null) { 9924 throw new NullPointerException("Layout parameters cannot be null"); 9925 } 9926 mLayoutParams = params; 9927 resolveLayoutParams(); 9928 if (mParent instanceof ViewGroup) { 9929 ((ViewGroup) mParent).onSetLayoutParams(this, params); 9930 } 9931 requestLayout(); 9932 } 9933 9934 /** 9935 * Resolve the layout parameters depending on the resolved layout direction 9936 */ 9937 private void resolveLayoutParams() { 9938 if (mLayoutParams != null) { 9939 mLayoutParams.onResolveLayoutDirection(getLayoutDirection()); 9940 } 9941 } 9942 9943 /** 9944 * Set the scrolled position of your view. This will cause a call to 9945 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9946 * invalidated. 9947 * @param x the x position to scroll to 9948 * @param y the y position to scroll to 9949 */ 9950 public void scrollTo(int x, int y) { 9951 if (mScrollX != x || mScrollY != y) { 9952 int oldX = mScrollX; 9953 int oldY = mScrollY; 9954 mScrollX = x; 9955 mScrollY = y; 9956 invalidateParentCaches(); 9957 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 9958 if (!awakenScrollBars()) { 9959 postInvalidateOnAnimation(); 9960 } 9961 } 9962 } 9963 9964 /** 9965 * Move the scrolled position of your view. This will cause a call to 9966 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9967 * invalidated. 9968 * @param x the amount of pixels to scroll by horizontally 9969 * @param y the amount of pixels to scroll by vertically 9970 */ 9971 public void scrollBy(int x, int y) { 9972 scrollTo(mScrollX + x, mScrollY + y); 9973 } 9974 9975 /** 9976 * <p>Trigger the scrollbars to draw. When invoked this method starts an 9977 * animation to fade the scrollbars out after a default delay. If a subclass 9978 * provides animated scrolling, the start delay should equal the duration 9979 * of the scrolling animation.</p> 9980 * 9981 * <p>The animation starts only if at least one of the scrollbars is 9982 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 9983 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 9984 * this method returns true, and false otherwise. If the animation is 9985 * started, this method calls {@link #invalidate()}; in that case the 9986 * caller should not call {@link #invalidate()}.</p> 9987 * 9988 * <p>This method should be invoked every time a subclass directly updates 9989 * the scroll parameters.</p> 9990 * 9991 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 9992 * and {@link #scrollTo(int, int)}.</p> 9993 * 9994 * @return true if the animation is played, false otherwise 9995 * 9996 * @see #awakenScrollBars(int) 9997 * @see #scrollBy(int, int) 9998 * @see #scrollTo(int, int) 9999 * @see #isHorizontalScrollBarEnabled() 10000 * @see #isVerticalScrollBarEnabled() 10001 * @see #setHorizontalScrollBarEnabled(boolean) 10002 * @see #setVerticalScrollBarEnabled(boolean) 10003 */ 10004 protected boolean awakenScrollBars() { 10005 return mScrollCache != null && 10006 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 10007 } 10008 10009 /** 10010 * Trigger the scrollbars to draw. 10011 * This method differs from awakenScrollBars() only in its default duration. 10012 * initialAwakenScrollBars() will show the scroll bars for longer than 10013 * usual to give the user more of a chance to notice them. 10014 * 10015 * @return true if the animation is played, false otherwise. 10016 */ 10017 private boolean initialAwakenScrollBars() { 10018 return mScrollCache != null && 10019 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 10020 } 10021 10022 /** 10023 * <p> 10024 * Trigger the scrollbars to draw. When invoked this method starts an 10025 * animation to fade the scrollbars out after a fixed delay. If a subclass 10026 * provides animated scrolling, the start delay should equal the duration of 10027 * the scrolling animation. 10028 * </p> 10029 * 10030 * <p> 10031 * The animation starts only if at least one of the scrollbars is enabled, 10032 * as specified by {@link #isHorizontalScrollBarEnabled()} and 10033 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 10034 * this method returns true, and false otherwise. If the animation is 10035 * started, this method calls {@link #invalidate()}; in that case the caller 10036 * should not call {@link #invalidate()}. 10037 * </p> 10038 * 10039 * <p> 10040 * This method should be invoked everytime a subclass directly updates the 10041 * scroll parameters. 10042 * </p> 10043 * 10044 * @param startDelay the delay, in milliseconds, after which the animation 10045 * should start; when the delay is 0, the animation starts 10046 * immediately 10047 * @return true if the animation is played, false otherwise 10048 * 10049 * @see #scrollBy(int, int) 10050 * @see #scrollTo(int, int) 10051 * @see #isHorizontalScrollBarEnabled() 10052 * @see #isVerticalScrollBarEnabled() 10053 * @see #setHorizontalScrollBarEnabled(boolean) 10054 * @see #setVerticalScrollBarEnabled(boolean) 10055 */ 10056 protected boolean awakenScrollBars(int startDelay) { 10057 return awakenScrollBars(startDelay, true); 10058 } 10059 10060 /** 10061 * <p> 10062 * Trigger the scrollbars to draw. When invoked this method starts an 10063 * animation to fade the scrollbars out after a fixed delay. If a subclass 10064 * provides animated scrolling, the start delay should equal the duration of 10065 * the scrolling animation. 10066 * </p> 10067 * 10068 * <p> 10069 * The animation starts only if at least one of the scrollbars is enabled, 10070 * as specified by {@link #isHorizontalScrollBarEnabled()} and 10071 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 10072 * this method returns true, and false otherwise. If the animation is 10073 * started, this method calls {@link #invalidate()} if the invalidate parameter 10074 * is set to true; in that case the caller 10075 * should not call {@link #invalidate()}. 10076 * </p> 10077 * 10078 * <p> 10079 * This method should be invoked everytime a subclass directly updates the 10080 * scroll parameters. 10081 * </p> 10082 * 10083 * @param startDelay the delay, in milliseconds, after which the animation 10084 * should start; when the delay is 0, the animation starts 10085 * immediately 10086 * 10087 * @param invalidate Wheter this method should call invalidate 10088 * 10089 * @return true if the animation is played, false otherwise 10090 * 10091 * @see #scrollBy(int, int) 10092 * @see #scrollTo(int, int) 10093 * @see #isHorizontalScrollBarEnabled() 10094 * @see #isVerticalScrollBarEnabled() 10095 * @see #setHorizontalScrollBarEnabled(boolean) 10096 * @see #setVerticalScrollBarEnabled(boolean) 10097 */ 10098 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 10099 final ScrollabilityCache scrollCache = mScrollCache; 10100 10101 if (scrollCache == null || !scrollCache.fadeScrollBars) { 10102 return false; 10103 } 10104 10105 if (scrollCache.scrollBar == null) { 10106 scrollCache.scrollBar = new ScrollBarDrawable(); 10107 } 10108 10109 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 10110 10111 if (invalidate) { 10112 // Invalidate to show the scrollbars 10113 postInvalidateOnAnimation(); 10114 } 10115 10116 if (scrollCache.state == ScrollabilityCache.OFF) { 10117 // FIXME: this is copied from WindowManagerService. 10118 // We should get this value from the system when it 10119 // is possible to do so. 10120 final int KEY_REPEAT_FIRST_DELAY = 750; 10121 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 10122 } 10123 10124 // Tell mScrollCache when we should start fading. This may 10125 // extend the fade start time if one was already scheduled 10126 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 10127 scrollCache.fadeStartTime = fadeStartTime; 10128 scrollCache.state = ScrollabilityCache.ON; 10129 10130 // Schedule our fader to run, unscheduling any old ones first 10131 if (mAttachInfo != null) { 10132 mAttachInfo.mHandler.removeCallbacks(scrollCache); 10133 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 10134 } 10135 10136 return true; 10137 } 10138 10139 return false; 10140 } 10141 10142 /** 10143 * Do not invalidate views which are not visible and which are not running an animation. They 10144 * will not get drawn and they should not set dirty flags as if they will be drawn 10145 */ 10146 private boolean skipInvalidate() { 10147 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 10148 (!(mParent instanceof ViewGroup) || 10149 !((ViewGroup) mParent).isViewTransitioning(this)); 10150 } 10151 /** 10152 * Mark the area defined by dirty as needing to be drawn. If the view is 10153 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point 10154 * in the future. This must be called from a UI thread. To call from a non-UI 10155 * thread, call {@link #postInvalidate()}. 10156 * 10157 * WARNING: This method is destructive to dirty. 10158 * @param dirty the rectangle representing the bounds of the dirty region 10159 */ 10160 public void invalidate(Rect dirty) { 10161 if (skipInvalidate()) { 10162 return; 10163 } 10164 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) || 10165 (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID || 10166 (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) { 10167 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 10168 mPrivateFlags |= PFLAG_INVALIDATED; 10169 mPrivateFlags |= PFLAG_DIRTY; 10170 final ViewParent p = mParent; 10171 final AttachInfo ai = mAttachInfo; 10172 //noinspection PointlessBooleanExpression,ConstantConditions 10173 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 10174 if (p != null && ai != null && ai.mHardwareAccelerated) { 10175 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 10176 // with a null dirty rect, which tells the ViewAncestor to redraw everything 10177 p.invalidateChild(this, null); 10178 return; 10179 } 10180 } 10181 if (p != null && ai != null) { 10182 final int scrollX = mScrollX; 10183 final int scrollY = mScrollY; 10184 final Rect r = ai.mTmpInvalRect; 10185 r.set(dirty.left - scrollX, dirty.top - scrollY, 10186 dirty.right - scrollX, dirty.bottom - scrollY); 10187 mParent.invalidateChild(this, r); 10188 } 10189 } 10190 } 10191 10192 /** 10193 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. 10194 * The coordinates of the dirty rect are relative to the view. 10195 * If the view is visible, {@link #onDraw(android.graphics.Canvas)} 10196 * will be called at some point in the future. This must be called from 10197 * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}. 10198 * @param l the left position of the dirty region 10199 * @param t the top position of the dirty region 10200 * @param r the right position of the dirty region 10201 * @param b the bottom position of the dirty region 10202 */ 10203 public void invalidate(int l, int t, int r, int b) { 10204 if (skipInvalidate()) { 10205 return; 10206 } 10207 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) || 10208 (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID || 10209 (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) { 10210 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 10211 mPrivateFlags |= PFLAG_INVALIDATED; 10212 mPrivateFlags |= PFLAG_DIRTY; 10213 final ViewParent p = mParent; 10214 final AttachInfo ai = mAttachInfo; 10215 //noinspection PointlessBooleanExpression,ConstantConditions 10216 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 10217 if (p != null && ai != null && ai.mHardwareAccelerated) { 10218 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 10219 // with a null dirty rect, which tells the ViewAncestor to redraw everything 10220 p.invalidateChild(this, null); 10221 return; 10222 } 10223 } 10224 if (p != null && ai != null && l < r && t < b) { 10225 final int scrollX = mScrollX; 10226 final int scrollY = mScrollY; 10227 final Rect tmpr = ai.mTmpInvalRect; 10228 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY); 10229 p.invalidateChild(this, tmpr); 10230 } 10231 } 10232 } 10233 10234 /** 10235 * Invalidate the whole view. If the view is visible, 10236 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 10237 * the future. This must be called from a UI thread. To call from a non-UI thread, 10238 * call {@link #postInvalidate()}. 10239 */ 10240 public void invalidate() { 10241 invalidate(true); 10242 } 10243 10244 /** 10245 * This is where the invalidate() work actually happens. A full invalidate() 10246 * causes the drawing cache to be invalidated, but this function can be called with 10247 * invalidateCache set to false to skip that invalidation step for cases that do not 10248 * need it (for example, a component that remains at the same dimensions with the same 10249 * content). 10250 * 10251 * @param invalidateCache Whether the drawing cache for this view should be invalidated as 10252 * well. This is usually true for a full invalidate, but may be set to false if the 10253 * View's contents or dimensions have not changed. 10254 */ 10255 void invalidate(boolean invalidateCache) { 10256 if (skipInvalidate()) { 10257 return; 10258 } 10259 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) || 10260 (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) || 10261 (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED || isOpaque() != mLastIsOpaque) { 10262 mLastIsOpaque = isOpaque(); 10263 mPrivateFlags &= ~PFLAG_DRAWN; 10264 mPrivateFlags |= PFLAG_DIRTY; 10265 if (invalidateCache) { 10266 mPrivateFlags |= PFLAG_INVALIDATED; 10267 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 10268 } 10269 final AttachInfo ai = mAttachInfo; 10270 final ViewParent p = mParent; 10271 //noinspection PointlessBooleanExpression,ConstantConditions 10272 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 10273 if (p != null && ai != null && ai.mHardwareAccelerated) { 10274 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 10275 // with a null dirty rect, which tells the ViewAncestor to redraw everything 10276 p.invalidateChild(this, null); 10277 return; 10278 } 10279 } 10280 10281 if (p != null && ai != null) { 10282 final Rect r = ai.mTmpInvalRect; 10283 r.set(0, 0, mRight - mLeft, mBottom - mTop); 10284 // Don't call invalidate -- we don't want to internally scroll 10285 // our own bounds 10286 p.invalidateChild(this, r); 10287 } 10288 } 10289 } 10290 10291 /** 10292 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 10293 * set any flags or handle all of the cases handled by the default invalidation methods. 10294 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 10295 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 10296 * walk up the hierarchy, transforming the dirty rect as necessary. 10297 * 10298 * The method also handles normal invalidation logic if display list properties are not 10299 * being used in this view. The invalidateParent and forceRedraw flags are used by that 10300 * backup approach, to handle these cases used in the various property-setting methods. 10301 * 10302 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 10303 * are not being used in this view 10304 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 10305 * list properties are not being used in this view 10306 */ 10307 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 10308 if (mDisplayList == null || (mPrivateFlags & PFLAG_DRAW_ANIMATION) == PFLAG_DRAW_ANIMATION) { 10309 if (invalidateParent) { 10310 invalidateParentCaches(); 10311 } 10312 if (forceRedraw) { 10313 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10314 } 10315 invalidate(false); 10316 } else { 10317 final AttachInfo ai = mAttachInfo; 10318 final ViewParent p = mParent; 10319 if (p != null && ai != null) { 10320 final Rect r = ai.mTmpInvalRect; 10321 r.set(0, 0, mRight - mLeft, mBottom - mTop); 10322 if (mParent instanceof ViewGroup) { 10323 ((ViewGroup) mParent).invalidateChildFast(this, r); 10324 } else { 10325 mParent.invalidateChild(this, r); 10326 } 10327 } 10328 } 10329 } 10330 10331 /** 10332 * Utility method to transform a given Rect by the current matrix of this view. 10333 */ 10334 void transformRect(final Rect rect) { 10335 if (!getMatrix().isIdentity()) { 10336 RectF boundingRect = mAttachInfo.mTmpTransformRect; 10337 boundingRect.set(rect); 10338 getMatrix().mapRect(boundingRect); 10339 rect.set((int) (boundingRect.left - 0.5f), 10340 (int) (boundingRect.top - 0.5f), 10341 (int) (boundingRect.right + 0.5f), 10342 (int) (boundingRect.bottom + 0.5f)); 10343 } 10344 } 10345 10346 /** 10347 * Used to indicate that the parent of this view should clear its caches. This functionality 10348 * is used to force the parent to rebuild its display list (when hardware-accelerated), 10349 * which is necessary when various parent-managed properties of the view change, such as 10350 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 10351 * clears the parent caches and does not causes an invalidate event. 10352 * 10353 * @hide 10354 */ 10355 protected void invalidateParentCaches() { 10356 if (mParent instanceof View) { 10357 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 10358 } 10359 } 10360 10361 /** 10362 * Used to indicate that the parent of this view should be invalidated. This functionality 10363 * is used to force the parent to rebuild its display list (when hardware-accelerated), 10364 * which is necessary when various parent-managed properties of the view change, such as 10365 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 10366 * an invalidation event to the parent. 10367 * 10368 * @hide 10369 */ 10370 protected void invalidateParentIfNeeded() { 10371 if (isHardwareAccelerated() && mParent instanceof View) { 10372 ((View) mParent).invalidate(true); 10373 } 10374 } 10375 10376 /** 10377 * Indicates whether this View is opaque. An opaque View guarantees that it will 10378 * draw all the pixels overlapping its bounds using a fully opaque color. 10379 * 10380 * Subclasses of View should override this method whenever possible to indicate 10381 * whether an instance is opaque. Opaque Views are treated in a special way by 10382 * the View hierarchy, possibly allowing it to perform optimizations during 10383 * invalidate/draw passes. 10384 * 10385 * @return True if this View is guaranteed to be fully opaque, false otherwise. 10386 */ 10387 @ViewDebug.ExportedProperty(category = "drawing") 10388 public boolean isOpaque() { 10389 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 10390 ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1.0f) >= 1.0f); 10391 } 10392 10393 /** 10394 * @hide 10395 */ 10396 protected void computeOpaqueFlags() { 10397 // Opaque if: 10398 // - Has a background 10399 // - Background is opaque 10400 // - Doesn't have scrollbars or scrollbars are inside overlay 10401 10402 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 10403 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 10404 } else { 10405 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 10406 } 10407 10408 final int flags = mViewFlags; 10409 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 10410 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) { 10411 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 10412 } else { 10413 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 10414 } 10415 } 10416 10417 /** 10418 * @hide 10419 */ 10420 protected boolean hasOpaqueScrollbars() { 10421 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 10422 } 10423 10424 /** 10425 * @return A handler associated with the thread running the View. This 10426 * handler can be used to pump events in the UI events queue. 10427 */ 10428 public Handler getHandler() { 10429 if (mAttachInfo != null) { 10430 return mAttachInfo.mHandler; 10431 } 10432 return null; 10433 } 10434 10435 /** 10436 * Gets the view root associated with the View. 10437 * @return The view root, or null if none. 10438 * @hide 10439 */ 10440 public ViewRootImpl getViewRootImpl() { 10441 if (mAttachInfo != null) { 10442 return mAttachInfo.mViewRootImpl; 10443 } 10444 return null; 10445 } 10446 10447 /** 10448 * <p>Causes the Runnable to be added to the message queue. 10449 * The runnable will be run on the user interface thread.</p> 10450 * 10451 * <p>This method can be invoked from outside of the UI thread 10452 * only when this View is attached to a window.</p> 10453 * 10454 * @param action The Runnable that will be executed. 10455 * 10456 * @return Returns true if the Runnable was successfully placed in to the 10457 * message queue. Returns false on failure, usually because the 10458 * looper processing the message queue is exiting. 10459 * 10460 * @see #postDelayed 10461 * @see #removeCallbacks 10462 */ 10463 public boolean post(Runnable action) { 10464 final AttachInfo attachInfo = mAttachInfo; 10465 if (attachInfo != null) { 10466 return attachInfo.mHandler.post(action); 10467 } 10468 // Assume that post will succeed later 10469 ViewRootImpl.getRunQueue().post(action); 10470 return true; 10471 } 10472 10473 /** 10474 * <p>Causes the Runnable to be added to the message queue, to be run 10475 * after the specified amount of time elapses. 10476 * The runnable will be run on the user interface thread.</p> 10477 * 10478 * <p>This method can be invoked from outside of the UI thread 10479 * only when this View is attached to a window.</p> 10480 * 10481 * @param action The Runnable that will be executed. 10482 * @param delayMillis The delay (in milliseconds) until the Runnable 10483 * will be executed. 10484 * 10485 * @return true if the Runnable was successfully placed in to the 10486 * message queue. Returns false on failure, usually because the 10487 * looper processing the message queue is exiting. Note that a 10488 * result of true does not mean the Runnable will be processed -- 10489 * if the looper is quit before the delivery time of the message 10490 * occurs then the message will be dropped. 10491 * 10492 * @see #post 10493 * @see #removeCallbacks 10494 */ 10495 public boolean postDelayed(Runnable action, long delayMillis) { 10496 final AttachInfo attachInfo = mAttachInfo; 10497 if (attachInfo != null) { 10498 return attachInfo.mHandler.postDelayed(action, delayMillis); 10499 } 10500 // Assume that post will succeed later 10501 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 10502 return true; 10503 } 10504 10505 /** 10506 * <p>Causes the Runnable to execute on the next animation time step. 10507 * The runnable will be run on the user interface thread.</p> 10508 * 10509 * <p>This method can be invoked from outside of the UI thread 10510 * only when this View is attached to a window.</p> 10511 * 10512 * @param action The Runnable that will be executed. 10513 * 10514 * @see #postOnAnimationDelayed 10515 * @see #removeCallbacks 10516 */ 10517 public void postOnAnimation(Runnable action) { 10518 final AttachInfo attachInfo = mAttachInfo; 10519 if (attachInfo != null) { 10520 attachInfo.mViewRootImpl.mChoreographer.postCallback( 10521 Choreographer.CALLBACK_ANIMATION, action, null); 10522 } else { 10523 // Assume that post will succeed later 10524 ViewRootImpl.getRunQueue().post(action); 10525 } 10526 } 10527 10528 /** 10529 * <p>Causes the Runnable to execute on the next animation time step, 10530 * after the specified amount of time elapses. 10531 * The runnable will be run on the user interface thread.</p> 10532 * 10533 * <p>This method can be invoked from outside of the UI thread 10534 * only when this View is attached to a window.</p> 10535 * 10536 * @param action The Runnable that will be executed. 10537 * @param delayMillis The delay (in milliseconds) until the Runnable 10538 * will be executed. 10539 * 10540 * @see #postOnAnimation 10541 * @see #removeCallbacks 10542 */ 10543 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 10544 final AttachInfo attachInfo = mAttachInfo; 10545 if (attachInfo != null) { 10546 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 10547 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 10548 } else { 10549 // Assume that post will succeed later 10550 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 10551 } 10552 } 10553 10554 /** 10555 * <p>Removes the specified Runnable from the message queue.</p> 10556 * 10557 * <p>This method can be invoked from outside of the UI thread 10558 * only when this View is attached to a window.</p> 10559 * 10560 * @param action The Runnable to remove from the message handling queue 10561 * 10562 * @return true if this view could ask the Handler to remove the Runnable, 10563 * false otherwise. When the returned value is true, the Runnable 10564 * may or may not have been actually removed from the message queue 10565 * (for instance, if the Runnable was not in the queue already.) 10566 * 10567 * @see #post 10568 * @see #postDelayed 10569 * @see #postOnAnimation 10570 * @see #postOnAnimationDelayed 10571 */ 10572 public boolean removeCallbacks(Runnable action) { 10573 if (action != null) { 10574 final AttachInfo attachInfo = mAttachInfo; 10575 if (attachInfo != null) { 10576 attachInfo.mHandler.removeCallbacks(action); 10577 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 10578 Choreographer.CALLBACK_ANIMATION, action, null); 10579 } else { 10580 // Assume that post will succeed later 10581 ViewRootImpl.getRunQueue().removeCallbacks(action); 10582 } 10583 } 10584 return true; 10585 } 10586 10587 /** 10588 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 10589 * Use this to invalidate the View from a non-UI thread.</p> 10590 * 10591 * <p>This method can be invoked from outside of the UI thread 10592 * only when this View is attached to a window.</p> 10593 * 10594 * @see #invalidate() 10595 * @see #postInvalidateDelayed(long) 10596 */ 10597 public void postInvalidate() { 10598 postInvalidateDelayed(0); 10599 } 10600 10601 /** 10602 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 10603 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 10604 * 10605 * <p>This method can be invoked from outside of the UI thread 10606 * only when this View is attached to a window.</p> 10607 * 10608 * @param left The left coordinate of the rectangle to invalidate. 10609 * @param top The top coordinate of the rectangle to invalidate. 10610 * @param right The right coordinate of the rectangle to invalidate. 10611 * @param bottom The bottom coordinate of the rectangle to invalidate. 10612 * 10613 * @see #invalidate(int, int, int, int) 10614 * @see #invalidate(Rect) 10615 * @see #postInvalidateDelayed(long, int, int, int, int) 10616 */ 10617 public void postInvalidate(int left, int top, int right, int bottom) { 10618 postInvalidateDelayed(0, left, top, right, bottom); 10619 } 10620 10621 /** 10622 * <p>Cause an invalidate to happen on a subsequent cycle through the event 10623 * loop. Waits for the specified amount of time.</p> 10624 * 10625 * <p>This method can be invoked from outside of the UI thread 10626 * only when this View is attached to a window.</p> 10627 * 10628 * @param delayMilliseconds the duration in milliseconds to delay the 10629 * invalidation by 10630 * 10631 * @see #invalidate() 10632 * @see #postInvalidate() 10633 */ 10634 public void postInvalidateDelayed(long delayMilliseconds) { 10635 // We try only with the AttachInfo because there's no point in invalidating 10636 // if we are not attached to our window 10637 final AttachInfo attachInfo = mAttachInfo; 10638 if (attachInfo != null) { 10639 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 10640 } 10641 } 10642 10643 /** 10644 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 10645 * through the event loop. Waits for the specified amount of time.</p> 10646 * 10647 * <p>This method can be invoked from outside of the UI thread 10648 * only when this View is attached to a window.</p> 10649 * 10650 * @param delayMilliseconds the duration in milliseconds to delay the 10651 * invalidation by 10652 * @param left The left coordinate of the rectangle to invalidate. 10653 * @param top The top coordinate of the rectangle to invalidate. 10654 * @param right The right coordinate of the rectangle to invalidate. 10655 * @param bottom The bottom coordinate of the rectangle to invalidate. 10656 * 10657 * @see #invalidate(int, int, int, int) 10658 * @see #invalidate(Rect) 10659 * @see #postInvalidate(int, int, int, int) 10660 */ 10661 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 10662 int right, int bottom) { 10663 10664 // We try only with the AttachInfo because there's no point in invalidating 10665 // if we are not attached to our window 10666 final AttachInfo attachInfo = mAttachInfo; 10667 if (attachInfo != null) { 10668 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire(); 10669 info.target = this; 10670 info.left = left; 10671 info.top = top; 10672 info.right = right; 10673 info.bottom = bottom; 10674 10675 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 10676 } 10677 } 10678 10679 /** 10680 * <p>Cause an invalidate to happen on the next animation time step, typically the 10681 * next display frame.</p> 10682 * 10683 * <p>This method can be invoked from outside of the UI thread 10684 * only when this View is attached to a window.</p> 10685 * 10686 * @see #invalidate() 10687 */ 10688 public void postInvalidateOnAnimation() { 10689 // We try only with the AttachInfo because there's no point in invalidating 10690 // if we are not attached to our window 10691 final AttachInfo attachInfo = mAttachInfo; 10692 if (attachInfo != null) { 10693 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 10694 } 10695 } 10696 10697 /** 10698 * <p>Cause an invalidate of the specified area to happen on the next animation 10699 * time step, typically the next display frame.</p> 10700 * 10701 * <p>This method can be invoked from outside of the UI thread 10702 * only when this View is attached to a window.</p> 10703 * 10704 * @param left The left coordinate of the rectangle to invalidate. 10705 * @param top The top coordinate of the rectangle to invalidate. 10706 * @param right The right coordinate of the rectangle to invalidate. 10707 * @param bottom The bottom coordinate of the rectangle to invalidate. 10708 * 10709 * @see #invalidate(int, int, int, int) 10710 * @see #invalidate(Rect) 10711 */ 10712 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 10713 // We try only with the AttachInfo because there's no point in invalidating 10714 // if we are not attached to our window 10715 final AttachInfo attachInfo = mAttachInfo; 10716 if (attachInfo != null) { 10717 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire(); 10718 info.target = this; 10719 info.left = left; 10720 info.top = top; 10721 info.right = right; 10722 info.bottom = bottom; 10723 10724 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 10725 } 10726 } 10727 10728 /** 10729 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 10730 * This event is sent at most once every 10731 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 10732 */ 10733 private void postSendViewScrolledAccessibilityEventCallback() { 10734 if (mSendViewScrolledAccessibilityEvent == null) { 10735 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 10736 } 10737 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 10738 mSendViewScrolledAccessibilityEvent.mIsPending = true; 10739 postDelayed(mSendViewScrolledAccessibilityEvent, 10740 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 10741 } 10742 } 10743 10744 /** 10745 * Called by a parent to request that a child update its values for mScrollX 10746 * and mScrollY if necessary. This will typically be done if the child is 10747 * animating a scroll using a {@link android.widget.Scroller Scroller} 10748 * object. 10749 */ 10750 public void computeScroll() { 10751 } 10752 10753 /** 10754 * <p>Indicate whether the horizontal edges are faded when the view is 10755 * scrolled horizontally.</p> 10756 * 10757 * @return true if the horizontal edges should are faded on scroll, false 10758 * otherwise 10759 * 10760 * @see #setHorizontalFadingEdgeEnabled(boolean) 10761 * 10762 * @attr ref android.R.styleable#View_requiresFadingEdge 10763 */ 10764 public boolean isHorizontalFadingEdgeEnabled() { 10765 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 10766 } 10767 10768 /** 10769 * <p>Define whether the horizontal edges should be faded when this view 10770 * is scrolled horizontally.</p> 10771 * 10772 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 10773 * be faded when the view is scrolled 10774 * horizontally 10775 * 10776 * @see #isHorizontalFadingEdgeEnabled() 10777 * 10778 * @attr ref android.R.styleable#View_requiresFadingEdge 10779 */ 10780 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 10781 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 10782 if (horizontalFadingEdgeEnabled) { 10783 initScrollCache(); 10784 } 10785 10786 mViewFlags ^= FADING_EDGE_HORIZONTAL; 10787 } 10788 } 10789 10790 /** 10791 * <p>Indicate whether the vertical edges are faded when the view is 10792 * scrolled horizontally.</p> 10793 * 10794 * @return true if the vertical edges should are faded on scroll, false 10795 * otherwise 10796 * 10797 * @see #setVerticalFadingEdgeEnabled(boolean) 10798 * 10799 * @attr ref android.R.styleable#View_requiresFadingEdge 10800 */ 10801 public boolean isVerticalFadingEdgeEnabled() { 10802 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 10803 } 10804 10805 /** 10806 * <p>Define whether the vertical edges should be faded when this view 10807 * is scrolled vertically.</p> 10808 * 10809 * @param verticalFadingEdgeEnabled true if the vertical edges should 10810 * be faded when the view is scrolled 10811 * vertically 10812 * 10813 * @see #isVerticalFadingEdgeEnabled() 10814 * 10815 * @attr ref android.R.styleable#View_requiresFadingEdge 10816 */ 10817 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 10818 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 10819 if (verticalFadingEdgeEnabled) { 10820 initScrollCache(); 10821 } 10822 10823 mViewFlags ^= FADING_EDGE_VERTICAL; 10824 } 10825 } 10826 10827 /** 10828 * Returns the strength, or intensity, of the top faded edge. The strength is 10829 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 10830 * returns 0.0 or 1.0 but no value in between. 10831 * 10832 * Subclasses should override this method to provide a smoother fade transition 10833 * when scrolling occurs. 10834 * 10835 * @return the intensity of the top fade as a float between 0.0f and 1.0f 10836 */ 10837 protected float getTopFadingEdgeStrength() { 10838 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 10839 } 10840 10841 /** 10842 * Returns the strength, or intensity, of the bottom faded edge. The strength is 10843 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 10844 * returns 0.0 or 1.0 but no value in between. 10845 * 10846 * Subclasses should override this method to provide a smoother fade transition 10847 * when scrolling occurs. 10848 * 10849 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 10850 */ 10851 protected float getBottomFadingEdgeStrength() { 10852 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 10853 computeVerticalScrollRange() ? 1.0f : 0.0f; 10854 } 10855 10856 /** 10857 * Returns the strength, or intensity, of the left faded edge. The strength is 10858 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 10859 * returns 0.0 or 1.0 but no value in between. 10860 * 10861 * Subclasses should override this method to provide a smoother fade transition 10862 * when scrolling occurs. 10863 * 10864 * @return the intensity of the left fade as a float between 0.0f and 1.0f 10865 */ 10866 protected float getLeftFadingEdgeStrength() { 10867 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 10868 } 10869 10870 /** 10871 * Returns the strength, or intensity, of the right faded edge. The strength is 10872 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 10873 * returns 0.0 or 1.0 but no value in between. 10874 * 10875 * Subclasses should override this method to provide a smoother fade transition 10876 * when scrolling occurs. 10877 * 10878 * @return the intensity of the right fade as a float between 0.0f and 1.0f 10879 */ 10880 protected float getRightFadingEdgeStrength() { 10881 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 10882 computeHorizontalScrollRange() ? 1.0f : 0.0f; 10883 } 10884 10885 /** 10886 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 10887 * scrollbar is not drawn by default.</p> 10888 * 10889 * @return true if the horizontal scrollbar should be painted, false 10890 * otherwise 10891 * 10892 * @see #setHorizontalScrollBarEnabled(boolean) 10893 */ 10894 public boolean isHorizontalScrollBarEnabled() { 10895 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 10896 } 10897 10898 /** 10899 * <p>Define whether the horizontal scrollbar should be drawn or not. The 10900 * scrollbar is not drawn by default.</p> 10901 * 10902 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 10903 * be painted 10904 * 10905 * @see #isHorizontalScrollBarEnabled() 10906 */ 10907 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 10908 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 10909 mViewFlags ^= SCROLLBARS_HORIZONTAL; 10910 computeOpaqueFlags(); 10911 resolvePadding(); 10912 } 10913 } 10914 10915 /** 10916 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 10917 * scrollbar is not drawn by default.</p> 10918 * 10919 * @return true if the vertical scrollbar should be painted, false 10920 * otherwise 10921 * 10922 * @see #setVerticalScrollBarEnabled(boolean) 10923 */ 10924 public boolean isVerticalScrollBarEnabled() { 10925 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 10926 } 10927 10928 /** 10929 * <p>Define whether the vertical scrollbar should be drawn or not. The 10930 * scrollbar is not drawn by default.</p> 10931 * 10932 * @param verticalScrollBarEnabled true if the vertical scrollbar should 10933 * be painted 10934 * 10935 * @see #isVerticalScrollBarEnabled() 10936 */ 10937 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 10938 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 10939 mViewFlags ^= SCROLLBARS_VERTICAL; 10940 computeOpaqueFlags(); 10941 resolvePadding(); 10942 } 10943 } 10944 10945 /** 10946 * @hide 10947 */ 10948 protected void recomputePadding() { 10949 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 10950 } 10951 10952 /** 10953 * Define whether scrollbars will fade when the view is not scrolling. 10954 * 10955 * @param fadeScrollbars wheter to enable fading 10956 * 10957 * @attr ref android.R.styleable#View_fadeScrollbars 10958 */ 10959 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 10960 initScrollCache(); 10961 final ScrollabilityCache scrollabilityCache = mScrollCache; 10962 scrollabilityCache.fadeScrollBars = fadeScrollbars; 10963 if (fadeScrollbars) { 10964 scrollabilityCache.state = ScrollabilityCache.OFF; 10965 } else { 10966 scrollabilityCache.state = ScrollabilityCache.ON; 10967 } 10968 } 10969 10970 /** 10971 * 10972 * Returns true if scrollbars will fade when this view is not scrolling 10973 * 10974 * @return true if scrollbar fading is enabled 10975 * 10976 * @attr ref android.R.styleable#View_fadeScrollbars 10977 */ 10978 public boolean isScrollbarFadingEnabled() { 10979 return mScrollCache != null && mScrollCache.fadeScrollBars; 10980 } 10981 10982 /** 10983 * 10984 * Returns the delay before scrollbars fade. 10985 * 10986 * @return the delay before scrollbars fade 10987 * 10988 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 10989 */ 10990 public int getScrollBarDefaultDelayBeforeFade() { 10991 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 10992 mScrollCache.scrollBarDefaultDelayBeforeFade; 10993 } 10994 10995 /** 10996 * Define the delay before scrollbars fade. 10997 * 10998 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 10999 * 11000 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 11001 */ 11002 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 11003 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 11004 } 11005 11006 /** 11007 * 11008 * Returns the scrollbar fade duration. 11009 * 11010 * @return the scrollbar fade duration 11011 * 11012 * @attr ref android.R.styleable#View_scrollbarFadeDuration 11013 */ 11014 public int getScrollBarFadeDuration() { 11015 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 11016 mScrollCache.scrollBarFadeDuration; 11017 } 11018 11019 /** 11020 * Define the scrollbar fade duration. 11021 * 11022 * @param scrollBarFadeDuration - the scrollbar fade duration 11023 * 11024 * @attr ref android.R.styleable#View_scrollbarFadeDuration 11025 */ 11026 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 11027 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 11028 } 11029 11030 /** 11031 * 11032 * Returns the scrollbar size. 11033 * 11034 * @return the scrollbar size 11035 * 11036 * @attr ref android.R.styleable#View_scrollbarSize 11037 */ 11038 public int getScrollBarSize() { 11039 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 11040 mScrollCache.scrollBarSize; 11041 } 11042 11043 /** 11044 * Define the scrollbar size. 11045 * 11046 * @param scrollBarSize - the scrollbar size 11047 * 11048 * @attr ref android.R.styleable#View_scrollbarSize 11049 */ 11050 public void setScrollBarSize(int scrollBarSize) { 11051 getScrollCache().scrollBarSize = scrollBarSize; 11052 } 11053 11054 /** 11055 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 11056 * inset. When inset, they add to the padding of the view. And the scrollbars 11057 * can be drawn inside the padding area or on the edge of the view. For example, 11058 * if a view has a background drawable and you want to draw the scrollbars 11059 * inside the padding specified by the drawable, you can use 11060 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 11061 * appear at the edge of the view, ignoring the padding, then you can use 11062 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 11063 * @param style the style of the scrollbars. Should be one of 11064 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 11065 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 11066 * @see #SCROLLBARS_INSIDE_OVERLAY 11067 * @see #SCROLLBARS_INSIDE_INSET 11068 * @see #SCROLLBARS_OUTSIDE_OVERLAY 11069 * @see #SCROLLBARS_OUTSIDE_INSET 11070 * 11071 * @attr ref android.R.styleable#View_scrollbarStyle 11072 */ 11073 public void setScrollBarStyle(int style) { 11074 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 11075 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 11076 computeOpaqueFlags(); 11077 resolvePadding(); 11078 } 11079 } 11080 11081 /** 11082 * <p>Returns the current scrollbar style.</p> 11083 * @return the current scrollbar style 11084 * @see #SCROLLBARS_INSIDE_OVERLAY 11085 * @see #SCROLLBARS_INSIDE_INSET 11086 * @see #SCROLLBARS_OUTSIDE_OVERLAY 11087 * @see #SCROLLBARS_OUTSIDE_INSET 11088 * 11089 * @attr ref android.R.styleable#View_scrollbarStyle 11090 */ 11091 @ViewDebug.ExportedProperty(mapping = { 11092 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 11093 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 11094 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 11095 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 11096 }) 11097 public int getScrollBarStyle() { 11098 return mViewFlags & SCROLLBARS_STYLE_MASK; 11099 } 11100 11101 /** 11102 * <p>Compute the horizontal range that the horizontal scrollbar 11103 * represents.</p> 11104 * 11105 * <p>The range is expressed in arbitrary units that must be the same as the 11106 * units used by {@link #computeHorizontalScrollExtent()} and 11107 * {@link #computeHorizontalScrollOffset()}.</p> 11108 * 11109 * <p>The default range is the drawing width of this view.</p> 11110 * 11111 * @return the total horizontal range represented by the horizontal 11112 * scrollbar 11113 * 11114 * @see #computeHorizontalScrollExtent() 11115 * @see #computeHorizontalScrollOffset() 11116 * @see android.widget.ScrollBarDrawable 11117 */ 11118 protected int computeHorizontalScrollRange() { 11119 return getWidth(); 11120 } 11121 11122 /** 11123 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 11124 * within the horizontal range. This value is used to compute the position 11125 * of the thumb within the scrollbar's track.</p> 11126 * 11127 * <p>The range is expressed in arbitrary units that must be the same as the 11128 * units used by {@link #computeHorizontalScrollRange()} and 11129 * {@link #computeHorizontalScrollExtent()}.</p> 11130 * 11131 * <p>The default offset is the scroll offset of this view.</p> 11132 * 11133 * @return the horizontal offset of the scrollbar's thumb 11134 * 11135 * @see #computeHorizontalScrollRange() 11136 * @see #computeHorizontalScrollExtent() 11137 * @see android.widget.ScrollBarDrawable 11138 */ 11139 protected int computeHorizontalScrollOffset() { 11140 return mScrollX; 11141 } 11142 11143 /** 11144 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 11145 * within the horizontal range. This value is used to compute the length 11146 * of the thumb within the scrollbar's track.</p> 11147 * 11148 * <p>The range is expressed in arbitrary units that must be the same as the 11149 * units used by {@link #computeHorizontalScrollRange()} and 11150 * {@link #computeHorizontalScrollOffset()}.</p> 11151 * 11152 * <p>The default extent is the drawing width of this view.</p> 11153 * 11154 * @return the horizontal extent of the scrollbar's thumb 11155 * 11156 * @see #computeHorizontalScrollRange() 11157 * @see #computeHorizontalScrollOffset() 11158 * @see android.widget.ScrollBarDrawable 11159 */ 11160 protected int computeHorizontalScrollExtent() { 11161 return getWidth(); 11162 } 11163 11164 /** 11165 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 11166 * 11167 * <p>The range is expressed in arbitrary units that must be the same as the 11168 * units used by {@link #computeVerticalScrollExtent()} and 11169 * {@link #computeVerticalScrollOffset()}.</p> 11170 * 11171 * @return the total vertical range represented by the vertical scrollbar 11172 * 11173 * <p>The default range is the drawing height of this view.</p> 11174 * 11175 * @see #computeVerticalScrollExtent() 11176 * @see #computeVerticalScrollOffset() 11177 * @see android.widget.ScrollBarDrawable 11178 */ 11179 protected int computeVerticalScrollRange() { 11180 return getHeight(); 11181 } 11182 11183 /** 11184 * <p>Compute the vertical offset of the vertical scrollbar's thumb 11185 * within the horizontal range. This value is used to compute the position 11186 * of the thumb within the scrollbar's track.</p> 11187 * 11188 * <p>The range is expressed in arbitrary units that must be the same as the 11189 * units used by {@link #computeVerticalScrollRange()} and 11190 * {@link #computeVerticalScrollExtent()}.</p> 11191 * 11192 * <p>The default offset is the scroll offset of this view.</p> 11193 * 11194 * @return the vertical offset of the scrollbar's thumb 11195 * 11196 * @see #computeVerticalScrollRange() 11197 * @see #computeVerticalScrollExtent() 11198 * @see android.widget.ScrollBarDrawable 11199 */ 11200 protected int computeVerticalScrollOffset() { 11201 return mScrollY; 11202 } 11203 11204 /** 11205 * <p>Compute the vertical extent of the horizontal scrollbar's thumb 11206 * within the vertical range. This value is used to compute the length 11207 * of the thumb within the scrollbar's track.</p> 11208 * 11209 * <p>The range is expressed in arbitrary units that must be the same as the 11210 * units used by {@link #computeVerticalScrollRange()} and 11211 * {@link #computeVerticalScrollOffset()}.</p> 11212 * 11213 * <p>The default extent is the drawing height of this view.</p> 11214 * 11215 * @return the vertical extent of the scrollbar's thumb 11216 * 11217 * @see #computeVerticalScrollRange() 11218 * @see #computeVerticalScrollOffset() 11219 * @see android.widget.ScrollBarDrawable 11220 */ 11221 protected int computeVerticalScrollExtent() { 11222 return getHeight(); 11223 } 11224 11225 /** 11226 * Check if this view can be scrolled horizontally in a certain direction. 11227 * 11228 * @param direction Negative to check scrolling left, positive to check scrolling right. 11229 * @return true if this view can be scrolled in the specified direction, false otherwise. 11230 */ 11231 public boolean canScrollHorizontally(int direction) { 11232 final int offset = computeHorizontalScrollOffset(); 11233 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 11234 if (range == 0) return false; 11235 if (direction < 0) { 11236 return offset > 0; 11237 } else { 11238 return offset < range - 1; 11239 } 11240 } 11241 11242 /** 11243 * Check if this view can be scrolled vertically in a certain direction. 11244 * 11245 * @param direction Negative to check scrolling up, positive to check scrolling down. 11246 * @return true if this view can be scrolled in the specified direction, false otherwise. 11247 */ 11248 public boolean canScrollVertically(int direction) { 11249 final int offset = computeVerticalScrollOffset(); 11250 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 11251 if (range == 0) return false; 11252 if (direction < 0) { 11253 return offset > 0; 11254 } else { 11255 return offset < range - 1; 11256 } 11257 } 11258 11259 /** 11260 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 11261 * scrollbars are painted only if they have been awakened first.</p> 11262 * 11263 * @param canvas the canvas on which to draw the scrollbars 11264 * 11265 * @see #awakenScrollBars(int) 11266 */ 11267 protected final void onDrawScrollBars(Canvas canvas) { 11268 // scrollbars are drawn only when the animation is running 11269 final ScrollabilityCache cache = mScrollCache; 11270 if (cache != null) { 11271 11272 int state = cache.state; 11273 11274 if (state == ScrollabilityCache.OFF) { 11275 return; 11276 } 11277 11278 boolean invalidate = false; 11279 11280 if (state == ScrollabilityCache.FADING) { 11281 // We're fading -- get our fade interpolation 11282 if (cache.interpolatorValues == null) { 11283 cache.interpolatorValues = new float[1]; 11284 } 11285 11286 float[] values = cache.interpolatorValues; 11287 11288 // Stops the animation if we're done 11289 if (cache.scrollBarInterpolator.timeToValues(values) == 11290 Interpolator.Result.FREEZE_END) { 11291 cache.state = ScrollabilityCache.OFF; 11292 } else { 11293 cache.scrollBar.setAlpha(Math.round(values[0])); 11294 } 11295 11296 // This will make the scroll bars inval themselves after 11297 // drawing. We only want this when we're fading so that 11298 // we prevent excessive redraws 11299 invalidate = true; 11300 } else { 11301 // We're just on -- but we may have been fading before so 11302 // reset alpha 11303 cache.scrollBar.setAlpha(255); 11304 } 11305 11306 11307 final int viewFlags = mViewFlags; 11308 11309 final boolean drawHorizontalScrollBar = 11310 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 11311 final boolean drawVerticalScrollBar = 11312 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 11313 && !isVerticalScrollBarHidden(); 11314 11315 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 11316 final int width = mRight - mLeft; 11317 final int height = mBottom - mTop; 11318 11319 final ScrollBarDrawable scrollBar = cache.scrollBar; 11320 11321 final int scrollX = mScrollX; 11322 final int scrollY = mScrollY; 11323 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 11324 11325 int left, top, right, bottom; 11326 11327 if (drawHorizontalScrollBar) { 11328 int size = scrollBar.getSize(false); 11329 if (size <= 0) { 11330 size = cache.scrollBarSize; 11331 } 11332 11333 scrollBar.setParameters(computeHorizontalScrollRange(), 11334 computeHorizontalScrollOffset(), 11335 computeHorizontalScrollExtent(), false); 11336 final int verticalScrollBarGap = drawVerticalScrollBar ? 11337 getVerticalScrollbarWidth() : 0; 11338 top = scrollY + height - size - (mUserPaddingBottom & inside); 11339 left = scrollX + (mPaddingLeft & inside); 11340 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 11341 bottom = top + size; 11342 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 11343 if (invalidate) { 11344 invalidate(left, top, right, bottom); 11345 } 11346 } 11347 11348 if (drawVerticalScrollBar) { 11349 int size = scrollBar.getSize(true); 11350 if (size <= 0) { 11351 size = cache.scrollBarSize; 11352 } 11353 11354 scrollBar.setParameters(computeVerticalScrollRange(), 11355 computeVerticalScrollOffset(), 11356 computeVerticalScrollExtent(), true); 11357 int verticalScrollbarPosition = mVerticalScrollbarPosition; 11358 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 11359 verticalScrollbarPosition = isLayoutRtl() ? 11360 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 11361 } 11362 switch (verticalScrollbarPosition) { 11363 default: 11364 case SCROLLBAR_POSITION_RIGHT: 11365 left = scrollX + width - size - (mUserPaddingRight & inside); 11366 break; 11367 case SCROLLBAR_POSITION_LEFT: 11368 left = scrollX + (mUserPaddingLeft & inside); 11369 break; 11370 } 11371 top = scrollY + (mPaddingTop & inside); 11372 right = left + size; 11373 bottom = scrollY + height - (mUserPaddingBottom & inside); 11374 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 11375 if (invalidate) { 11376 invalidate(left, top, right, bottom); 11377 } 11378 } 11379 } 11380 } 11381 } 11382 11383 /** 11384 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 11385 * FastScroller is visible. 11386 * @return whether to temporarily hide the vertical scrollbar 11387 * @hide 11388 */ 11389 protected boolean isVerticalScrollBarHidden() { 11390 return false; 11391 } 11392 11393 /** 11394 * <p>Draw the horizontal scrollbar if 11395 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 11396 * 11397 * @param canvas the canvas on which to draw the scrollbar 11398 * @param scrollBar the scrollbar's drawable 11399 * 11400 * @see #isHorizontalScrollBarEnabled() 11401 * @see #computeHorizontalScrollRange() 11402 * @see #computeHorizontalScrollExtent() 11403 * @see #computeHorizontalScrollOffset() 11404 * @see android.widget.ScrollBarDrawable 11405 * @hide 11406 */ 11407 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 11408 int l, int t, int r, int b) { 11409 scrollBar.setBounds(l, t, r, b); 11410 scrollBar.draw(canvas); 11411 } 11412 11413 /** 11414 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 11415 * returns true.</p> 11416 * 11417 * @param canvas the canvas on which to draw the scrollbar 11418 * @param scrollBar the scrollbar's drawable 11419 * 11420 * @see #isVerticalScrollBarEnabled() 11421 * @see #computeVerticalScrollRange() 11422 * @see #computeVerticalScrollExtent() 11423 * @see #computeVerticalScrollOffset() 11424 * @see android.widget.ScrollBarDrawable 11425 * @hide 11426 */ 11427 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 11428 int l, int t, int r, int b) { 11429 scrollBar.setBounds(l, t, r, b); 11430 scrollBar.draw(canvas); 11431 } 11432 11433 /** 11434 * Implement this to do your drawing. 11435 * 11436 * @param canvas the canvas on which the background will be drawn 11437 */ 11438 protected void onDraw(Canvas canvas) { 11439 } 11440 11441 /* 11442 * Caller is responsible for calling requestLayout if necessary. 11443 * (This allows addViewInLayout to not request a new layout.) 11444 */ 11445 void assignParent(ViewParent parent) { 11446 if (mParent == null) { 11447 mParent = parent; 11448 } else if (parent == null) { 11449 mParent = null; 11450 } else { 11451 throw new RuntimeException("view " + this + " being added, but" 11452 + " it already has a parent"); 11453 } 11454 } 11455 11456 /** 11457 * This is called when the view is attached to a window. At this point it 11458 * has a Surface and will start drawing. Note that this function is 11459 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 11460 * however it may be called any time before the first onDraw -- including 11461 * before or after {@link #onMeasure(int, int)}. 11462 * 11463 * @see #onDetachedFromWindow() 11464 */ 11465 protected void onAttachedToWindow() { 11466 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 11467 mParent.requestTransparentRegion(this); 11468 } 11469 11470 if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 11471 initialAwakenScrollBars(); 11472 mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 11473 } 11474 11475 jumpDrawablesToCurrentState(); 11476 11477 resolveRtlProperties(); 11478 // Notify changes 11479 onRtlPropertiesChanged(); 11480 11481 clearAccessibilityFocus(); 11482 if (isFocused()) { 11483 InputMethodManager imm = InputMethodManager.peekInstance(); 11484 imm.focusIn(this); 11485 } 11486 11487 if (mAttachInfo != null && mDisplayList != null) { 11488 mAttachInfo.mViewRootImpl.dequeueDisplayList(mDisplayList); 11489 } 11490 } 11491 11492 /** 11493 * Resolve all RTL related properties 11494 */ 11495 void resolveRtlProperties() { 11496 // Order is important here: LayoutDirection MUST be resolved first... 11497 resolveLayoutDirection(); 11498 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 11499 resolveTextDirection(); 11500 resolveTextAlignment(); 11501 resolvePadding(); 11502 resolveLayoutParams(); 11503 resolveDrawables(); 11504 } 11505 11506 // Reset resolution of all RTL related properties 11507 void resetRtlProperties() { 11508 resetResolvedLayoutDirection(); 11509 resetResolvedTextDirection(); 11510 resetResolvedTextAlignment(); 11511 resetResolvedPadding(); 11512 } 11513 11514 /** 11515 * @see #onScreenStateChanged(int) 11516 */ 11517 void dispatchScreenStateChanged(int screenState) { 11518 onScreenStateChanged(screenState); 11519 } 11520 11521 /** 11522 * This method is called whenever the state of the screen this view is 11523 * attached to changes. A state change will usually occurs when the screen 11524 * turns on or off (whether it happens automatically or the user does it 11525 * manually.) 11526 * 11527 * @param screenState The new state of the screen. Can be either 11528 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 11529 */ 11530 public void onScreenStateChanged(int screenState) { 11531 } 11532 11533 /** 11534 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 11535 */ 11536 private boolean hasRtlSupport() { 11537 return mContext.getApplicationInfo().hasRtlSupport(); 11538 } 11539 11540 /** 11541 * Called when any RTL property (layout direction or text direction or text alignment) has 11542 * been changed. 11543 * 11544 * Subclasses need to override this method to take care of cached information that depends on the 11545 * resolved layout direction, or to inform child views that inherit their layout direction. 11546 * 11547 * The default implementation does nothing. 11548 */ 11549 public void onRtlPropertiesChanged() { 11550 } 11551 11552 /** 11553 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 11554 * that the parent directionality can and will be resolved before its children. 11555 * 11556 * @hide 11557 */ 11558 public void resolveLayoutDirection() { 11559 // Clear any previous layout direction resolution 11560 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 11561 11562 if (hasRtlSupport()) { 11563 // Set resolved depending on layout direction 11564 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 11565 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 11566 case LAYOUT_DIRECTION_INHERIT: 11567 // We cannot resolve yet. LTR is by default and let the resolution happen again 11568 // later to get the correct resolved value 11569 if (!canResolveLayoutDirection()) return; 11570 11571 ViewGroup viewGroup = ((ViewGroup) mParent); 11572 11573 // We cannot resolve yet on the parent too. LTR is by default and let the 11574 // resolution happen again later 11575 if (!viewGroup.canResolveLayoutDirection()) return; 11576 11577 if (viewGroup.getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 11578 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 11579 } 11580 break; 11581 case LAYOUT_DIRECTION_RTL: 11582 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 11583 break; 11584 case LAYOUT_DIRECTION_LOCALE: 11585 if((LAYOUT_DIRECTION_RTL == 11586 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) { 11587 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 11588 } 11589 break; 11590 default: 11591 // Nothing to do, LTR by default 11592 } 11593 } 11594 11595 // Set to resolved 11596 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 11597 } 11598 11599 /** 11600 * Check if layout direction resolution can be done. 11601 * 11602 * @return true if layout direction resolution can be done otherwise return false. 11603 * 11604 * @hide 11605 */ 11606 public boolean canResolveLayoutDirection() { 11607 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 11608 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 11609 case LAYOUT_DIRECTION_INHERIT: 11610 return (mParent != null) && (mParent instanceof ViewGroup); 11611 default: 11612 return true; 11613 } 11614 } 11615 11616 /** 11617 * Reset the resolved layout direction. 11618 * 11619 * @hide 11620 */ 11621 public void resetResolvedLayoutDirection() { 11622 // Reset the current resolved bits 11623 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 11624 } 11625 11626 /** 11627 * @hide 11628 */ 11629 public boolean isLayoutDirectionInherited() { 11630 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT); 11631 } 11632 11633 /** 11634 * Return if padding has been resolved 11635 * 11636 * @hide 11637 */ 11638 boolean isPaddingResolved() { 11639 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) != 0; 11640 } 11641 11642 /** 11643 * Resolve padding depending on layout direction. 11644 * 11645 * @hide 11646 */ 11647 public void resolvePadding() { 11648 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 11649 if (targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport()) { 11650 // Pre Jelly Bean MR1 case (compatibility mode) OR no RTL support case: 11651 // left / right padding are used if defined. If they are not defined and start / end 11652 // padding are defined (e.g. in Frameworks resources), then we use start / end and 11653 // resolve them as left / right (layout direction is not taken into account). 11654 if (mUserPaddingLeftInitial == UNDEFINED_PADDING && 11655 mUserPaddingStart != UNDEFINED_PADDING) { 11656 mUserPaddingLeft = mUserPaddingStart; 11657 } 11658 if (mUserPaddingRightInitial == UNDEFINED_PADDING && 11659 mUserPaddingEnd != UNDEFINED_PADDING) { 11660 mUserPaddingRight = mUserPaddingEnd; 11661 } 11662 11663 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 11664 11665 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, 11666 mUserPaddingBottom); 11667 } else { 11668 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 11669 // If start / end padding are defined, they will be resolved (hence overriding) to 11670 // left / right or right / left depending on the resolved layout direction. 11671 // If start / end padding are not defined, use the left / right ones. 11672 int resolvedLayoutDirection = getLayoutDirection(); 11673 // Set user padding to initial values ... 11674 mUserPaddingLeft = (mUserPaddingLeftInitial == UNDEFINED_PADDING) ? 11675 0 : mUserPaddingLeftInitial; 11676 mUserPaddingRight = (mUserPaddingRightInitial == UNDEFINED_PADDING) ? 11677 0 : mUserPaddingRightInitial; 11678 // ... then resolve it. 11679 switch (resolvedLayoutDirection) { 11680 case LAYOUT_DIRECTION_RTL: 11681 if (mUserPaddingStart != UNDEFINED_PADDING) { 11682 mUserPaddingRight = mUserPaddingStart; 11683 } 11684 if (mUserPaddingEnd != UNDEFINED_PADDING) { 11685 mUserPaddingLeft = mUserPaddingEnd; 11686 } 11687 break; 11688 case LAYOUT_DIRECTION_LTR: 11689 default: 11690 if (mUserPaddingStart != UNDEFINED_PADDING) { 11691 mUserPaddingLeft = mUserPaddingStart; 11692 } 11693 if (mUserPaddingEnd != UNDEFINED_PADDING) { 11694 mUserPaddingRight = mUserPaddingEnd; 11695 } 11696 } 11697 11698 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 11699 11700 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, 11701 mUserPaddingBottom); 11702 onPaddingChanged(resolvedLayoutDirection); 11703 } 11704 11705 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 11706 } 11707 11708 /** 11709 * Reset the resolved layout direction. 11710 * 11711 * @hide 11712 */ 11713 public void resetResolvedPadding() { 11714 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 11715 } 11716 11717 /** 11718 * Resolve padding depending on the layout direction. Subclasses that care about 11719 * padding resolution should override this method. The default implementation does 11720 * nothing. 11721 * 11722 * @param layoutDirection the direction of the layout 11723 * 11724 * @see #LAYOUT_DIRECTION_LTR 11725 * @see #LAYOUT_DIRECTION_RTL 11726 */ 11727 public void onPaddingChanged(int layoutDirection) { 11728 } 11729 11730 /** 11731 * This is called when the view is detached from a window. At this point it 11732 * no longer has a surface for drawing. 11733 * 11734 * @see #onAttachedToWindow() 11735 */ 11736 protected void onDetachedFromWindow() { 11737 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 11738 11739 removeUnsetPressCallback(); 11740 removeLongPressCallback(); 11741 removePerformClickCallback(); 11742 removeSendViewScrolledAccessibilityEventCallback(); 11743 11744 destroyDrawingCache(); 11745 11746 destroyLayer(false); 11747 11748 if (mAttachInfo != null) { 11749 if (mDisplayList != null) { 11750 mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList); 11751 } 11752 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 11753 } else { 11754 // Should never happen 11755 clearDisplayList(); 11756 } 11757 11758 mCurrentAnimation = null; 11759 11760 resetRtlProperties(); 11761 onRtlPropertiesChanged(); 11762 resetAccessibilityStateChanged(); 11763 } 11764 11765 /** 11766 * @return The number of times this view has been attached to a window 11767 */ 11768 protected int getWindowAttachCount() { 11769 return mWindowAttachCount; 11770 } 11771 11772 /** 11773 * Retrieve a unique token identifying the window this view is attached to. 11774 * @return Return the window's token for use in 11775 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 11776 */ 11777 public IBinder getWindowToken() { 11778 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 11779 } 11780 11781 /** 11782 * Retrieve a unique token identifying the top-level "real" window of 11783 * the window that this view is attached to. That is, this is like 11784 * {@link #getWindowToken}, except if the window this view in is a panel 11785 * window (attached to another containing window), then the token of 11786 * the containing window is returned instead. 11787 * 11788 * @return Returns the associated window token, either 11789 * {@link #getWindowToken()} or the containing window's token. 11790 */ 11791 public IBinder getApplicationWindowToken() { 11792 AttachInfo ai = mAttachInfo; 11793 if (ai != null) { 11794 IBinder appWindowToken = ai.mPanelParentWindowToken; 11795 if (appWindowToken == null) { 11796 appWindowToken = ai.mWindowToken; 11797 } 11798 return appWindowToken; 11799 } 11800 return null; 11801 } 11802 11803 /** 11804 * Gets the logical display to which the view's window has been attached. 11805 * 11806 * @return The logical display, or null if the view is not currently attached to a window. 11807 */ 11808 public Display getDisplay() { 11809 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 11810 } 11811 11812 /** 11813 * Retrieve private session object this view hierarchy is using to 11814 * communicate with the window manager. 11815 * @return the session object to communicate with the window manager 11816 */ 11817 /*package*/ IWindowSession getWindowSession() { 11818 return mAttachInfo != null ? mAttachInfo.mSession : null; 11819 } 11820 11821 /** 11822 * @param info the {@link android.view.View.AttachInfo} to associated with 11823 * this view 11824 */ 11825 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 11826 //System.out.println("Attached! " + this); 11827 mAttachInfo = info; 11828 mWindowAttachCount++; 11829 // We will need to evaluate the drawable state at least once. 11830 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 11831 if (mFloatingTreeObserver != null) { 11832 info.mTreeObserver.merge(mFloatingTreeObserver); 11833 mFloatingTreeObserver = null; 11834 } 11835 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 11836 mAttachInfo.mScrollContainers.add(this); 11837 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 11838 } 11839 performCollectViewAttributes(mAttachInfo, visibility); 11840 onAttachedToWindow(); 11841 11842 ListenerInfo li = mListenerInfo; 11843 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 11844 li != null ? li.mOnAttachStateChangeListeners : null; 11845 if (listeners != null && listeners.size() > 0) { 11846 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 11847 // perform the dispatching. The iterator is a safe guard against listeners that 11848 // could mutate the list by calling the various add/remove methods. This prevents 11849 // the array from being modified while we iterate it. 11850 for (OnAttachStateChangeListener listener : listeners) { 11851 listener.onViewAttachedToWindow(this); 11852 } 11853 } 11854 11855 int vis = info.mWindowVisibility; 11856 if (vis != GONE) { 11857 onWindowVisibilityChanged(vis); 11858 } 11859 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 11860 // If nobody has evaluated the drawable state yet, then do it now. 11861 refreshDrawableState(); 11862 } 11863 needGlobalAttributesUpdate(false); 11864 } 11865 11866 void dispatchDetachedFromWindow() { 11867 AttachInfo info = mAttachInfo; 11868 if (info != null) { 11869 int vis = info.mWindowVisibility; 11870 if (vis != GONE) { 11871 onWindowVisibilityChanged(GONE); 11872 } 11873 } 11874 11875 onDetachedFromWindow(); 11876 11877 ListenerInfo li = mListenerInfo; 11878 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 11879 li != null ? li.mOnAttachStateChangeListeners : null; 11880 if (listeners != null && listeners.size() > 0) { 11881 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 11882 // perform the dispatching. The iterator is a safe guard against listeners that 11883 // could mutate the list by calling the various add/remove methods. This prevents 11884 // the array from being modified while we iterate it. 11885 for (OnAttachStateChangeListener listener : listeners) { 11886 listener.onViewDetachedFromWindow(this); 11887 } 11888 } 11889 11890 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 11891 mAttachInfo.mScrollContainers.remove(this); 11892 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 11893 } 11894 11895 mAttachInfo = null; 11896 } 11897 11898 /** 11899 * Store this view hierarchy's frozen state into the given container. 11900 * 11901 * @param container The SparseArray in which to save the view's state. 11902 * 11903 * @see #restoreHierarchyState(android.util.SparseArray) 11904 * @see #dispatchSaveInstanceState(android.util.SparseArray) 11905 * @see #onSaveInstanceState() 11906 */ 11907 public void saveHierarchyState(SparseArray<Parcelable> container) { 11908 dispatchSaveInstanceState(container); 11909 } 11910 11911 /** 11912 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 11913 * this view and its children. May be overridden to modify how freezing happens to a 11914 * view's children; for example, some views may want to not store state for their children. 11915 * 11916 * @param container The SparseArray in which to save the view's state. 11917 * 11918 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 11919 * @see #saveHierarchyState(android.util.SparseArray) 11920 * @see #onSaveInstanceState() 11921 */ 11922 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 11923 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 11924 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 11925 Parcelable state = onSaveInstanceState(); 11926 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 11927 throw new IllegalStateException( 11928 "Derived class did not call super.onSaveInstanceState()"); 11929 } 11930 if (state != null) { 11931 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 11932 // + ": " + state); 11933 container.put(mID, state); 11934 } 11935 } 11936 } 11937 11938 /** 11939 * Hook allowing a view to generate a representation of its internal state 11940 * that can later be used to create a new instance with that same state. 11941 * This state should only contain information that is not persistent or can 11942 * not be reconstructed later. For example, you will never store your 11943 * current position on screen because that will be computed again when a 11944 * new instance of the view is placed in its view hierarchy. 11945 * <p> 11946 * Some examples of things you may store here: the current cursor position 11947 * in a text view (but usually not the text itself since that is stored in a 11948 * content provider or other persistent storage), the currently selected 11949 * item in a list view. 11950 * 11951 * @return Returns a Parcelable object containing the view's current dynamic 11952 * state, or null if there is nothing interesting to save. The 11953 * default implementation returns null. 11954 * @see #onRestoreInstanceState(android.os.Parcelable) 11955 * @see #saveHierarchyState(android.util.SparseArray) 11956 * @see #dispatchSaveInstanceState(android.util.SparseArray) 11957 * @see #setSaveEnabled(boolean) 11958 */ 11959 protected Parcelable onSaveInstanceState() { 11960 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 11961 return BaseSavedState.EMPTY_STATE; 11962 } 11963 11964 /** 11965 * Restore this view hierarchy's frozen state from the given container. 11966 * 11967 * @param container The SparseArray which holds previously frozen states. 11968 * 11969 * @see #saveHierarchyState(android.util.SparseArray) 11970 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 11971 * @see #onRestoreInstanceState(android.os.Parcelable) 11972 */ 11973 public void restoreHierarchyState(SparseArray<Parcelable> container) { 11974 dispatchRestoreInstanceState(container); 11975 } 11976 11977 /** 11978 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 11979 * state for this view and its children. May be overridden to modify how restoring 11980 * happens to a view's children; for example, some views may want to not store state 11981 * for their children. 11982 * 11983 * @param container The SparseArray which holds previously saved state. 11984 * 11985 * @see #dispatchSaveInstanceState(android.util.SparseArray) 11986 * @see #restoreHierarchyState(android.util.SparseArray) 11987 * @see #onRestoreInstanceState(android.os.Parcelable) 11988 */ 11989 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 11990 if (mID != NO_ID) { 11991 Parcelable state = container.get(mID); 11992 if (state != null) { 11993 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 11994 // + ": " + state); 11995 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 11996 onRestoreInstanceState(state); 11997 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 11998 throw new IllegalStateException( 11999 "Derived class did not call super.onRestoreInstanceState()"); 12000 } 12001 } 12002 } 12003 } 12004 12005 /** 12006 * Hook allowing a view to re-apply a representation of its internal state that had previously 12007 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 12008 * null state. 12009 * 12010 * @param state The frozen state that had previously been returned by 12011 * {@link #onSaveInstanceState}. 12012 * 12013 * @see #onSaveInstanceState() 12014 * @see #restoreHierarchyState(android.util.SparseArray) 12015 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 12016 */ 12017 protected void onRestoreInstanceState(Parcelable state) { 12018 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 12019 if (state != BaseSavedState.EMPTY_STATE && state != null) { 12020 throw new IllegalArgumentException("Wrong state class, expecting View State but " 12021 + "received " + state.getClass().toString() + " instead. This usually happens " 12022 + "when two views of different type have the same id in the same hierarchy. " 12023 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 12024 + "other views do not use the same id."); 12025 } 12026 } 12027 12028 /** 12029 * <p>Return the time at which the drawing of the view hierarchy started.</p> 12030 * 12031 * @return the drawing start time in milliseconds 12032 */ 12033 public long getDrawingTime() { 12034 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 12035 } 12036 12037 /** 12038 * <p>Enables or disables the duplication of the parent's state into this view. When 12039 * duplication is enabled, this view gets its drawable state from its parent rather 12040 * than from its own internal properties.</p> 12041 * 12042 * <p>Note: in the current implementation, setting this property to true after the 12043 * view was added to a ViewGroup might have no effect at all. This property should 12044 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 12045 * 12046 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 12047 * property is enabled, an exception will be thrown.</p> 12048 * 12049 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 12050 * parent, these states should not be affected by this method.</p> 12051 * 12052 * @param enabled True to enable duplication of the parent's drawable state, false 12053 * to disable it. 12054 * 12055 * @see #getDrawableState() 12056 * @see #isDuplicateParentStateEnabled() 12057 */ 12058 public void setDuplicateParentStateEnabled(boolean enabled) { 12059 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 12060 } 12061 12062 /** 12063 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 12064 * 12065 * @return True if this view's drawable state is duplicated from the parent, 12066 * false otherwise 12067 * 12068 * @see #getDrawableState() 12069 * @see #setDuplicateParentStateEnabled(boolean) 12070 */ 12071 public boolean isDuplicateParentStateEnabled() { 12072 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 12073 } 12074 12075 /** 12076 * <p>Specifies the type of layer backing this view. The layer can be 12077 * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or 12078 * {@link #LAYER_TYPE_HARDWARE hardware}.</p> 12079 * 12080 * <p>A layer is associated with an optional {@link android.graphics.Paint} 12081 * instance that controls how the layer is composed on screen. The following 12082 * properties of the paint are taken into account when composing the layer:</p> 12083 * <ul> 12084 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 12085 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 12086 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 12087 * </ul> 12088 * 12089 * <p>If this view has an alpha value set to < 1.0 by calling 12090 * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by 12091 * this view's alpha value. Calling {@link #setAlpha(float)} is therefore 12092 * equivalent to setting a hardware layer on this view and providing a paint with 12093 * the desired alpha value.</p> 12094 * 12095 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled}, 12096 * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware} 12097 * for more information on when and how to use layers.</p> 12098 * 12099 * @param layerType The type of layer to use with this view, must be one of 12100 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 12101 * {@link #LAYER_TYPE_HARDWARE} 12102 * @param paint The paint used to compose the layer. This argument is optional 12103 * and can be null. It is ignored when the layer type is 12104 * {@link #LAYER_TYPE_NONE} 12105 * 12106 * @see #getLayerType() 12107 * @see #LAYER_TYPE_NONE 12108 * @see #LAYER_TYPE_SOFTWARE 12109 * @see #LAYER_TYPE_HARDWARE 12110 * @see #setAlpha(float) 12111 * 12112 * @attr ref android.R.styleable#View_layerType 12113 */ 12114 public void setLayerType(int layerType, Paint paint) { 12115 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 12116 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 12117 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 12118 } 12119 12120 if (layerType == mLayerType) { 12121 if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) { 12122 mLayerPaint = paint == null ? new Paint() : paint; 12123 invalidateParentCaches(); 12124 invalidate(true); 12125 } 12126 return; 12127 } 12128 12129 // Destroy any previous software drawing cache if needed 12130 switch (mLayerType) { 12131 case LAYER_TYPE_HARDWARE: 12132 destroyLayer(false); 12133 // fall through - non-accelerated views may use software layer mechanism instead 12134 case LAYER_TYPE_SOFTWARE: 12135 destroyDrawingCache(); 12136 break; 12137 default: 12138 break; 12139 } 12140 12141 mLayerType = layerType; 12142 final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE; 12143 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 12144 mLocalDirtyRect = layerDisabled ? null : new Rect(); 12145 12146 invalidateParentCaches(); 12147 invalidate(true); 12148 } 12149 12150 /** 12151 * Updates the {@link Paint} object used with the current layer (used only if the current 12152 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 12153 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 12154 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 12155 * ensure that the view gets redrawn immediately. 12156 * 12157 * <p>A layer is associated with an optional {@link android.graphics.Paint} 12158 * instance that controls how the layer is composed on screen. The following 12159 * properties of the paint are taken into account when composing the layer:</p> 12160 * <ul> 12161 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 12162 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 12163 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 12164 * </ul> 12165 * 12166 * <p>If this view has an alpha value set to < 1.0 by calling 12167 * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by 12168 * this view's alpha value. Calling {@link #setAlpha(float)} is therefore 12169 * equivalent to setting a hardware layer on this view and providing a paint with 12170 * the desired alpha value.</p> 12171 * 12172 * @param paint The paint used to compose the layer. This argument is optional 12173 * and can be null. It is ignored when the layer type is 12174 * {@link #LAYER_TYPE_NONE} 12175 * 12176 * @see #setLayerType(int, android.graphics.Paint) 12177 */ 12178 public void setLayerPaint(Paint paint) { 12179 int layerType = getLayerType(); 12180 if (layerType != LAYER_TYPE_NONE) { 12181 mLayerPaint = paint == null ? new Paint() : paint; 12182 if (layerType == LAYER_TYPE_HARDWARE) { 12183 HardwareLayer layer = getHardwareLayer(); 12184 if (layer != null) { 12185 layer.setLayerPaint(paint); 12186 } 12187 invalidateViewProperty(false, false); 12188 } else { 12189 invalidate(); 12190 } 12191 } 12192 } 12193 12194 /** 12195 * Indicates whether this view has a static layer. A view with layer type 12196 * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are 12197 * dynamic. 12198 */ 12199 boolean hasStaticLayer() { 12200 return true; 12201 } 12202 12203 /** 12204 * Indicates what type of layer is currently associated with this view. By default 12205 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 12206 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 12207 * for more information on the different types of layers. 12208 * 12209 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 12210 * {@link #LAYER_TYPE_HARDWARE} 12211 * 12212 * @see #setLayerType(int, android.graphics.Paint) 12213 * @see #buildLayer() 12214 * @see #LAYER_TYPE_NONE 12215 * @see #LAYER_TYPE_SOFTWARE 12216 * @see #LAYER_TYPE_HARDWARE 12217 */ 12218 public int getLayerType() { 12219 return mLayerType; 12220 } 12221 12222 /** 12223 * Forces this view's layer to be created and this view to be rendered 12224 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 12225 * invoking this method will have no effect. 12226 * 12227 * This method can for instance be used to render a view into its layer before 12228 * starting an animation. If this view is complex, rendering into the layer 12229 * before starting the animation will avoid skipping frames. 12230 * 12231 * @throws IllegalStateException If this view is not attached to a window 12232 * 12233 * @see #setLayerType(int, android.graphics.Paint) 12234 */ 12235 public void buildLayer() { 12236 if (mLayerType == LAYER_TYPE_NONE) return; 12237 12238 if (mAttachInfo == null) { 12239 throw new IllegalStateException("This view must be attached to a window first"); 12240 } 12241 12242 switch (mLayerType) { 12243 case LAYER_TYPE_HARDWARE: 12244 if (mAttachInfo.mHardwareRenderer != null && 12245 mAttachInfo.mHardwareRenderer.isEnabled() && 12246 mAttachInfo.mHardwareRenderer.validate()) { 12247 getHardwareLayer(); 12248 } 12249 break; 12250 case LAYER_TYPE_SOFTWARE: 12251 buildDrawingCache(true); 12252 break; 12253 } 12254 } 12255 12256 /** 12257 * <p>Returns a hardware layer that can be used to draw this view again 12258 * without executing its draw method.</p> 12259 * 12260 * @return A HardwareLayer ready to render, or null if an error occurred. 12261 */ 12262 HardwareLayer getHardwareLayer() { 12263 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null || 12264 !mAttachInfo.mHardwareRenderer.isEnabled()) { 12265 return null; 12266 } 12267 12268 if (!mAttachInfo.mHardwareRenderer.validate()) return null; 12269 12270 final int width = mRight - mLeft; 12271 final int height = mBottom - mTop; 12272 12273 if (width == 0 || height == 0) { 12274 return null; 12275 } 12276 12277 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) { 12278 if (mHardwareLayer == null) { 12279 mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer( 12280 width, height, isOpaque()); 12281 mLocalDirtyRect.set(0, 0, width, height); 12282 } else { 12283 if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) { 12284 if (mHardwareLayer.resize(width, height)) { 12285 mLocalDirtyRect.set(0, 0, width, height); 12286 } 12287 } 12288 12289 // This should not be necessary but applications that change 12290 // the parameters of their background drawable without calling 12291 // this.setBackground(Drawable) can leave the view in a bad state 12292 // (for instance isOpaque() returns true, but the background is 12293 // not opaque.) 12294 computeOpaqueFlags(); 12295 12296 final boolean opaque = isOpaque(); 12297 if (mHardwareLayer.isValid() && mHardwareLayer.isOpaque() != opaque) { 12298 mHardwareLayer.setOpaque(opaque); 12299 mLocalDirtyRect.set(0, 0, width, height); 12300 } 12301 } 12302 12303 // The layer is not valid if the underlying GPU resources cannot be allocated 12304 if (!mHardwareLayer.isValid()) { 12305 return null; 12306 } 12307 12308 mHardwareLayer.setLayerPaint(mLayerPaint); 12309 mHardwareLayer.redrawLater(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect); 12310 ViewRootImpl viewRoot = getViewRootImpl(); 12311 if (viewRoot != null) viewRoot.pushHardwareLayerUpdate(mHardwareLayer); 12312 12313 mLocalDirtyRect.setEmpty(); 12314 } 12315 12316 return mHardwareLayer; 12317 } 12318 12319 /** 12320 * Destroys this View's hardware layer if possible. 12321 * 12322 * @return True if the layer was destroyed, false otherwise. 12323 * 12324 * @see #setLayerType(int, android.graphics.Paint) 12325 * @see #LAYER_TYPE_HARDWARE 12326 */ 12327 boolean destroyLayer(boolean valid) { 12328 if (mHardwareLayer != null) { 12329 AttachInfo info = mAttachInfo; 12330 if (info != null && info.mHardwareRenderer != null && 12331 info.mHardwareRenderer.isEnabled() && 12332 (valid || info.mHardwareRenderer.validate())) { 12333 mHardwareLayer.destroy(); 12334 mHardwareLayer = null; 12335 12336 invalidate(true); 12337 invalidateParentCaches(); 12338 } 12339 return true; 12340 } 12341 return false; 12342 } 12343 12344 /** 12345 * Destroys all hardware rendering resources. This method is invoked 12346 * when the system needs to reclaim resources. Upon execution of this 12347 * method, you should free any OpenGL resources created by the view. 12348 * 12349 * Note: you <strong>must</strong> call 12350 * <code>super.destroyHardwareResources()</code> when overriding 12351 * this method. 12352 * 12353 * @hide 12354 */ 12355 protected void destroyHardwareResources() { 12356 destroyLayer(true); 12357 } 12358 12359 /** 12360 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 12361 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 12362 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 12363 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 12364 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 12365 * null.</p> 12366 * 12367 * <p>Enabling the drawing cache is similar to 12368 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 12369 * acceleration is turned off. When hardware acceleration is turned on, enabling the 12370 * drawing cache has no effect on rendering because the system uses a different mechanism 12371 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 12372 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 12373 * for information on how to enable software and hardware layers.</p> 12374 * 12375 * <p>This API can be used to manually generate 12376 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 12377 * {@link #getDrawingCache()}.</p> 12378 * 12379 * @param enabled true to enable the drawing cache, false otherwise 12380 * 12381 * @see #isDrawingCacheEnabled() 12382 * @see #getDrawingCache() 12383 * @see #buildDrawingCache() 12384 * @see #setLayerType(int, android.graphics.Paint) 12385 */ 12386 public void setDrawingCacheEnabled(boolean enabled) { 12387 mCachingFailed = false; 12388 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 12389 } 12390 12391 /** 12392 * <p>Indicates whether the drawing cache is enabled for this view.</p> 12393 * 12394 * @return true if the drawing cache is enabled 12395 * 12396 * @see #setDrawingCacheEnabled(boolean) 12397 * @see #getDrawingCache() 12398 */ 12399 @ViewDebug.ExportedProperty(category = "drawing") 12400 public boolean isDrawingCacheEnabled() { 12401 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 12402 } 12403 12404 /** 12405 * Debugging utility which recursively outputs the dirty state of a view and its 12406 * descendants. 12407 * 12408 * @hide 12409 */ 12410 @SuppressWarnings({"UnusedDeclaration"}) 12411 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 12412 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 12413 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 12414 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 12415 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 12416 if (clear) { 12417 mPrivateFlags &= clearMask; 12418 } 12419 if (this instanceof ViewGroup) { 12420 ViewGroup parent = (ViewGroup) this; 12421 final int count = parent.getChildCount(); 12422 for (int i = 0; i < count; i++) { 12423 final View child = parent.getChildAt(i); 12424 child.outputDirtyFlags(indent + " ", clear, clearMask); 12425 } 12426 } 12427 } 12428 12429 /** 12430 * This method is used by ViewGroup to cause its children to restore or recreate their 12431 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 12432 * to recreate its own display list, which would happen if it went through the normal 12433 * draw/dispatchDraw mechanisms. 12434 * 12435 * @hide 12436 */ 12437 protected void dispatchGetDisplayList() {} 12438 12439 /** 12440 * A view that is not attached or hardware accelerated cannot create a display list. 12441 * This method checks these conditions and returns the appropriate result. 12442 * 12443 * @return true if view has the ability to create a display list, false otherwise. 12444 * 12445 * @hide 12446 */ 12447 public boolean canHaveDisplayList() { 12448 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 12449 } 12450 12451 /** 12452 * @return The HardwareRenderer associated with that view or null if hardware rendering 12453 * is not supported or this this has not been attached to a window. 12454 * 12455 * @hide 12456 */ 12457 public HardwareRenderer getHardwareRenderer() { 12458 if (mAttachInfo != null) { 12459 return mAttachInfo.mHardwareRenderer; 12460 } 12461 return null; 12462 } 12463 12464 /** 12465 * Returns a DisplayList. If the incoming displayList is null, one will be created. 12466 * Otherwise, the same display list will be returned (after having been rendered into 12467 * along the way, depending on the invalidation state of the view). 12468 * 12469 * @param displayList The previous version of this displayList, could be null. 12470 * @param isLayer Whether the requester of the display list is a layer. If so, 12471 * the view will avoid creating a layer inside the resulting display list. 12472 * @return A new or reused DisplayList object. 12473 */ 12474 private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) { 12475 if (!canHaveDisplayList()) { 12476 return null; 12477 } 12478 12479 if (((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || 12480 displayList == null || !displayList.isValid() || 12481 (!isLayer && mRecreateDisplayList))) { 12482 // Don't need to recreate the display list, just need to tell our 12483 // children to restore/recreate theirs 12484 if (displayList != null && displayList.isValid() && 12485 !isLayer && !mRecreateDisplayList) { 12486 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 12487 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 12488 dispatchGetDisplayList(); 12489 12490 return displayList; 12491 } 12492 12493 if (!isLayer) { 12494 // If we got here, we're recreating it. Mark it as such to ensure that 12495 // we copy in child display lists into ours in drawChild() 12496 mRecreateDisplayList = true; 12497 } 12498 if (displayList == null) { 12499 final String name = getClass().getSimpleName(); 12500 displayList = mAttachInfo.mHardwareRenderer.createDisplayList(name); 12501 // If we're creating a new display list, make sure our parent gets invalidated 12502 // since they will need to recreate their display list to account for this 12503 // new child display list. 12504 invalidateParentCaches(); 12505 } 12506 12507 boolean caching = false; 12508 final HardwareCanvas canvas = displayList.start(); 12509 int width = mRight - mLeft; 12510 int height = mBottom - mTop; 12511 12512 try { 12513 canvas.setViewport(width, height); 12514 // The dirty rect should always be null for a display list 12515 canvas.onPreDraw(null); 12516 int layerType = getLayerType(); 12517 if (!isLayer && layerType != LAYER_TYPE_NONE) { 12518 if (layerType == LAYER_TYPE_HARDWARE) { 12519 final HardwareLayer layer = getHardwareLayer(); 12520 if (layer != null && layer.isValid()) { 12521 canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint); 12522 } else { 12523 canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint, 12524 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | 12525 Canvas.CLIP_TO_LAYER_SAVE_FLAG); 12526 } 12527 caching = true; 12528 } else { 12529 buildDrawingCache(true); 12530 Bitmap cache = getDrawingCache(true); 12531 if (cache != null) { 12532 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 12533 caching = true; 12534 } 12535 } 12536 } else { 12537 12538 computeScroll(); 12539 12540 canvas.translate(-mScrollX, -mScrollY); 12541 if (!isLayer) { 12542 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 12543 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 12544 } 12545 12546 // Fast path for layouts with no backgrounds 12547 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 12548 dispatchDraw(canvas); 12549 } else { 12550 draw(canvas); 12551 } 12552 } 12553 } finally { 12554 canvas.onPostDraw(); 12555 12556 displayList.end(); 12557 displayList.setCaching(caching); 12558 if (isLayer) { 12559 displayList.setLeftTopRightBottom(0, 0, width, height); 12560 } else { 12561 setDisplayListProperties(displayList); 12562 } 12563 } 12564 } else if (!isLayer) { 12565 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 12566 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 12567 } 12568 12569 return displayList; 12570 } 12571 12572 /** 12573 * Get the DisplayList for the HardwareLayer 12574 * 12575 * @param layer The HardwareLayer whose DisplayList we want 12576 * @return A DisplayList fopr the specified HardwareLayer 12577 */ 12578 private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) { 12579 DisplayList displayList = getDisplayList(layer.getDisplayList(), true); 12580 layer.setDisplayList(displayList); 12581 return displayList; 12582 } 12583 12584 12585 /** 12586 * <p>Returns a display list that can be used to draw this view again 12587 * without executing its draw method.</p> 12588 * 12589 * @return A DisplayList ready to replay, or null if caching is not enabled. 12590 * 12591 * @hide 12592 */ 12593 public DisplayList getDisplayList() { 12594 mDisplayList = getDisplayList(mDisplayList, false); 12595 return mDisplayList; 12596 } 12597 12598 private void clearDisplayList() { 12599 if (mDisplayList != null) { 12600 mDisplayList.invalidate(); 12601 mDisplayList.clear(); 12602 } 12603 } 12604 12605 /** 12606 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 12607 * 12608 * @return A non-scaled bitmap representing this view or null if cache is disabled. 12609 * 12610 * @see #getDrawingCache(boolean) 12611 */ 12612 public Bitmap getDrawingCache() { 12613 return getDrawingCache(false); 12614 } 12615 12616 /** 12617 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 12618 * is null when caching is disabled. If caching is enabled and the cache is not ready, 12619 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 12620 * draw from the cache when the cache is enabled. To benefit from the cache, you must 12621 * request the drawing cache by calling this method and draw it on screen if the 12622 * returned bitmap is not null.</p> 12623 * 12624 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 12625 * this method will create a bitmap of the same size as this view. Because this bitmap 12626 * will be drawn scaled by the parent ViewGroup, the result on screen might show 12627 * scaling artifacts. To avoid such artifacts, you should call this method by setting 12628 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 12629 * size than the view. This implies that your application must be able to handle this 12630 * size.</p> 12631 * 12632 * @param autoScale Indicates whether the generated bitmap should be scaled based on 12633 * the current density of the screen when the application is in compatibility 12634 * mode. 12635 * 12636 * @return A bitmap representing this view or null if cache is disabled. 12637 * 12638 * @see #setDrawingCacheEnabled(boolean) 12639 * @see #isDrawingCacheEnabled() 12640 * @see #buildDrawingCache(boolean) 12641 * @see #destroyDrawingCache() 12642 */ 12643 public Bitmap getDrawingCache(boolean autoScale) { 12644 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 12645 return null; 12646 } 12647 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 12648 buildDrawingCache(autoScale); 12649 } 12650 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 12651 } 12652 12653 /** 12654 * <p>Frees the resources used by the drawing cache. If you call 12655 * {@link #buildDrawingCache()} manually without calling 12656 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 12657 * should cleanup the cache with this method afterwards.</p> 12658 * 12659 * @see #setDrawingCacheEnabled(boolean) 12660 * @see #buildDrawingCache() 12661 * @see #getDrawingCache() 12662 */ 12663 public void destroyDrawingCache() { 12664 if (mDrawingCache != null) { 12665 mDrawingCache.recycle(); 12666 mDrawingCache = null; 12667 } 12668 if (mUnscaledDrawingCache != null) { 12669 mUnscaledDrawingCache.recycle(); 12670 mUnscaledDrawingCache = null; 12671 } 12672 } 12673 12674 /** 12675 * Setting a solid background color for the drawing cache's bitmaps will improve 12676 * performance and memory usage. Note, though that this should only be used if this 12677 * view will always be drawn on top of a solid color. 12678 * 12679 * @param color The background color to use for the drawing cache's bitmap 12680 * 12681 * @see #setDrawingCacheEnabled(boolean) 12682 * @see #buildDrawingCache() 12683 * @see #getDrawingCache() 12684 */ 12685 public void setDrawingCacheBackgroundColor(int color) { 12686 if (color != mDrawingCacheBackgroundColor) { 12687 mDrawingCacheBackgroundColor = color; 12688 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 12689 } 12690 } 12691 12692 /** 12693 * @see #setDrawingCacheBackgroundColor(int) 12694 * 12695 * @return The background color to used for the drawing cache's bitmap 12696 */ 12697 public int getDrawingCacheBackgroundColor() { 12698 return mDrawingCacheBackgroundColor; 12699 } 12700 12701 /** 12702 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 12703 * 12704 * @see #buildDrawingCache(boolean) 12705 */ 12706 public void buildDrawingCache() { 12707 buildDrawingCache(false); 12708 } 12709 12710 /** 12711 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 12712 * 12713 * <p>If you call {@link #buildDrawingCache()} manually without calling 12714 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 12715 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 12716 * 12717 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 12718 * this method will create a bitmap of the same size as this view. Because this bitmap 12719 * will be drawn scaled by the parent ViewGroup, the result on screen might show 12720 * scaling artifacts. To avoid such artifacts, you should call this method by setting 12721 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 12722 * size than the view. This implies that your application must be able to handle this 12723 * size.</p> 12724 * 12725 * <p>You should avoid calling this method when hardware acceleration is enabled. If 12726 * you do not need the drawing cache bitmap, calling this method will increase memory 12727 * usage and cause the view to be rendered in software once, thus negatively impacting 12728 * performance.</p> 12729 * 12730 * @see #getDrawingCache() 12731 * @see #destroyDrawingCache() 12732 */ 12733 public void buildDrawingCache(boolean autoScale) { 12734 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 12735 mDrawingCache == null : mUnscaledDrawingCache == null)) { 12736 mCachingFailed = false; 12737 12738 int width = mRight - mLeft; 12739 int height = mBottom - mTop; 12740 12741 final AttachInfo attachInfo = mAttachInfo; 12742 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 12743 12744 if (autoScale && scalingRequired) { 12745 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 12746 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 12747 } 12748 12749 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 12750 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 12751 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 12752 12753 final int projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 12754 final int drawingCacheSize = 12755 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 12756 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 12757 if (width > 0 && height > 0) { 12758 Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs " 12759 + projectedBitmapSize + " bytes, only " 12760 + drawingCacheSize + " available"); 12761 } 12762 destroyDrawingCache(); 12763 mCachingFailed = true; 12764 return; 12765 } 12766 12767 boolean clear = true; 12768 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 12769 12770 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 12771 Bitmap.Config quality; 12772 if (!opaque) { 12773 // Never pick ARGB_4444 because it looks awful 12774 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 12775 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 12776 case DRAWING_CACHE_QUALITY_AUTO: 12777 quality = Bitmap.Config.ARGB_8888; 12778 break; 12779 case DRAWING_CACHE_QUALITY_LOW: 12780 quality = Bitmap.Config.ARGB_8888; 12781 break; 12782 case DRAWING_CACHE_QUALITY_HIGH: 12783 quality = Bitmap.Config.ARGB_8888; 12784 break; 12785 default: 12786 quality = Bitmap.Config.ARGB_8888; 12787 break; 12788 } 12789 } else { 12790 // Optimization for translucent windows 12791 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 12792 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 12793 } 12794 12795 // Try to cleanup memory 12796 if (bitmap != null) bitmap.recycle(); 12797 12798 try { 12799 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 12800 width, height, quality); 12801 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 12802 if (autoScale) { 12803 mDrawingCache = bitmap; 12804 } else { 12805 mUnscaledDrawingCache = bitmap; 12806 } 12807 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 12808 } catch (OutOfMemoryError e) { 12809 // If there is not enough memory to create the bitmap cache, just 12810 // ignore the issue as bitmap caches are not required to draw the 12811 // view hierarchy 12812 if (autoScale) { 12813 mDrawingCache = null; 12814 } else { 12815 mUnscaledDrawingCache = null; 12816 } 12817 mCachingFailed = true; 12818 return; 12819 } 12820 12821 clear = drawingCacheBackgroundColor != 0; 12822 } 12823 12824 Canvas canvas; 12825 if (attachInfo != null) { 12826 canvas = attachInfo.mCanvas; 12827 if (canvas == null) { 12828 canvas = new Canvas(); 12829 } 12830 canvas.setBitmap(bitmap); 12831 // Temporarily clobber the cached Canvas in case one of our children 12832 // is also using a drawing cache. Without this, the children would 12833 // steal the canvas by attaching their own bitmap to it and bad, bad 12834 // thing would happen (invisible views, corrupted drawings, etc.) 12835 attachInfo.mCanvas = null; 12836 } else { 12837 // This case should hopefully never or seldom happen 12838 canvas = new Canvas(bitmap); 12839 } 12840 12841 if (clear) { 12842 bitmap.eraseColor(drawingCacheBackgroundColor); 12843 } 12844 12845 computeScroll(); 12846 final int restoreCount = canvas.save(); 12847 12848 if (autoScale && scalingRequired) { 12849 final float scale = attachInfo.mApplicationScale; 12850 canvas.scale(scale, scale); 12851 } 12852 12853 canvas.translate(-mScrollX, -mScrollY); 12854 12855 mPrivateFlags |= PFLAG_DRAWN; 12856 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 12857 mLayerType != LAYER_TYPE_NONE) { 12858 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 12859 } 12860 12861 // Fast path for layouts with no backgrounds 12862 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 12863 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 12864 dispatchDraw(canvas); 12865 } else { 12866 draw(canvas); 12867 } 12868 12869 canvas.restoreToCount(restoreCount); 12870 canvas.setBitmap(null); 12871 12872 if (attachInfo != null) { 12873 // Restore the cached Canvas for our siblings 12874 attachInfo.mCanvas = canvas; 12875 } 12876 } 12877 } 12878 12879 /** 12880 * Create a snapshot of the view into a bitmap. We should probably make 12881 * some form of this public, but should think about the API. 12882 */ 12883 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 12884 int width = mRight - mLeft; 12885 int height = mBottom - mTop; 12886 12887 final AttachInfo attachInfo = mAttachInfo; 12888 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 12889 width = (int) ((width * scale) + 0.5f); 12890 height = (int) ((height * scale) + 0.5f); 12891 12892 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 12893 width > 0 ? width : 1, height > 0 ? height : 1, quality); 12894 if (bitmap == null) { 12895 throw new OutOfMemoryError(); 12896 } 12897 12898 Resources resources = getResources(); 12899 if (resources != null) { 12900 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 12901 } 12902 12903 Canvas canvas; 12904 if (attachInfo != null) { 12905 canvas = attachInfo.mCanvas; 12906 if (canvas == null) { 12907 canvas = new Canvas(); 12908 } 12909 canvas.setBitmap(bitmap); 12910 // Temporarily clobber the cached Canvas in case one of our children 12911 // is also using a drawing cache. Without this, the children would 12912 // steal the canvas by attaching their own bitmap to it and bad, bad 12913 // things would happen (invisible views, corrupted drawings, etc.) 12914 attachInfo.mCanvas = null; 12915 } else { 12916 // This case should hopefully never or seldom happen 12917 canvas = new Canvas(bitmap); 12918 } 12919 12920 if ((backgroundColor & 0xff000000) != 0) { 12921 bitmap.eraseColor(backgroundColor); 12922 } 12923 12924 computeScroll(); 12925 final int restoreCount = canvas.save(); 12926 canvas.scale(scale, scale); 12927 canvas.translate(-mScrollX, -mScrollY); 12928 12929 // Temporarily remove the dirty mask 12930 int flags = mPrivateFlags; 12931 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 12932 12933 // Fast path for layouts with no backgrounds 12934 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 12935 dispatchDraw(canvas); 12936 } else { 12937 draw(canvas); 12938 } 12939 12940 mPrivateFlags = flags; 12941 12942 canvas.restoreToCount(restoreCount); 12943 canvas.setBitmap(null); 12944 12945 if (attachInfo != null) { 12946 // Restore the cached Canvas for our siblings 12947 attachInfo.mCanvas = canvas; 12948 } 12949 12950 return bitmap; 12951 } 12952 12953 /** 12954 * Indicates whether this View is currently in edit mode. A View is usually 12955 * in edit mode when displayed within a developer tool. For instance, if 12956 * this View is being drawn by a visual user interface builder, this method 12957 * should return true. 12958 * 12959 * Subclasses should check the return value of this method to provide 12960 * different behaviors if their normal behavior might interfere with the 12961 * host environment. For instance: the class spawns a thread in its 12962 * constructor, the drawing code relies on device-specific features, etc. 12963 * 12964 * This method is usually checked in the drawing code of custom widgets. 12965 * 12966 * @return True if this View is in edit mode, false otherwise. 12967 */ 12968 public boolean isInEditMode() { 12969 return false; 12970 } 12971 12972 /** 12973 * If the View draws content inside its padding and enables fading edges, 12974 * it needs to support padding offsets. Padding offsets are added to the 12975 * fading edges to extend the length of the fade so that it covers pixels 12976 * drawn inside the padding. 12977 * 12978 * Subclasses of this class should override this method if they need 12979 * to draw content inside the padding. 12980 * 12981 * @return True if padding offset must be applied, false otherwise. 12982 * 12983 * @see #getLeftPaddingOffset() 12984 * @see #getRightPaddingOffset() 12985 * @see #getTopPaddingOffset() 12986 * @see #getBottomPaddingOffset() 12987 * 12988 * @since CURRENT 12989 */ 12990 protected boolean isPaddingOffsetRequired() { 12991 return false; 12992 } 12993 12994 /** 12995 * Amount by which to extend the left fading region. Called only when 12996 * {@link #isPaddingOffsetRequired()} returns true. 12997 * 12998 * @return The left padding offset in pixels. 12999 * 13000 * @see #isPaddingOffsetRequired() 13001 * 13002 * @since CURRENT 13003 */ 13004 protected int getLeftPaddingOffset() { 13005 return 0; 13006 } 13007 13008 /** 13009 * Amount by which to extend the right fading region. Called only when 13010 * {@link #isPaddingOffsetRequired()} returns true. 13011 * 13012 * @return The right padding offset in pixels. 13013 * 13014 * @see #isPaddingOffsetRequired() 13015 * 13016 * @since CURRENT 13017 */ 13018 protected int getRightPaddingOffset() { 13019 return 0; 13020 } 13021 13022 /** 13023 * Amount by which to extend the top fading region. Called only when 13024 * {@link #isPaddingOffsetRequired()} returns true. 13025 * 13026 * @return The top padding offset in pixels. 13027 * 13028 * @see #isPaddingOffsetRequired() 13029 * 13030 * @since CURRENT 13031 */ 13032 protected int getTopPaddingOffset() { 13033 return 0; 13034 } 13035 13036 /** 13037 * Amount by which to extend the bottom fading region. Called only when 13038 * {@link #isPaddingOffsetRequired()} returns true. 13039 * 13040 * @return The bottom padding offset in pixels. 13041 * 13042 * @see #isPaddingOffsetRequired() 13043 * 13044 * @since CURRENT 13045 */ 13046 protected int getBottomPaddingOffset() { 13047 return 0; 13048 } 13049 13050 /** 13051 * @hide 13052 * @param offsetRequired 13053 */ 13054 protected int getFadeTop(boolean offsetRequired) { 13055 int top = mPaddingTop; 13056 if (offsetRequired) top += getTopPaddingOffset(); 13057 return top; 13058 } 13059 13060 /** 13061 * @hide 13062 * @param offsetRequired 13063 */ 13064 protected int getFadeHeight(boolean offsetRequired) { 13065 int padding = mPaddingTop; 13066 if (offsetRequired) padding += getTopPaddingOffset(); 13067 return mBottom - mTop - mPaddingBottom - padding; 13068 } 13069 13070 /** 13071 * <p>Indicates whether this view is attached to a hardware accelerated 13072 * window or not.</p> 13073 * 13074 * <p>Even if this method returns true, it does not mean that every call 13075 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 13076 * accelerated {@link android.graphics.Canvas}. For instance, if this view 13077 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 13078 * window is hardware accelerated, 13079 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 13080 * return false, and this method will return true.</p> 13081 * 13082 * @return True if the view is attached to a window and the window is 13083 * hardware accelerated; false in any other case. 13084 */ 13085 public boolean isHardwareAccelerated() { 13086 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 13087 } 13088 13089 /** 13090 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 13091 * case of an active Animation being run on the view. 13092 */ 13093 private boolean drawAnimation(ViewGroup parent, long drawingTime, 13094 Animation a, boolean scalingRequired) { 13095 Transformation invalidationTransform; 13096 final int flags = parent.mGroupFlags; 13097 final boolean initialized = a.isInitialized(); 13098 if (!initialized) { 13099 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 13100 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 13101 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 13102 onAnimationStart(); 13103 } 13104 13105 boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f); 13106 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 13107 if (parent.mInvalidationTransformation == null) { 13108 parent.mInvalidationTransformation = new Transformation(); 13109 } 13110 invalidationTransform = parent.mInvalidationTransformation; 13111 a.getTransformation(drawingTime, invalidationTransform, 1f); 13112 } else { 13113 invalidationTransform = parent.mChildTransformation; 13114 } 13115 13116 if (more) { 13117 if (!a.willChangeBounds()) { 13118 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 13119 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 13120 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 13121 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 13122 // The child need to draw an animation, potentially offscreen, so 13123 // make sure we do not cancel invalidate requests 13124 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 13125 parent.invalidate(mLeft, mTop, mRight, mBottom); 13126 } 13127 } else { 13128 if (parent.mInvalidateRegion == null) { 13129 parent.mInvalidateRegion = new RectF(); 13130 } 13131 final RectF region = parent.mInvalidateRegion; 13132 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 13133 invalidationTransform); 13134 13135 // The child need to draw an animation, potentially offscreen, so 13136 // make sure we do not cancel invalidate requests 13137 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 13138 13139 final int left = mLeft + (int) region.left; 13140 final int top = mTop + (int) region.top; 13141 parent.invalidate(left, top, left + (int) (region.width() + .5f), 13142 top + (int) (region.height() + .5f)); 13143 } 13144 } 13145 return more; 13146 } 13147 13148 /** 13149 * This method is called by getDisplayList() when a display list is created or re-rendered. 13150 * It sets or resets the current value of all properties on that display list (resetting is 13151 * necessary when a display list is being re-created, because we need to make sure that 13152 * previously-set transform values 13153 */ 13154 void setDisplayListProperties(DisplayList displayList) { 13155 if (displayList != null) { 13156 displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 13157 displayList.setHasOverlappingRendering(hasOverlappingRendering()); 13158 if (mParent instanceof ViewGroup) { 13159 displayList.setClipChildren( 13160 (((ViewGroup)mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0); 13161 } 13162 float alpha = 1; 13163 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 13164 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 13165 ViewGroup parentVG = (ViewGroup) mParent; 13166 final boolean hasTransform = 13167 parentVG.getChildStaticTransformation(this, parentVG.mChildTransformation); 13168 if (hasTransform) { 13169 Transformation transform = parentVG.mChildTransformation; 13170 final int transformType = parentVG.mChildTransformation.getTransformationType(); 13171 if (transformType != Transformation.TYPE_IDENTITY) { 13172 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 13173 alpha = transform.getAlpha(); 13174 } 13175 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 13176 displayList.setStaticMatrix(transform.getMatrix()); 13177 } 13178 } 13179 } 13180 } 13181 if (mTransformationInfo != null) { 13182 alpha *= mTransformationInfo.mAlpha; 13183 if (alpha < 1) { 13184 final int multipliedAlpha = (int) (255 * alpha); 13185 if (onSetAlpha(multipliedAlpha)) { 13186 alpha = 1; 13187 } 13188 } 13189 displayList.setTransformationInfo(alpha, 13190 mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY, 13191 mTransformationInfo.mRotation, mTransformationInfo.mRotationX, 13192 mTransformationInfo.mRotationY, mTransformationInfo.mScaleX, 13193 mTransformationInfo.mScaleY); 13194 if (mTransformationInfo.mCamera == null) { 13195 mTransformationInfo.mCamera = new Camera(); 13196 mTransformationInfo.matrix3D = new Matrix(); 13197 } 13198 displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ()); 13199 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == PFLAG_PIVOT_EXPLICITLY_SET) { 13200 displayList.setPivotX(getPivotX()); 13201 displayList.setPivotY(getPivotY()); 13202 } 13203 } else if (alpha < 1) { 13204 displayList.setAlpha(alpha); 13205 } 13206 } 13207 } 13208 13209 /** 13210 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 13211 * This draw() method is an implementation detail and is not intended to be overridden or 13212 * to be called from anywhere else other than ViewGroup.drawChild(). 13213 */ 13214 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 13215 boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 13216 boolean more = false; 13217 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 13218 final int flags = parent.mGroupFlags; 13219 13220 if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) { 13221 parent.mChildTransformation.clear(); 13222 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 13223 } 13224 13225 Transformation transformToApply = null; 13226 boolean concatMatrix = false; 13227 13228 boolean scalingRequired = false; 13229 boolean caching; 13230 int layerType = getLayerType(); 13231 13232 final boolean hardwareAccelerated = canvas.isHardwareAccelerated(); 13233 if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 || 13234 (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) { 13235 caching = true; 13236 // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList 13237 if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired; 13238 } else { 13239 caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated; 13240 } 13241 13242 final Animation a = getAnimation(); 13243 if (a != null) { 13244 more = drawAnimation(parent, drawingTime, a, scalingRequired); 13245 concatMatrix = a.willChangeTransformationMatrix(); 13246 if (concatMatrix) { 13247 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 13248 } 13249 transformToApply = parent.mChildTransformation; 13250 } else { 13251 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) == PFLAG3_VIEW_IS_ANIMATING_TRANSFORM && 13252 mDisplayList != null) { 13253 // No longer animating: clear out old animation matrix 13254 mDisplayList.setAnimationMatrix(null); 13255 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 13256 } 13257 if (!useDisplayListProperties && 13258 (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 13259 final boolean hasTransform = 13260 parent.getChildStaticTransformation(this, parent.mChildTransformation); 13261 if (hasTransform) { 13262 final int transformType = parent.mChildTransformation.getTransformationType(); 13263 transformToApply = transformType != Transformation.TYPE_IDENTITY ? 13264 parent.mChildTransformation : null; 13265 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 13266 } 13267 } 13268 } 13269 13270 concatMatrix |= !childHasIdentityMatrix; 13271 13272 // Sets the flag as early as possible to allow draw() implementations 13273 // to call invalidate() successfully when doing animations 13274 mPrivateFlags |= PFLAG_DRAWN; 13275 13276 if (!concatMatrix && 13277 (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 13278 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 13279 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 13280 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 13281 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 13282 return more; 13283 } 13284 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 13285 13286 if (hardwareAccelerated) { 13287 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 13288 // retain the flag's value temporarily in the mRecreateDisplayList flag 13289 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED; 13290 mPrivateFlags &= ~PFLAG_INVALIDATED; 13291 } 13292 13293 DisplayList displayList = null; 13294 Bitmap cache = null; 13295 boolean hasDisplayList = false; 13296 if (caching) { 13297 if (!hardwareAccelerated) { 13298 if (layerType != LAYER_TYPE_NONE) { 13299 layerType = LAYER_TYPE_SOFTWARE; 13300 buildDrawingCache(true); 13301 } 13302 cache = getDrawingCache(true); 13303 } else { 13304 switch (layerType) { 13305 case LAYER_TYPE_SOFTWARE: 13306 if (useDisplayListProperties) { 13307 hasDisplayList = canHaveDisplayList(); 13308 } else { 13309 buildDrawingCache(true); 13310 cache = getDrawingCache(true); 13311 } 13312 break; 13313 case LAYER_TYPE_HARDWARE: 13314 if (useDisplayListProperties) { 13315 hasDisplayList = canHaveDisplayList(); 13316 } 13317 break; 13318 case LAYER_TYPE_NONE: 13319 // Delay getting the display list until animation-driven alpha values are 13320 // set up and possibly passed on to the view 13321 hasDisplayList = canHaveDisplayList(); 13322 break; 13323 } 13324 } 13325 } 13326 useDisplayListProperties &= hasDisplayList; 13327 if (useDisplayListProperties) { 13328 displayList = getDisplayList(); 13329 if (!displayList.isValid()) { 13330 // Uncommon, but possible. If a view is removed from the hierarchy during the call 13331 // to getDisplayList(), the display list will be marked invalid and we should not 13332 // try to use it again. 13333 displayList = null; 13334 hasDisplayList = false; 13335 useDisplayListProperties = false; 13336 } 13337 } 13338 13339 int sx = 0; 13340 int sy = 0; 13341 if (!hasDisplayList) { 13342 computeScroll(); 13343 sx = mScrollX; 13344 sy = mScrollY; 13345 } 13346 13347 final boolean hasNoCache = cache == null || hasDisplayList; 13348 final boolean offsetForScroll = cache == null && !hasDisplayList && 13349 layerType != LAYER_TYPE_HARDWARE; 13350 13351 int restoreTo = -1; 13352 if (!useDisplayListProperties || transformToApply != null) { 13353 restoreTo = canvas.save(); 13354 } 13355 if (offsetForScroll) { 13356 canvas.translate(mLeft - sx, mTop - sy); 13357 } else { 13358 if (!useDisplayListProperties) { 13359 canvas.translate(mLeft, mTop); 13360 } 13361 if (scalingRequired) { 13362 if (useDisplayListProperties) { 13363 // TODO: Might not need this if we put everything inside the DL 13364 restoreTo = canvas.save(); 13365 } 13366 // mAttachInfo cannot be null, otherwise scalingRequired == false 13367 final float scale = 1.0f / mAttachInfo.mApplicationScale; 13368 canvas.scale(scale, scale); 13369 } 13370 } 13371 13372 float alpha = useDisplayListProperties ? 1 : getAlpha(); 13373 if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() || 13374 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 13375 if (transformToApply != null || !childHasIdentityMatrix) { 13376 int transX = 0; 13377 int transY = 0; 13378 13379 if (offsetForScroll) { 13380 transX = -sx; 13381 transY = -sy; 13382 } 13383 13384 if (transformToApply != null) { 13385 if (concatMatrix) { 13386 if (useDisplayListProperties) { 13387 displayList.setAnimationMatrix(transformToApply.getMatrix()); 13388 } else { 13389 // Undo the scroll translation, apply the transformation matrix, 13390 // then redo the scroll translate to get the correct result. 13391 canvas.translate(-transX, -transY); 13392 canvas.concat(transformToApply.getMatrix()); 13393 canvas.translate(transX, transY); 13394 } 13395 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 13396 } 13397 13398 float transformAlpha = transformToApply.getAlpha(); 13399 if (transformAlpha < 1) { 13400 alpha *= transformAlpha; 13401 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 13402 } 13403 } 13404 13405 if (!childHasIdentityMatrix && !useDisplayListProperties) { 13406 canvas.translate(-transX, -transY); 13407 canvas.concat(getMatrix()); 13408 canvas.translate(transX, transY); 13409 } 13410 } 13411 13412 // Deal with alpha if it is or used to be <1 13413 if (alpha < 1 || 13414 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 13415 if (alpha < 1) { 13416 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 13417 } else { 13418 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 13419 } 13420 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 13421 if (hasNoCache) { 13422 final int multipliedAlpha = (int) (255 * alpha); 13423 if (!onSetAlpha(multipliedAlpha)) { 13424 int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 13425 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 || 13426 layerType != LAYER_TYPE_NONE) { 13427 layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG; 13428 } 13429 if (useDisplayListProperties) { 13430 displayList.setAlpha(alpha * getAlpha()); 13431 } else if (layerType == LAYER_TYPE_NONE) { 13432 final int scrollX = hasDisplayList ? 0 : sx; 13433 final int scrollY = hasDisplayList ? 0 : sy; 13434 canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft, 13435 scrollY + mBottom - mTop, multipliedAlpha, layerFlags); 13436 } 13437 } else { 13438 // Alpha is handled by the child directly, clobber the layer's alpha 13439 mPrivateFlags |= PFLAG_ALPHA_SET; 13440 } 13441 } 13442 } 13443 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 13444 onSetAlpha(255); 13445 mPrivateFlags &= ~PFLAG_ALPHA_SET; 13446 } 13447 13448 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN && 13449 !useDisplayListProperties) { 13450 if (offsetForScroll) { 13451 canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop)); 13452 } else { 13453 if (!scalingRequired || cache == null) { 13454 canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop); 13455 } else { 13456 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 13457 } 13458 } 13459 } 13460 13461 if (!useDisplayListProperties && hasDisplayList) { 13462 displayList = getDisplayList(); 13463 if (!displayList.isValid()) { 13464 // Uncommon, but possible. If a view is removed from the hierarchy during the call 13465 // to getDisplayList(), the display list will be marked invalid and we should not 13466 // try to use it again. 13467 displayList = null; 13468 hasDisplayList = false; 13469 } 13470 } 13471 13472 if (hasNoCache) { 13473 boolean layerRendered = false; 13474 if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) { 13475 final HardwareLayer layer = getHardwareLayer(); 13476 if (layer != null && layer.isValid()) { 13477 mLayerPaint.setAlpha((int) (alpha * 255)); 13478 ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint); 13479 layerRendered = true; 13480 } else { 13481 final int scrollX = hasDisplayList ? 0 : sx; 13482 final int scrollY = hasDisplayList ? 0 : sy; 13483 canvas.saveLayer(scrollX, scrollY, 13484 scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint, 13485 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG); 13486 } 13487 } 13488 13489 if (!layerRendered) { 13490 if (!hasDisplayList) { 13491 // Fast path for layouts with no backgrounds 13492 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 13493 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13494 dispatchDraw(canvas); 13495 } else { 13496 draw(canvas); 13497 } 13498 } else { 13499 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13500 ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags); 13501 } 13502 } 13503 } else if (cache != null) { 13504 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13505 Paint cachePaint; 13506 13507 if (layerType == LAYER_TYPE_NONE) { 13508 cachePaint = parent.mCachePaint; 13509 if (cachePaint == null) { 13510 cachePaint = new Paint(); 13511 cachePaint.setDither(false); 13512 parent.mCachePaint = cachePaint; 13513 } 13514 if (alpha < 1) { 13515 cachePaint.setAlpha((int) (alpha * 255)); 13516 parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 13517 } else if ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) { 13518 cachePaint.setAlpha(255); 13519 parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 13520 } 13521 } else { 13522 cachePaint = mLayerPaint; 13523 cachePaint.setAlpha((int) (alpha * 255)); 13524 } 13525 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 13526 } 13527 13528 if (restoreTo >= 0) { 13529 canvas.restoreToCount(restoreTo); 13530 } 13531 13532 if (a != null && !more) { 13533 if (!hardwareAccelerated && !a.getFillAfter()) { 13534 onSetAlpha(255); 13535 } 13536 parent.finishAnimatingView(this, a); 13537 } 13538 13539 if (more && hardwareAccelerated) { 13540 // invalidation is the trigger to recreate display lists, so if we're using 13541 // display lists to render, force an invalidate to allow the animation to 13542 // continue drawing another frame 13543 parent.invalidate(true); 13544 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 13545 // alpha animations should cause the child to recreate its display list 13546 invalidate(true); 13547 } 13548 } 13549 13550 mRecreateDisplayList = false; 13551 13552 return more; 13553 } 13554 13555 /** 13556 * Manually render this view (and all of its children) to the given Canvas. 13557 * The view must have already done a full layout before this function is 13558 * called. When implementing a view, implement 13559 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 13560 * If you do need to override this method, call the superclass version. 13561 * 13562 * @param canvas The Canvas to which the View is rendered. 13563 */ 13564 public void draw(Canvas canvas) { 13565 final int privateFlags = mPrivateFlags; 13566 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 13567 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 13568 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 13569 13570 /* 13571 * Draw traversal performs several drawing steps which must be executed 13572 * in the appropriate order: 13573 * 13574 * 1. Draw the background 13575 * 2. If necessary, save the canvas' layers to prepare for fading 13576 * 3. Draw view's content 13577 * 4. Draw children 13578 * 5. If necessary, draw the fading edges and restore layers 13579 * 6. Draw decorations (scrollbars for instance) 13580 */ 13581 13582 // Step 1, draw the background, if needed 13583 int saveCount; 13584 13585 if (!dirtyOpaque) { 13586 final Drawable background = mBackground; 13587 if (background != null) { 13588 final int scrollX = mScrollX; 13589 final int scrollY = mScrollY; 13590 13591 if (mBackgroundSizeChanged) { 13592 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 13593 mBackgroundSizeChanged = false; 13594 } 13595 13596 if ((scrollX | scrollY) == 0) { 13597 background.draw(canvas); 13598 } else { 13599 canvas.translate(scrollX, scrollY); 13600 background.draw(canvas); 13601 canvas.translate(-scrollX, -scrollY); 13602 } 13603 } 13604 } 13605 13606 // skip step 2 & 5 if possible (common case) 13607 final int viewFlags = mViewFlags; 13608 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 13609 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 13610 if (!verticalEdges && !horizontalEdges) { 13611 // Step 3, draw the content 13612 if (!dirtyOpaque) onDraw(canvas); 13613 13614 // Step 4, draw the children 13615 dispatchDraw(canvas); 13616 13617 // Step 6, draw decorations (scrollbars) 13618 onDrawScrollBars(canvas); 13619 13620 // we're done... 13621 return; 13622 } 13623 13624 /* 13625 * Here we do the full fledged routine... 13626 * (this is an uncommon case where speed matters less, 13627 * this is why we repeat some of the tests that have been 13628 * done above) 13629 */ 13630 13631 boolean drawTop = false; 13632 boolean drawBottom = false; 13633 boolean drawLeft = false; 13634 boolean drawRight = false; 13635 13636 float topFadeStrength = 0.0f; 13637 float bottomFadeStrength = 0.0f; 13638 float leftFadeStrength = 0.0f; 13639 float rightFadeStrength = 0.0f; 13640 13641 // Step 2, save the canvas' layers 13642 int paddingLeft = mPaddingLeft; 13643 13644 final boolean offsetRequired = isPaddingOffsetRequired(); 13645 if (offsetRequired) { 13646 paddingLeft += getLeftPaddingOffset(); 13647 } 13648 13649 int left = mScrollX + paddingLeft; 13650 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 13651 int top = mScrollY + getFadeTop(offsetRequired); 13652 int bottom = top + getFadeHeight(offsetRequired); 13653 13654 if (offsetRequired) { 13655 right += getRightPaddingOffset(); 13656 bottom += getBottomPaddingOffset(); 13657 } 13658 13659 final ScrollabilityCache scrollabilityCache = mScrollCache; 13660 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 13661 int length = (int) fadeHeight; 13662 13663 // clip the fade length if top and bottom fades overlap 13664 // overlapping fades produce odd-looking artifacts 13665 if (verticalEdges && (top + length > bottom - length)) { 13666 length = (bottom - top) / 2; 13667 } 13668 13669 // also clip horizontal fades if necessary 13670 if (horizontalEdges && (left + length > right - length)) { 13671 length = (right - left) / 2; 13672 } 13673 13674 if (verticalEdges) { 13675 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 13676 drawTop = topFadeStrength * fadeHeight > 1.0f; 13677 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 13678 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 13679 } 13680 13681 if (horizontalEdges) { 13682 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 13683 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 13684 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 13685 drawRight = rightFadeStrength * fadeHeight > 1.0f; 13686 } 13687 13688 saveCount = canvas.getSaveCount(); 13689 13690 int solidColor = getSolidColor(); 13691 if (solidColor == 0) { 13692 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 13693 13694 if (drawTop) { 13695 canvas.saveLayer(left, top, right, top + length, null, flags); 13696 } 13697 13698 if (drawBottom) { 13699 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 13700 } 13701 13702 if (drawLeft) { 13703 canvas.saveLayer(left, top, left + length, bottom, null, flags); 13704 } 13705 13706 if (drawRight) { 13707 canvas.saveLayer(right - length, top, right, bottom, null, flags); 13708 } 13709 } else { 13710 scrollabilityCache.setFadeColor(solidColor); 13711 } 13712 13713 // Step 3, draw the content 13714 if (!dirtyOpaque) onDraw(canvas); 13715 13716 // Step 4, draw the children 13717 dispatchDraw(canvas); 13718 13719 // Step 5, draw the fade effect and restore layers 13720 final Paint p = scrollabilityCache.paint; 13721 final Matrix matrix = scrollabilityCache.matrix; 13722 final Shader fade = scrollabilityCache.shader; 13723 13724 if (drawTop) { 13725 matrix.setScale(1, fadeHeight * topFadeStrength); 13726 matrix.postTranslate(left, top); 13727 fade.setLocalMatrix(matrix); 13728 canvas.drawRect(left, top, right, top + length, p); 13729 } 13730 13731 if (drawBottom) { 13732 matrix.setScale(1, fadeHeight * bottomFadeStrength); 13733 matrix.postRotate(180); 13734 matrix.postTranslate(left, bottom); 13735 fade.setLocalMatrix(matrix); 13736 canvas.drawRect(left, bottom - length, right, bottom, p); 13737 } 13738 13739 if (drawLeft) { 13740 matrix.setScale(1, fadeHeight * leftFadeStrength); 13741 matrix.postRotate(-90); 13742 matrix.postTranslate(left, top); 13743 fade.setLocalMatrix(matrix); 13744 canvas.drawRect(left, top, left + length, bottom, p); 13745 } 13746 13747 if (drawRight) { 13748 matrix.setScale(1, fadeHeight * rightFadeStrength); 13749 matrix.postRotate(90); 13750 matrix.postTranslate(right, top); 13751 fade.setLocalMatrix(matrix); 13752 canvas.drawRect(right - length, top, right, bottom, p); 13753 } 13754 13755 canvas.restoreToCount(saveCount); 13756 13757 // Step 6, draw decorations (scrollbars) 13758 onDrawScrollBars(canvas); 13759 } 13760 13761 /** 13762 * Override this if your view is known to always be drawn on top of a solid color background, 13763 * and needs to draw fading edges. Returning a non-zero color enables the view system to 13764 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 13765 * should be set to 0xFF. 13766 * 13767 * @see #setVerticalFadingEdgeEnabled(boolean) 13768 * @see #setHorizontalFadingEdgeEnabled(boolean) 13769 * 13770 * @return The known solid color background for this view, or 0 if the color may vary 13771 */ 13772 @ViewDebug.ExportedProperty(category = "drawing") 13773 public int getSolidColor() { 13774 return 0; 13775 } 13776 13777 /** 13778 * Build a human readable string representation of the specified view flags. 13779 * 13780 * @param flags the view flags to convert to a string 13781 * @return a String representing the supplied flags 13782 */ 13783 private static String printFlags(int flags) { 13784 String output = ""; 13785 int numFlags = 0; 13786 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 13787 output += "TAKES_FOCUS"; 13788 numFlags++; 13789 } 13790 13791 switch (flags & VISIBILITY_MASK) { 13792 case INVISIBLE: 13793 if (numFlags > 0) { 13794 output += " "; 13795 } 13796 output += "INVISIBLE"; 13797 // USELESS HERE numFlags++; 13798 break; 13799 case GONE: 13800 if (numFlags > 0) { 13801 output += " "; 13802 } 13803 output += "GONE"; 13804 // USELESS HERE numFlags++; 13805 break; 13806 default: 13807 break; 13808 } 13809 return output; 13810 } 13811 13812 /** 13813 * Build a human readable string representation of the specified private 13814 * view flags. 13815 * 13816 * @param privateFlags the private view flags to convert to a string 13817 * @return a String representing the supplied flags 13818 */ 13819 private static String printPrivateFlags(int privateFlags) { 13820 String output = ""; 13821 int numFlags = 0; 13822 13823 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 13824 output += "WANTS_FOCUS"; 13825 numFlags++; 13826 } 13827 13828 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 13829 if (numFlags > 0) { 13830 output += " "; 13831 } 13832 output += "FOCUSED"; 13833 numFlags++; 13834 } 13835 13836 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 13837 if (numFlags > 0) { 13838 output += " "; 13839 } 13840 output += "SELECTED"; 13841 numFlags++; 13842 } 13843 13844 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 13845 if (numFlags > 0) { 13846 output += " "; 13847 } 13848 output += "IS_ROOT_NAMESPACE"; 13849 numFlags++; 13850 } 13851 13852 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 13853 if (numFlags > 0) { 13854 output += " "; 13855 } 13856 output += "HAS_BOUNDS"; 13857 numFlags++; 13858 } 13859 13860 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 13861 if (numFlags > 0) { 13862 output += " "; 13863 } 13864 output += "DRAWN"; 13865 // USELESS HERE numFlags++; 13866 } 13867 return output; 13868 } 13869 13870 /** 13871 * <p>Indicates whether or not this view's layout will be requested during 13872 * the next hierarchy layout pass.</p> 13873 * 13874 * @return true if the layout will be forced during next layout pass 13875 */ 13876 public boolean isLayoutRequested() { 13877 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 13878 } 13879 13880 /** 13881 * Return true if o is a ViewGroup that is laying out using optical bounds. 13882 * @hide 13883 */ 13884 public static boolean isLayoutModeOptical(Object o) { 13885 return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical(); 13886 } 13887 13888 private boolean setOpticalFrame(int left, int top, int right, int bottom) { 13889 Insets parentInsets = mParent instanceof View ? 13890 ((View) mParent).getOpticalInsets() : Insets.NONE; 13891 Insets childInsets = getOpticalInsets(); 13892 return setFrame( 13893 left + parentInsets.left - childInsets.left, 13894 top + parentInsets.top - childInsets.top, 13895 right + parentInsets.left + childInsets.right, 13896 bottom + parentInsets.top + childInsets.bottom); 13897 } 13898 13899 /** 13900 * Assign a size and position to a view and all of its 13901 * descendants 13902 * 13903 * <p>This is the second phase of the layout mechanism. 13904 * (The first is measuring). In this phase, each parent calls 13905 * layout on all of its children to position them. 13906 * This is typically done using the child measurements 13907 * that were stored in the measure pass().</p> 13908 * 13909 * <p>Derived classes should not override this method. 13910 * Derived classes with children should override 13911 * onLayout. In that method, they should 13912 * call layout on each of their children.</p> 13913 * 13914 * @param l Left position, relative to parent 13915 * @param t Top position, relative to parent 13916 * @param r Right position, relative to parent 13917 * @param b Bottom position, relative to parent 13918 */ 13919 @SuppressWarnings({"unchecked"}) 13920 public void layout(int l, int t, int r, int b) { 13921 int oldL = mLeft; 13922 int oldT = mTop; 13923 int oldB = mBottom; 13924 int oldR = mRight; 13925 boolean changed = isLayoutModeOptical(mParent) ? 13926 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); 13927 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 13928 onLayout(changed, l, t, r, b); 13929 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 13930 13931 ListenerInfo li = mListenerInfo; 13932 if (li != null && li.mOnLayoutChangeListeners != null) { 13933 ArrayList<OnLayoutChangeListener> listenersCopy = 13934 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 13935 int numListeners = listenersCopy.size(); 13936 for (int i = 0; i < numListeners; ++i) { 13937 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 13938 } 13939 } 13940 } 13941 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 13942 } 13943 13944 /** 13945 * Called from layout when this view should 13946 * assign a size and position to each of its children. 13947 * 13948 * Derived classes with children should override 13949 * this method and call layout on each of 13950 * their children. 13951 * @param changed This is a new size or position for this view 13952 * @param left Left position, relative to parent 13953 * @param top Top position, relative to parent 13954 * @param right Right position, relative to parent 13955 * @param bottom Bottom position, relative to parent 13956 */ 13957 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 13958 } 13959 13960 /** 13961 * Assign a size and position to this view. 13962 * 13963 * This is called from layout. 13964 * 13965 * @param left Left position, relative to parent 13966 * @param top Top position, relative to parent 13967 * @param right Right position, relative to parent 13968 * @param bottom Bottom position, relative to parent 13969 * @return true if the new size and position are different than the 13970 * previous ones 13971 * {@hide} 13972 */ 13973 protected boolean setFrame(int left, int top, int right, int bottom) { 13974 boolean changed = false; 13975 13976 if (DBG) { 13977 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 13978 + right + "," + bottom + ")"); 13979 } 13980 13981 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 13982 changed = true; 13983 13984 // Remember our drawn bit 13985 int drawn = mPrivateFlags & PFLAG_DRAWN; 13986 13987 int oldWidth = mRight - mLeft; 13988 int oldHeight = mBottom - mTop; 13989 int newWidth = right - left; 13990 int newHeight = bottom - top; 13991 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 13992 13993 // Invalidate our old position 13994 invalidate(sizeChanged); 13995 13996 mLeft = left; 13997 mTop = top; 13998 mRight = right; 13999 mBottom = bottom; 14000 if (mDisplayList != null) { 14001 mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 14002 } 14003 14004 mPrivateFlags |= PFLAG_HAS_BOUNDS; 14005 14006 14007 if (sizeChanged) { 14008 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 14009 // A change in dimension means an auto-centered pivot point changes, too 14010 if (mTransformationInfo != null) { 14011 mTransformationInfo.mMatrixDirty = true; 14012 } 14013 } 14014 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 14015 } 14016 14017 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 14018 // If we are visible, force the DRAWN bit to on so that 14019 // this invalidate will go through (at least to our parent). 14020 // This is because someone may have invalidated this view 14021 // before this call to setFrame came in, thereby clearing 14022 // the DRAWN bit. 14023 mPrivateFlags |= PFLAG_DRAWN; 14024 invalidate(sizeChanged); 14025 // parent display list may need to be recreated based on a change in the bounds 14026 // of any child 14027 invalidateParentCaches(); 14028 } 14029 14030 // Reset drawn bit to original value (invalidate turns it off) 14031 mPrivateFlags |= drawn; 14032 14033 mBackgroundSizeChanged = true; 14034 } 14035 return changed; 14036 } 14037 14038 /** 14039 * Finalize inflating a view from XML. This is called as the last phase 14040 * of inflation, after all child views have been added. 14041 * 14042 * <p>Even if the subclass overrides onFinishInflate, they should always be 14043 * sure to call the super method, so that we get called. 14044 */ 14045 protected void onFinishInflate() { 14046 } 14047 14048 /** 14049 * Returns the resources associated with this view. 14050 * 14051 * @return Resources object. 14052 */ 14053 public Resources getResources() { 14054 return mResources; 14055 } 14056 14057 /** 14058 * Invalidates the specified Drawable. 14059 * 14060 * @param drawable the drawable to invalidate 14061 */ 14062 public void invalidateDrawable(Drawable drawable) { 14063 if (verifyDrawable(drawable)) { 14064 final Rect dirty = drawable.getBounds(); 14065 final int scrollX = mScrollX; 14066 final int scrollY = mScrollY; 14067 14068 invalidate(dirty.left + scrollX, dirty.top + scrollY, 14069 dirty.right + scrollX, dirty.bottom + scrollY); 14070 } 14071 } 14072 14073 /** 14074 * Schedules an action on a drawable to occur at a specified time. 14075 * 14076 * @param who the recipient of the action 14077 * @param what the action to run on the drawable 14078 * @param when the time at which the action must occur. Uses the 14079 * {@link SystemClock#uptimeMillis} timebase. 14080 */ 14081 public void scheduleDrawable(Drawable who, Runnable what, long when) { 14082 if (verifyDrawable(who) && what != null) { 14083 final long delay = when - SystemClock.uptimeMillis(); 14084 if (mAttachInfo != null) { 14085 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 14086 Choreographer.CALLBACK_ANIMATION, what, who, 14087 Choreographer.subtractFrameDelay(delay)); 14088 } else { 14089 ViewRootImpl.getRunQueue().postDelayed(what, delay); 14090 } 14091 } 14092 } 14093 14094 /** 14095 * Cancels a scheduled action on a drawable. 14096 * 14097 * @param who the recipient of the action 14098 * @param what the action to cancel 14099 */ 14100 public void unscheduleDrawable(Drawable who, Runnable what) { 14101 if (verifyDrawable(who) && what != null) { 14102 if (mAttachInfo != null) { 14103 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 14104 Choreographer.CALLBACK_ANIMATION, what, who); 14105 } else { 14106 ViewRootImpl.getRunQueue().removeCallbacks(what); 14107 } 14108 } 14109 } 14110 14111 /** 14112 * Unschedule any events associated with the given Drawable. This can be 14113 * used when selecting a new Drawable into a view, so that the previous 14114 * one is completely unscheduled. 14115 * 14116 * @param who The Drawable to unschedule. 14117 * 14118 * @see #drawableStateChanged 14119 */ 14120 public void unscheduleDrawable(Drawable who) { 14121 if (mAttachInfo != null && who != null) { 14122 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 14123 Choreographer.CALLBACK_ANIMATION, null, who); 14124 } 14125 } 14126 14127 /** 14128 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 14129 * that the View directionality can and will be resolved before its Drawables. 14130 * 14131 * Will call {@link View#onResolveDrawables} when resolution is done. 14132 * 14133 * @hide 14134 */ 14135 public void resolveDrawables() { 14136 if (mBackground != null) { 14137 mBackground.setLayoutDirection(getLayoutDirection()); 14138 } 14139 onResolveDrawables(getLayoutDirection()); 14140 } 14141 14142 /** 14143 * Called when layout direction has been resolved. 14144 * 14145 * The default implementation does nothing. 14146 * 14147 * @param layoutDirection The resolved layout direction. 14148 * 14149 * @see #LAYOUT_DIRECTION_LTR 14150 * @see #LAYOUT_DIRECTION_RTL 14151 * 14152 * @hide 14153 */ 14154 public void onResolveDrawables(int layoutDirection) { 14155 } 14156 14157 /** 14158 * If your view subclass is displaying its own Drawable objects, it should 14159 * override this function and return true for any Drawable it is 14160 * displaying. This allows animations for those drawables to be 14161 * scheduled. 14162 * 14163 * <p>Be sure to call through to the super class when overriding this 14164 * function. 14165 * 14166 * @param who The Drawable to verify. Return true if it is one you are 14167 * displaying, else return the result of calling through to the 14168 * super class. 14169 * 14170 * @return boolean If true than the Drawable is being displayed in the 14171 * view; else false and it is not allowed to animate. 14172 * 14173 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 14174 * @see #drawableStateChanged() 14175 */ 14176 protected boolean verifyDrawable(Drawable who) { 14177 return who == mBackground; 14178 } 14179 14180 /** 14181 * This function is called whenever the state of the view changes in such 14182 * a way that it impacts the state of drawables being shown. 14183 * 14184 * <p>Be sure to call through to the superclass when overriding this 14185 * function. 14186 * 14187 * @see Drawable#setState(int[]) 14188 */ 14189 protected void drawableStateChanged() { 14190 Drawable d = mBackground; 14191 if (d != null && d.isStateful()) { 14192 d.setState(getDrawableState()); 14193 } 14194 } 14195 14196 /** 14197 * Call this to force a view to update its drawable state. This will cause 14198 * drawableStateChanged to be called on this view. Views that are interested 14199 * in the new state should call getDrawableState. 14200 * 14201 * @see #drawableStateChanged 14202 * @see #getDrawableState 14203 */ 14204 public void refreshDrawableState() { 14205 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 14206 drawableStateChanged(); 14207 14208 ViewParent parent = mParent; 14209 if (parent != null) { 14210 parent.childDrawableStateChanged(this); 14211 } 14212 } 14213 14214 /** 14215 * Return an array of resource IDs of the drawable states representing the 14216 * current state of the view. 14217 * 14218 * @return The current drawable state 14219 * 14220 * @see Drawable#setState(int[]) 14221 * @see #drawableStateChanged() 14222 * @see #onCreateDrawableState(int) 14223 */ 14224 public final int[] getDrawableState() { 14225 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 14226 return mDrawableState; 14227 } else { 14228 mDrawableState = onCreateDrawableState(0); 14229 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 14230 return mDrawableState; 14231 } 14232 } 14233 14234 /** 14235 * Generate the new {@link android.graphics.drawable.Drawable} state for 14236 * this view. This is called by the view 14237 * system when the cached Drawable state is determined to be invalid. To 14238 * retrieve the current state, you should use {@link #getDrawableState}. 14239 * 14240 * @param extraSpace if non-zero, this is the number of extra entries you 14241 * would like in the returned array in which you can place your own 14242 * states. 14243 * 14244 * @return Returns an array holding the current {@link Drawable} state of 14245 * the view. 14246 * 14247 * @see #mergeDrawableStates(int[], int[]) 14248 */ 14249 protected int[] onCreateDrawableState(int extraSpace) { 14250 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 14251 mParent instanceof View) { 14252 return ((View) mParent).onCreateDrawableState(extraSpace); 14253 } 14254 14255 int[] drawableState; 14256 14257 int privateFlags = mPrivateFlags; 14258 14259 int viewStateIndex = 0; 14260 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 14261 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 14262 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 14263 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 14264 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 14265 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 14266 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 14267 HardwareRenderer.isAvailable()) { 14268 // This is set if HW acceleration is requested, even if the current 14269 // process doesn't allow it. This is just to allow app preview 14270 // windows to better match their app. 14271 viewStateIndex |= VIEW_STATE_ACCELERATED; 14272 } 14273 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 14274 14275 final int privateFlags2 = mPrivateFlags2; 14276 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 14277 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 14278 14279 drawableState = VIEW_STATE_SETS[viewStateIndex]; 14280 14281 //noinspection ConstantIfStatement 14282 if (false) { 14283 Log.i("View", "drawableStateIndex=" + viewStateIndex); 14284 Log.i("View", toString() 14285 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 14286 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 14287 + " fo=" + hasFocus() 14288 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 14289 + " wf=" + hasWindowFocus() 14290 + ": " + Arrays.toString(drawableState)); 14291 } 14292 14293 if (extraSpace == 0) { 14294 return drawableState; 14295 } 14296 14297 final int[] fullState; 14298 if (drawableState != null) { 14299 fullState = new int[drawableState.length + extraSpace]; 14300 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 14301 } else { 14302 fullState = new int[extraSpace]; 14303 } 14304 14305 return fullState; 14306 } 14307 14308 /** 14309 * Merge your own state values in <var>additionalState</var> into the base 14310 * state values <var>baseState</var> that were returned by 14311 * {@link #onCreateDrawableState(int)}. 14312 * 14313 * @param baseState The base state values returned by 14314 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 14315 * own additional state values. 14316 * 14317 * @param additionalState The additional state values you would like 14318 * added to <var>baseState</var>; this array is not modified. 14319 * 14320 * @return As a convenience, the <var>baseState</var> array you originally 14321 * passed into the function is returned. 14322 * 14323 * @see #onCreateDrawableState(int) 14324 */ 14325 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 14326 final int N = baseState.length; 14327 int i = N - 1; 14328 while (i >= 0 && baseState[i] == 0) { 14329 i--; 14330 } 14331 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 14332 return baseState; 14333 } 14334 14335 /** 14336 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 14337 * on all Drawable objects associated with this view. 14338 */ 14339 public void jumpDrawablesToCurrentState() { 14340 if (mBackground != null) { 14341 mBackground.jumpToCurrentState(); 14342 } 14343 } 14344 14345 /** 14346 * Sets the background color for this view. 14347 * @param color the color of the background 14348 */ 14349 @RemotableViewMethod 14350 public void setBackgroundColor(int color) { 14351 if (mBackground instanceof ColorDrawable) { 14352 ((ColorDrawable) mBackground.mutate()).setColor(color); 14353 computeOpaqueFlags(); 14354 } else { 14355 setBackground(new ColorDrawable(color)); 14356 } 14357 } 14358 14359 /** 14360 * Set the background to a given resource. The resource should refer to 14361 * a Drawable object or 0 to remove the background. 14362 * @param resid The identifier of the resource. 14363 * 14364 * @attr ref android.R.styleable#View_background 14365 */ 14366 @RemotableViewMethod 14367 public void setBackgroundResource(int resid) { 14368 if (resid != 0 && resid == mBackgroundResource) { 14369 return; 14370 } 14371 14372 Drawable d= null; 14373 if (resid != 0) { 14374 d = mResources.getDrawable(resid); 14375 } 14376 setBackground(d); 14377 14378 mBackgroundResource = resid; 14379 } 14380 14381 /** 14382 * Set the background to a given Drawable, or remove the background. If the 14383 * background has padding, this View's padding is set to the background's 14384 * padding. However, when a background is removed, this View's padding isn't 14385 * touched. If setting the padding is desired, please use 14386 * {@link #setPadding(int, int, int, int)}. 14387 * 14388 * @param background The Drawable to use as the background, or null to remove the 14389 * background 14390 */ 14391 public void setBackground(Drawable background) { 14392 //noinspection deprecation 14393 setBackgroundDrawable(background); 14394 } 14395 14396 /** 14397 * @deprecated use {@link #setBackground(Drawable)} instead 14398 */ 14399 @Deprecated 14400 public void setBackgroundDrawable(Drawable background) { 14401 computeOpaqueFlags(); 14402 14403 if (background == mBackground) { 14404 return; 14405 } 14406 14407 boolean requestLayout = false; 14408 14409 mBackgroundResource = 0; 14410 14411 /* 14412 * Regardless of whether we're setting a new background or not, we want 14413 * to clear the previous drawable. 14414 */ 14415 if (mBackground != null) { 14416 mBackground.setCallback(null); 14417 unscheduleDrawable(mBackground); 14418 } 14419 14420 if (background != null) { 14421 Rect padding = sThreadLocal.get(); 14422 if (padding == null) { 14423 padding = new Rect(); 14424 sThreadLocal.set(padding); 14425 } 14426 background.setLayoutDirection(getLayoutDirection()); 14427 if (background.getPadding(padding)) { 14428 resetResolvedPadding(); 14429 switch (background.getLayoutDirection()) { 14430 case LAYOUT_DIRECTION_RTL: 14431 mUserPaddingLeftInitial = padding.right; 14432 mUserPaddingRightInitial = padding.left; 14433 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 14434 break; 14435 case LAYOUT_DIRECTION_LTR: 14436 default: 14437 mUserPaddingLeftInitial = padding.left; 14438 mUserPaddingRightInitial = padding.right; 14439 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 14440 } 14441 } 14442 14443 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 14444 // if it has a different minimum size, we should layout again 14445 if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() || 14446 mBackground.getMinimumWidth() != background.getMinimumWidth()) { 14447 requestLayout = true; 14448 } 14449 14450 background.setCallback(this); 14451 if (background.isStateful()) { 14452 background.setState(getDrawableState()); 14453 } 14454 background.setVisible(getVisibility() == VISIBLE, false); 14455 mBackground = background; 14456 14457 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 14458 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 14459 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 14460 requestLayout = true; 14461 } 14462 } else { 14463 /* Remove the background */ 14464 mBackground = null; 14465 14466 if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) { 14467 /* 14468 * This view ONLY drew the background before and we're removing 14469 * the background, so now it won't draw anything 14470 * (hence we SKIP_DRAW) 14471 */ 14472 mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND; 14473 mPrivateFlags |= PFLAG_SKIP_DRAW; 14474 } 14475 14476 /* 14477 * When the background is set, we try to apply its padding to this 14478 * View. When the background is removed, we don't touch this View's 14479 * padding. This is noted in the Javadocs. Hence, we don't need to 14480 * requestLayout(), the invalidate() below is sufficient. 14481 */ 14482 14483 // The old background's minimum size could have affected this 14484 // View's layout, so let's requestLayout 14485 requestLayout = true; 14486 } 14487 14488 computeOpaqueFlags(); 14489 14490 if (requestLayout) { 14491 requestLayout(); 14492 } 14493 14494 mBackgroundSizeChanged = true; 14495 invalidate(true); 14496 } 14497 14498 /** 14499 * Gets the background drawable 14500 * 14501 * @return The drawable used as the background for this view, if any. 14502 * 14503 * @see #setBackground(Drawable) 14504 * 14505 * @attr ref android.R.styleable#View_background 14506 */ 14507 public Drawable getBackground() { 14508 return mBackground; 14509 } 14510 14511 /** 14512 * Sets the padding. The view may add on the space required to display 14513 * the scrollbars, depending on the style and visibility of the scrollbars. 14514 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 14515 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 14516 * from the values set in this call. 14517 * 14518 * @attr ref android.R.styleable#View_padding 14519 * @attr ref android.R.styleable#View_paddingBottom 14520 * @attr ref android.R.styleable#View_paddingLeft 14521 * @attr ref android.R.styleable#View_paddingRight 14522 * @attr ref android.R.styleable#View_paddingTop 14523 * @param left the left padding in pixels 14524 * @param top the top padding in pixels 14525 * @param right the right padding in pixels 14526 * @param bottom the bottom padding in pixels 14527 */ 14528 public void setPadding(int left, int top, int right, int bottom) { 14529 resetResolvedPadding(); 14530 14531 mUserPaddingStart = UNDEFINED_PADDING; 14532 mUserPaddingEnd = UNDEFINED_PADDING; 14533 14534 mUserPaddingLeftInitial = left; 14535 mUserPaddingRightInitial = right; 14536 14537 internalSetPadding(left, top, right, bottom); 14538 } 14539 14540 /** 14541 * @hide 14542 */ 14543 protected void internalSetPadding(int left, int top, int right, int bottom) { 14544 mUserPaddingLeft = left; 14545 mUserPaddingRight = right; 14546 mUserPaddingBottom = bottom; 14547 14548 final int viewFlags = mViewFlags; 14549 boolean changed = false; 14550 14551 // Common case is there are no scroll bars. 14552 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 14553 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 14554 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 14555 ? 0 : getVerticalScrollbarWidth(); 14556 switch (mVerticalScrollbarPosition) { 14557 case SCROLLBAR_POSITION_DEFAULT: 14558 if (isLayoutRtl()) { 14559 left += offset; 14560 } else { 14561 right += offset; 14562 } 14563 break; 14564 case SCROLLBAR_POSITION_RIGHT: 14565 right += offset; 14566 break; 14567 case SCROLLBAR_POSITION_LEFT: 14568 left += offset; 14569 break; 14570 } 14571 } 14572 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 14573 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 14574 ? 0 : getHorizontalScrollbarHeight(); 14575 } 14576 } 14577 14578 if (mPaddingLeft != left) { 14579 changed = true; 14580 mPaddingLeft = left; 14581 } 14582 if (mPaddingTop != top) { 14583 changed = true; 14584 mPaddingTop = top; 14585 } 14586 if (mPaddingRight != right) { 14587 changed = true; 14588 mPaddingRight = right; 14589 } 14590 if (mPaddingBottom != bottom) { 14591 changed = true; 14592 mPaddingBottom = bottom; 14593 } 14594 14595 if (changed) { 14596 requestLayout(); 14597 } 14598 } 14599 14600 /** 14601 * Sets the relative padding. The view may add on the space required to display 14602 * the scrollbars, depending on the style and visibility of the scrollbars. 14603 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 14604 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 14605 * from the values set in this call. 14606 * 14607 * @attr ref android.R.styleable#View_padding 14608 * @attr ref android.R.styleable#View_paddingBottom 14609 * @attr ref android.R.styleable#View_paddingStart 14610 * @attr ref android.R.styleable#View_paddingEnd 14611 * @attr ref android.R.styleable#View_paddingTop 14612 * @param start the start padding in pixels 14613 * @param top the top padding in pixels 14614 * @param end the end padding in pixels 14615 * @param bottom the bottom padding in pixels 14616 */ 14617 public void setPaddingRelative(int start, int top, int end, int bottom) { 14618 resetResolvedPadding(); 14619 14620 mUserPaddingStart = start; 14621 mUserPaddingEnd = end; 14622 14623 switch(getLayoutDirection()) { 14624 case LAYOUT_DIRECTION_RTL: 14625 mUserPaddingLeftInitial = end; 14626 mUserPaddingRightInitial = start; 14627 internalSetPadding(end, top, start, bottom); 14628 break; 14629 case LAYOUT_DIRECTION_LTR: 14630 default: 14631 mUserPaddingLeftInitial = start; 14632 mUserPaddingRightInitial = end; 14633 internalSetPadding(start, top, end, bottom); 14634 } 14635 } 14636 14637 /** 14638 * Returns the top padding of this view. 14639 * 14640 * @return the top padding in pixels 14641 */ 14642 public int getPaddingTop() { 14643 return mPaddingTop; 14644 } 14645 14646 /** 14647 * Returns the bottom padding of this view. If there are inset and enabled 14648 * scrollbars, this value may include the space required to display the 14649 * scrollbars as well. 14650 * 14651 * @return the bottom padding in pixels 14652 */ 14653 public int getPaddingBottom() { 14654 return mPaddingBottom; 14655 } 14656 14657 /** 14658 * Returns the left padding of this view. If there are inset and enabled 14659 * scrollbars, this value may include the space required to display the 14660 * scrollbars as well. 14661 * 14662 * @return the left padding in pixels 14663 */ 14664 public int getPaddingLeft() { 14665 if (!isPaddingResolved()) { 14666 resolvePadding(); 14667 } 14668 return mPaddingLeft; 14669 } 14670 14671 /** 14672 * Returns the start padding of this view depending on its resolved layout direction. 14673 * If there are inset and enabled scrollbars, this value may include the space 14674 * required to display the scrollbars as well. 14675 * 14676 * @return the start padding in pixels 14677 */ 14678 public int getPaddingStart() { 14679 if (!isPaddingResolved()) { 14680 resolvePadding(); 14681 } 14682 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 14683 mPaddingRight : mPaddingLeft; 14684 } 14685 14686 /** 14687 * Returns the right padding of this view. If there are inset and enabled 14688 * scrollbars, this value may include the space required to display the 14689 * scrollbars as well. 14690 * 14691 * @return the right padding in pixels 14692 */ 14693 public int getPaddingRight() { 14694 if (!isPaddingResolved()) { 14695 resolvePadding(); 14696 } 14697 return mPaddingRight; 14698 } 14699 14700 /** 14701 * Returns the end padding of this view depending on its resolved layout direction. 14702 * If there are inset and enabled scrollbars, this value may include the space 14703 * required to display the scrollbars as well. 14704 * 14705 * @return the end padding in pixels 14706 */ 14707 public int getPaddingEnd() { 14708 if (!isPaddingResolved()) { 14709 resolvePadding(); 14710 } 14711 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 14712 mPaddingLeft : mPaddingRight; 14713 } 14714 14715 /** 14716 * Return if the padding as been set thru relative values 14717 * {@link #setPaddingRelative(int, int, int, int)} or thru 14718 * @attr ref android.R.styleable#View_paddingStart or 14719 * @attr ref android.R.styleable#View_paddingEnd 14720 * 14721 * @return true if the padding is relative or false if it is not. 14722 */ 14723 public boolean isPaddingRelative() { 14724 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 14725 } 14726 14727 Insets computeOpticalInsets() { 14728 return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets(); 14729 } 14730 14731 /** 14732 * @hide 14733 */ 14734 public Insets getOpticalInsets() { 14735 if (mLayoutInsets == null) { 14736 mLayoutInsets = computeOpticalInsets(); 14737 } 14738 return mLayoutInsets; 14739 } 14740 14741 /** 14742 * Changes the selection state of this view. A view can be selected or not. 14743 * Note that selection is not the same as focus. Views are typically 14744 * selected in the context of an AdapterView like ListView or GridView; 14745 * the selected view is the view that is highlighted. 14746 * 14747 * @param selected true if the view must be selected, false otherwise 14748 */ 14749 public void setSelected(boolean selected) { 14750 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 14751 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 14752 if (!selected) resetPressedState(); 14753 invalidate(true); 14754 refreshDrawableState(); 14755 dispatchSetSelected(selected); 14756 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 14757 notifyAccessibilityStateChanged(); 14758 } 14759 } 14760 } 14761 14762 /** 14763 * Dispatch setSelected to all of this View's children. 14764 * 14765 * @see #setSelected(boolean) 14766 * 14767 * @param selected The new selected state 14768 */ 14769 protected void dispatchSetSelected(boolean selected) { 14770 } 14771 14772 /** 14773 * Indicates the selection state of this view. 14774 * 14775 * @return true if the view is selected, false otherwise 14776 */ 14777 @ViewDebug.ExportedProperty 14778 public boolean isSelected() { 14779 return (mPrivateFlags & PFLAG_SELECTED) != 0; 14780 } 14781 14782 /** 14783 * Changes the activated state of this view. A view can be activated or not. 14784 * Note that activation is not the same as selection. Selection is 14785 * a transient property, representing the view (hierarchy) the user is 14786 * currently interacting with. Activation is a longer-term state that the 14787 * user can move views in and out of. For example, in a list view with 14788 * single or multiple selection enabled, the views in the current selection 14789 * set are activated. (Um, yeah, we are deeply sorry about the terminology 14790 * here.) The activated state is propagated down to children of the view it 14791 * is set on. 14792 * 14793 * @param activated true if the view must be activated, false otherwise 14794 */ 14795 public void setActivated(boolean activated) { 14796 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 14797 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 14798 invalidate(true); 14799 refreshDrawableState(); 14800 dispatchSetActivated(activated); 14801 } 14802 } 14803 14804 /** 14805 * Dispatch setActivated to all of this View's children. 14806 * 14807 * @see #setActivated(boolean) 14808 * 14809 * @param activated The new activated state 14810 */ 14811 protected void dispatchSetActivated(boolean activated) { 14812 } 14813 14814 /** 14815 * Indicates the activation state of this view. 14816 * 14817 * @return true if the view is activated, false otherwise 14818 */ 14819 @ViewDebug.ExportedProperty 14820 public boolean isActivated() { 14821 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 14822 } 14823 14824 /** 14825 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 14826 * observer can be used to get notifications when global events, like 14827 * layout, happen. 14828 * 14829 * The returned ViewTreeObserver observer is not guaranteed to remain 14830 * valid for the lifetime of this View. If the caller of this method keeps 14831 * a long-lived reference to ViewTreeObserver, it should always check for 14832 * the return value of {@link ViewTreeObserver#isAlive()}. 14833 * 14834 * @return The ViewTreeObserver for this view's hierarchy. 14835 */ 14836 public ViewTreeObserver getViewTreeObserver() { 14837 if (mAttachInfo != null) { 14838 return mAttachInfo.mTreeObserver; 14839 } 14840 if (mFloatingTreeObserver == null) { 14841 mFloatingTreeObserver = new ViewTreeObserver(); 14842 } 14843 return mFloatingTreeObserver; 14844 } 14845 14846 /** 14847 * <p>Finds the topmost view in the current view hierarchy.</p> 14848 * 14849 * @return the topmost view containing this view 14850 */ 14851 public View getRootView() { 14852 if (mAttachInfo != null) { 14853 final View v = mAttachInfo.mRootView; 14854 if (v != null) { 14855 return v; 14856 } 14857 } 14858 14859 View parent = this; 14860 14861 while (parent.mParent != null && parent.mParent instanceof View) { 14862 parent = (View) parent.mParent; 14863 } 14864 14865 return parent; 14866 } 14867 14868 /** 14869 * <p>Computes the coordinates of this view on the screen. The argument 14870 * must be an array of two integers. After the method returns, the array 14871 * contains the x and y location in that order.</p> 14872 * 14873 * @param location an array of two integers in which to hold the coordinates 14874 */ 14875 public void getLocationOnScreen(int[] location) { 14876 getLocationInWindow(location); 14877 14878 final AttachInfo info = mAttachInfo; 14879 if (info != null) { 14880 location[0] += info.mWindowLeft; 14881 location[1] += info.mWindowTop; 14882 } 14883 } 14884 14885 /** 14886 * <p>Computes the coordinates of this view in its window. The argument 14887 * must be an array of two integers. After the method returns, the array 14888 * contains the x and y location in that order.</p> 14889 * 14890 * @param location an array of two integers in which to hold the coordinates 14891 */ 14892 public void getLocationInWindow(int[] location) { 14893 if (location == null || location.length < 2) { 14894 throw new IllegalArgumentException("location must be an array of two integers"); 14895 } 14896 14897 if (mAttachInfo == null) { 14898 // When the view is not attached to a window, this method does not make sense 14899 location[0] = location[1] = 0; 14900 return; 14901 } 14902 14903 float[] position = mAttachInfo.mTmpTransformLocation; 14904 position[0] = position[1] = 0.0f; 14905 14906 if (!hasIdentityMatrix()) { 14907 getMatrix().mapPoints(position); 14908 } 14909 14910 position[0] += mLeft; 14911 position[1] += mTop; 14912 14913 ViewParent viewParent = mParent; 14914 while (viewParent instanceof View) { 14915 final View view = (View) viewParent; 14916 14917 position[0] -= view.mScrollX; 14918 position[1] -= view.mScrollY; 14919 14920 if (!view.hasIdentityMatrix()) { 14921 view.getMatrix().mapPoints(position); 14922 } 14923 14924 position[0] += view.mLeft; 14925 position[1] += view.mTop; 14926 14927 viewParent = view.mParent; 14928 } 14929 14930 if (viewParent instanceof ViewRootImpl) { 14931 // *cough* 14932 final ViewRootImpl vr = (ViewRootImpl) viewParent; 14933 position[1] -= vr.mCurScrollY; 14934 } 14935 14936 location[0] = (int) (position[0] + 0.5f); 14937 location[1] = (int) (position[1] + 0.5f); 14938 } 14939 14940 /** 14941 * {@hide} 14942 * @param id the id of the view to be found 14943 * @return the view of the specified id, null if cannot be found 14944 */ 14945 protected View findViewTraversal(int id) { 14946 if (id == mID) { 14947 return this; 14948 } 14949 return null; 14950 } 14951 14952 /** 14953 * {@hide} 14954 * @param tag the tag of the view to be found 14955 * @return the view of specified tag, null if cannot be found 14956 */ 14957 protected View findViewWithTagTraversal(Object tag) { 14958 if (tag != null && tag.equals(mTag)) { 14959 return this; 14960 } 14961 return null; 14962 } 14963 14964 /** 14965 * {@hide} 14966 * @param predicate The predicate to evaluate. 14967 * @param childToSkip If not null, ignores this child during the recursive traversal. 14968 * @return The first view that matches the predicate or null. 14969 */ 14970 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 14971 if (predicate.apply(this)) { 14972 return this; 14973 } 14974 return null; 14975 } 14976 14977 /** 14978 * Look for a child view with the given id. If this view has the given 14979 * id, return this view. 14980 * 14981 * @param id The id to search for. 14982 * @return The view that has the given id in the hierarchy or null 14983 */ 14984 public final View findViewById(int id) { 14985 if (id < 0) { 14986 return null; 14987 } 14988 return findViewTraversal(id); 14989 } 14990 14991 /** 14992 * Finds a view by its unuque and stable accessibility id. 14993 * 14994 * @param accessibilityId The searched accessibility id. 14995 * @return The found view. 14996 */ 14997 final View findViewByAccessibilityId(int accessibilityId) { 14998 if (accessibilityId < 0) { 14999 return null; 15000 } 15001 return findViewByAccessibilityIdTraversal(accessibilityId); 15002 } 15003 15004 /** 15005 * Performs the traversal to find a view by its unuque and stable accessibility id. 15006 * 15007 * <strong>Note:</strong>This method does not stop at the root namespace 15008 * boundary since the user can touch the screen at an arbitrary location 15009 * potentially crossing the root namespace bounday which will send an 15010 * accessibility event to accessibility services and they should be able 15011 * to obtain the event source. Also accessibility ids are guaranteed to be 15012 * unique in the window. 15013 * 15014 * @param accessibilityId The accessibility id. 15015 * @return The found view. 15016 */ 15017 View findViewByAccessibilityIdTraversal(int accessibilityId) { 15018 if (getAccessibilityViewId() == accessibilityId) { 15019 return this; 15020 } 15021 return null; 15022 } 15023 15024 /** 15025 * Look for a child view with the given tag. If this view has the given 15026 * tag, return this view. 15027 * 15028 * @param tag The tag to search for, using "tag.equals(getTag())". 15029 * @return The View that has the given tag in the hierarchy or null 15030 */ 15031 public final View findViewWithTag(Object tag) { 15032 if (tag == null) { 15033 return null; 15034 } 15035 return findViewWithTagTraversal(tag); 15036 } 15037 15038 /** 15039 * {@hide} 15040 * Look for a child view that matches the specified predicate. 15041 * If this view matches the predicate, return this view. 15042 * 15043 * @param predicate The predicate to evaluate. 15044 * @return The first view that matches the predicate or null. 15045 */ 15046 public final View findViewByPredicate(Predicate<View> predicate) { 15047 return findViewByPredicateTraversal(predicate, null); 15048 } 15049 15050 /** 15051 * {@hide} 15052 * Look for a child view that matches the specified predicate, 15053 * starting with the specified view and its descendents and then 15054 * recusively searching the ancestors and siblings of that view 15055 * until this view is reached. 15056 * 15057 * This method is useful in cases where the predicate does not match 15058 * a single unique view (perhaps multiple views use the same id) 15059 * and we are trying to find the view that is "closest" in scope to the 15060 * starting view. 15061 * 15062 * @param start The view to start from. 15063 * @param predicate The predicate to evaluate. 15064 * @return The first view that matches the predicate or null. 15065 */ 15066 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 15067 View childToSkip = null; 15068 for (;;) { 15069 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 15070 if (view != null || start == this) { 15071 return view; 15072 } 15073 15074 ViewParent parent = start.getParent(); 15075 if (parent == null || !(parent instanceof View)) { 15076 return null; 15077 } 15078 15079 childToSkip = start; 15080 start = (View) parent; 15081 } 15082 } 15083 15084 /** 15085 * Sets the identifier for this view. The identifier does not have to be 15086 * unique in this view's hierarchy. The identifier should be a positive 15087 * number. 15088 * 15089 * @see #NO_ID 15090 * @see #getId() 15091 * @see #findViewById(int) 15092 * 15093 * @param id a number used to identify the view 15094 * 15095 * @attr ref android.R.styleable#View_id 15096 */ 15097 public void setId(int id) { 15098 mID = id; 15099 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 15100 mID = generateViewId(); 15101 } 15102 } 15103 15104 /** 15105 * {@hide} 15106 * 15107 * @param isRoot true if the view belongs to the root namespace, false 15108 * otherwise 15109 */ 15110 public void setIsRootNamespace(boolean isRoot) { 15111 if (isRoot) { 15112 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 15113 } else { 15114 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 15115 } 15116 } 15117 15118 /** 15119 * {@hide} 15120 * 15121 * @return true if the view belongs to the root namespace, false otherwise 15122 */ 15123 public boolean isRootNamespace() { 15124 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 15125 } 15126 15127 /** 15128 * Returns this view's identifier. 15129 * 15130 * @return a positive integer used to identify the view or {@link #NO_ID} 15131 * if the view has no ID 15132 * 15133 * @see #setId(int) 15134 * @see #findViewById(int) 15135 * @attr ref android.R.styleable#View_id 15136 */ 15137 @ViewDebug.CapturedViewProperty 15138 public int getId() { 15139 return mID; 15140 } 15141 15142 /** 15143 * Returns this view's tag. 15144 * 15145 * @return the Object stored in this view as a tag 15146 * 15147 * @see #setTag(Object) 15148 * @see #getTag(int) 15149 */ 15150 @ViewDebug.ExportedProperty 15151 public Object getTag() { 15152 return mTag; 15153 } 15154 15155 /** 15156 * Sets the tag associated with this view. A tag can be used to mark 15157 * a view in its hierarchy and does not have to be unique within the 15158 * hierarchy. Tags can also be used to store data within a view without 15159 * resorting to another data structure. 15160 * 15161 * @param tag an Object to tag the view with 15162 * 15163 * @see #getTag() 15164 * @see #setTag(int, Object) 15165 */ 15166 public void setTag(final Object tag) { 15167 mTag = tag; 15168 } 15169 15170 /** 15171 * Returns the tag associated with this view and the specified key. 15172 * 15173 * @param key The key identifying the tag 15174 * 15175 * @return the Object stored in this view as a tag 15176 * 15177 * @see #setTag(int, Object) 15178 * @see #getTag() 15179 */ 15180 public Object getTag(int key) { 15181 if (mKeyedTags != null) return mKeyedTags.get(key); 15182 return null; 15183 } 15184 15185 /** 15186 * Sets a tag associated with this view and a key. A tag can be used 15187 * to mark a view in its hierarchy and does not have to be unique within 15188 * the hierarchy. Tags can also be used to store data within a view 15189 * without resorting to another data structure. 15190 * 15191 * The specified key should be an id declared in the resources of the 15192 * application to ensure it is unique (see the <a 15193 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 15194 * Keys identified as belonging to 15195 * the Android framework or not associated with any package will cause 15196 * an {@link IllegalArgumentException} to be thrown. 15197 * 15198 * @param key The key identifying the tag 15199 * @param tag An Object to tag the view with 15200 * 15201 * @throws IllegalArgumentException If they specified key is not valid 15202 * 15203 * @see #setTag(Object) 15204 * @see #getTag(int) 15205 */ 15206 public void setTag(int key, final Object tag) { 15207 // If the package id is 0x00 or 0x01, it's either an undefined package 15208 // or a framework id 15209 if ((key >>> 24) < 2) { 15210 throw new IllegalArgumentException("The key must be an application-specific " 15211 + "resource id."); 15212 } 15213 15214 setKeyedTag(key, tag); 15215 } 15216 15217 /** 15218 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 15219 * framework id. 15220 * 15221 * @hide 15222 */ 15223 public void setTagInternal(int key, Object tag) { 15224 if ((key >>> 24) != 0x1) { 15225 throw new IllegalArgumentException("The key must be a framework-specific " 15226 + "resource id."); 15227 } 15228 15229 setKeyedTag(key, tag); 15230 } 15231 15232 private void setKeyedTag(int key, Object tag) { 15233 if (mKeyedTags == null) { 15234 mKeyedTags = new SparseArray<Object>(); 15235 } 15236 15237 mKeyedTags.put(key, tag); 15238 } 15239 15240 /** 15241 * Prints information about this view in the log output, with the tag 15242 * {@link #VIEW_LOG_TAG}. 15243 * 15244 * @hide 15245 */ 15246 public void debug() { 15247 debug(0); 15248 } 15249 15250 /** 15251 * Prints information about this view in the log output, with the tag 15252 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 15253 * indentation defined by the <code>depth</code>. 15254 * 15255 * @param depth the indentation level 15256 * 15257 * @hide 15258 */ 15259 protected void debug(int depth) { 15260 String output = debugIndent(depth - 1); 15261 15262 output += "+ " + this; 15263 int id = getId(); 15264 if (id != -1) { 15265 output += " (id=" + id + ")"; 15266 } 15267 Object tag = getTag(); 15268 if (tag != null) { 15269 output += " (tag=" + tag + ")"; 15270 } 15271 Log.d(VIEW_LOG_TAG, output); 15272 15273 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 15274 output = debugIndent(depth) + " FOCUSED"; 15275 Log.d(VIEW_LOG_TAG, output); 15276 } 15277 15278 output = debugIndent(depth); 15279 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 15280 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 15281 + "} "; 15282 Log.d(VIEW_LOG_TAG, output); 15283 15284 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 15285 || mPaddingBottom != 0) { 15286 output = debugIndent(depth); 15287 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 15288 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 15289 Log.d(VIEW_LOG_TAG, output); 15290 } 15291 15292 output = debugIndent(depth); 15293 output += "mMeasureWidth=" + mMeasuredWidth + 15294 " mMeasureHeight=" + mMeasuredHeight; 15295 Log.d(VIEW_LOG_TAG, output); 15296 15297 output = debugIndent(depth); 15298 if (mLayoutParams == null) { 15299 output += "BAD! no layout params"; 15300 } else { 15301 output = mLayoutParams.debug(output); 15302 } 15303 Log.d(VIEW_LOG_TAG, output); 15304 15305 output = debugIndent(depth); 15306 output += "flags={"; 15307 output += View.printFlags(mViewFlags); 15308 output += "}"; 15309 Log.d(VIEW_LOG_TAG, output); 15310 15311 output = debugIndent(depth); 15312 output += "privateFlags={"; 15313 output += View.printPrivateFlags(mPrivateFlags); 15314 output += "}"; 15315 Log.d(VIEW_LOG_TAG, output); 15316 } 15317 15318 /** 15319 * Creates a string of whitespaces used for indentation. 15320 * 15321 * @param depth the indentation level 15322 * @return a String containing (depth * 2 + 3) * 2 white spaces 15323 * 15324 * @hide 15325 */ 15326 protected static String debugIndent(int depth) { 15327 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 15328 for (int i = 0; i < (depth * 2) + 3; i++) { 15329 spaces.append(' ').append(' '); 15330 } 15331 return spaces.toString(); 15332 } 15333 15334 /** 15335 * <p>Return the offset of the widget's text baseline from the widget's top 15336 * boundary. If this widget does not support baseline alignment, this 15337 * method returns -1. </p> 15338 * 15339 * @return the offset of the baseline within the widget's bounds or -1 15340 * if baseline alignment is not supported 15341 */ 15342 @ViewDebug.ExportedProperty(category = "layout") 15343 public int getBaseline() { 15344 return -1; 15345 } 15346 15347 /** 15348 * Returns whether the view hierarchy is currently undergoing a layout pass. This 15349 * information is useful to avoid situations such as calling {@link #requestLayout()} during 15350 * a layout pass. 15351 * 15352 * @return whether the view hierarchy is currently undergoing a layout pass 15353 */ 15354 public boolean isInLayout() { 15355 ViewRootImpl viewRoot = getViewRootImpl(); 15356 return (viewRoot != null && viewRoot.isInLayout()); 15357 } 15358 15359 /** 15360 * Call this when something has changed which has invalidated the 15361 * layout of this view. This will schedule a layout pass of the view 15362 * tree. This should not be called while the view hierarchy is currently in a layout 15363 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 15364 * end of the current layout pass (and then layout will run again) or after the current 15365 * frame is drawn and the next layout occurs. 15366 * 15367 * <p>Subclasses which override this method should call the superclass method to 15368 * handle possible request-during-layout errors correctly.</p> 15369 */ 15370 public void requestLayout() { 15371 ViewRootImpl viewRoot = getViewRootImpl(); 15372 if (viewRoot != null && viewRoot.isInLayout()) { 15373 viewRoot.requestLayoutDuringLayout(this); 15374 return; 15375 } 15376 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 15377 mPrivateFlags |= PFLAG_INVALIDATED; 15378 15379 if (mParent != null && !mParent.isLayoutRequested()) { 15380 mParent.requestLayout(); 15381 } 15382 } 15383 15384 /** 15385 * Forces this view to be laid out during the next layout pass. 15386 * This method does not call requestLayout() or forceLayout() 15387 * on the parent. 15388 */ 15389 public void forceLayout() { 15390 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 15391 mPrivateFlags |= PFLAG_INVALIDATED; 15392 } 15393 15394 /** 15395 * <p> 15396 * This is called to find out how big a view should be. The parent 15397 * supplies constraint information in the width and height parameters. 15398 * </p> 15399 * 15400 * <p> 15401 * The actual measurement work of a view is performed in 15402 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 15403 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 15404 * </p> 15405 * 15406 * 15407 * @param widthMeasureSpec Horizontal space requirements as imposed by the 15408 * parent 15409 * @param heightMeasureSpec Vertical space requirements as imposed by the 15410 * parent 15411 * 15412 * @see #onMeasure(int, int) 15413 */ 15414 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 15415 boolean optical = isLayoutModeOptical(this); 15416 if (optical != isLayoutModeOptical(mParent)) { 15417 Insets insets = getOpticalInsets(); 15418 int oWidth = insets.left + insets.right; 15419 int oHeight = insets.top + insets.bottom; 15420 widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth); 15421 heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight); 15422 } 15423 if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT || 15424 widthMeasureSpec != mOldWidthMeasureSpec || 15425 heightMeasureSpec != mOldHeightMeasureSpec) { 15426 15427 // first clears the measured dimension flag 15428 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 15429 15430 if (!isPaddingResolved()) { 15431 resolvePadding(); 15432 } 15433 15434 // measure ourselves, this should set the measured dimension flag back 15435 onMeasure(widthMeasureSpec, heightMeasureSpec); 15436 15437 // flag not set, setMeasuredDimension() was not invoked, we raise 15438 // an exception to warn the developer 15439 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 15440 throw new IllegalStateException("onMeasure() did not set the" 15441 + " measured dimension by calling" 15442 + " setMeasuredDimension()"); 15443 } 15444 15445 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 15446 } 15447 15448 mOldWidthMeasureSpec = widthMeasureSpec; 15449 mOldHeightMeasureSpec = heightMeasureSpec; 15450 } 15451 15452 /** 15453 * <p> 15454 * Measure the view and its content to determine the measured width and the 15455 * measured height. This method is invoked by {@link #measure(int, int)} and 15456 * should be overriden by subclasses to provide accurate and efficient 15457 * measurement of their contents. 15458 * </p> 15459 * 15460 * <p> 15461 * <strong>CONTRACT:</strong> When overriding this method, you 15462 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 15463 * measured width and height of this view. Failure to do so will trigger an 15464 * <code>IllegalStateException</code>, thrown by 15465 * {@link #measure(int, int)}. Calling the superclass' 15466 * {@link #onMeasure(int, int)} is a valid use. 15467 * </p> 15468 * 15469 * <p> 15470 * The base class implementation of measure defaults to the background size, 15471 * unless a larger size is allowed by the MeasureSpec. Subclasses should 15472 * override {@link #onMeasure(int, int)} to provide better measurements of 15473 * their content. 15474 * </p> 15475 * 15476 * <p> 15477 * If this method is overridden, it is the subclass's responsibility to make 15478 * sure the measured height and width are at least the view's minimum height 15479 * and width ({@link #getSuggestedMinimumHeight()} and 15480 * {@link #getSuggestedMinimumWidth()}). 15481 * </p> 15482 * 15483 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 15484 * The requirements are encoded with 15485 * {@link android.view.View.MeasureSpec}. 15486 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 15487 * The requirements are encoded with 15488 * {@link android.view.View.MeasureSpec}. 15489 * 15490 * @see #getMeasuredWidth() 15491 * @see #getMeasuredHeight() 15492 * @see #setMeasuredDimension(int, int) 15493 * @see #getSuggestedMinimumHeight() 15494 * @see #getSuggestedMinimumWidth() 15495 * @see android.view.View.MeasureSpec#getMode(int) 15496 * @see android.view.View.MeasureSpec#getSize(int) 15497 */ 15498 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 15499 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 15500 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 15501 } 15502 15503 /** 15504 * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the 15505 * measured width and measured height. Failing to do so will trigger an 15506 * exception at measurement time.</p> 15507 * 15508 * @param measuredWidth The measured width of this view. May be a complex 15509 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 15510 * {@link #MEASURED_STATE_TOO_SMALL}. 15511 * @param measuredHeight The measured height of this view. May be a complex 15512 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 15513 * {@link #MEASURED_STATE_TOO_SMALL}. 15514 */ 15515 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 15516 boolean optical = isLayoutModeOptical(this); 15517 if (optical != isLayoutModeOptical(mParent)) { 15518 Insets insets = getOpticalInsets(); 15519 int opticalWidth = insets.left + insets.right; 15520 int opticalHeight = insets.top + insets.bottom; 15521 15522 measuredWidth += optical ? opticalWidth : -opticalWidth; 15523 measuredHeight += optical ? opticalHeight : -opticalHeight; 15524 } 15525 mMeasuredWidth = measuredWidth; 15526 mMeasuredHeight = measuredHeight; 15527 15528 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 15529 } 15530 15531 /** 15532 * Merge two states as returned by {@link #getMeasuredState()}. 15533 * @param curState The current state as returned from a view or the result 15534 * of combining multiple views. 15535 * @param newState The new view state to combine. 15536 * @return Returns a new integer reflecting the combination of the two 15537 * states. 15538 */ 15539 public static int combineMeasuredStates(int curState, int newState) { 15540 return curState | newState; 15541 } 15542 15543 /** 15544 * Version of {@link #resolveSizeAndState(int, int, int)} 15545 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 15546 */ 15547 public static int resolveSize(int size, int measureSpec) { 15548 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 15549 } 15550 15551 /** 15552 * Utility to reconcile a desired size and state, with constraints imposed 15553 * by a MeasureSpec. Will take the desired size, unless a different size 15554 * is imposed by the constraints. The returned value is a compound integer, 15555 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 15556 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 15557 * size is smaller than the size the view wants to be. 15558 * 15559 * @param size How big the view wants to be 15560 * @param measureSpec Constraints imposed by the parent 15561 * @return Size information bit mask as defined by 15562 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 15563 */ 15564 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 15565 int result = size; 15566 int specMode = MeasureSpec.getMode(measureSpec); 15567 int specSize = MeasureSpec.getSize(measureSpec); 15568 switch (specMode) { 15569 case MeasureSpec.UNSPECIFIED: 15570 result = size; 15571 break; 15572 case MeasureSpec.AT_MOST: 15573 if (specSize < size) { 15574 result = specSize | MEASURED_STATE_TOO_SMALL; 15575 } else { 15576 result = size; 15577 } 15578 break; 15579 case MeasureSpec.EXACTLY: 15580 result = specSize; 15581 break; 15582 } 15583 return result | (childMeasuredState&MEASURED_STATE_MASK); 15584 } 15585 15586 /** 15587 * Utility to return a default size. Uses the supplied size if the 15588 * MeasureSpec imposed no constraints. Will get larger if allowed 15589 * by the MeasureSpec. 15590 * 15591 * @param size Default size for this view 15592 * @param measureSpec Constraints imposed by the parent 15593 * @return The size this view should be. 15594 */ 15595 public static int getDefaultSize(int size, int measureSpec) { 15596 int result = size; 15597 int specMode = MeasureSpec.getMode(measureSpec); 15598 int specSize = MeasureSpec.getSize(measureSpec); 15599 15600 switch (specMode) { 15601 case MeasureSpec.UNSPECIFIED: 15602 result = size; 15603 break; 15604 case MeasureSpec.AT_MOST: 15605 case MeasureSpec.EXACTLY: 15606 result = specSize; 15607 break; 15608 } 15609 return result; 15610 } 15611 15612 /** 15613 * Returns the suggested minimum height that the view should use. This 15614 * returns the maximum of the view's minimum height 15615 * and the background's minimum height 15616 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 15617 * <p> 15618 * When being used in {@link #onMeasure(int, int)}, the caller should still 15619 * ensure the returned height is within the requirements of the parent. 15620 * 15621 * @return The suggested minimum height of the view. 15622 */ 15623 protected int getSuggestedMinimumHeight() { 15624 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 15625 15626 } 15627 15628 /** 15629 * Returns the suggested minimum width that the view should use. This 15630 * returns the maximum of the view's minimum width) 15631 * and the background's minimum width 15632 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 15633 * <p> 15634 * When being used in {@link #onMeasure(int, int)}, the caller should still 15635 * ensure the returned width is within the requirements of the parent. 15636 * 15637 * @return The suggested minimum width of the view. 15638 */ 15639 protected int getSuggestedMinimumWidth() { 15640 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 15641 } 15642 15643 /** 15644 * Returns the minimum height of the view. 15645 * 15646 * @return the minimum height the view will try to be. 15647 * 15648 * @see #setMinimumHeight(int) 15649 * 15650 * @attr ref android.R.styleable#View_minHeight 15651 */ 15652 public int getMinimumHeight() { 15653 return mMinHeight; 15654 } 15655 15656 /** 15657 * Sets the minimum height of the view. It is not guaranteed the view will 15658 * be able to achieve this minimum height (for example, if its parent layout 15659 * constrains it with less available height). 15660 * 15661 * @param minHeight The minimum height the view will try to be. 15662 * 15663 * @see #getMinimumHeight() 15664 * 15665 * @attr ref android.R.styleable#View_minHeight 15666 */ 15667 public void setMinimumHeight(int minHeight) { 15668 mMinHeight = minHeight; 15669 requestLayout(); 15670 } 15671 15672 /** 15673 * Returns the minimum width of the view. 15674 * 15675 * @return the minimum width the view will try to be. 15676 * 15677 * @see #setMinimumWidth(int) 15678 * 15679 * @attr ref android.R.styleable#View_minWidth 15680 */ 15681 public int getMinimumWidth() { 15682 return mMinWidth; 15683 } 15684 15685 /** 15686 * Sets the minimum width of the view. It is not guaranteed the view will 15687 * be able to achieve this minimum width (for example, if its parent layout 15688 * constrains it with less available width). 15689 * 15690 * @param minWidth The minimum width the view will try to be. 15691 * 15692 * @see #getMinimumWidth() 15693 * 15694 * @attr ref android.R.styleable#View_minWidth 15695 */ 15696 public void setMinimumWidth(int minWidth) { 15697 mMinWidth = minWidth; 15698 requestLayout(); 15699 15700 } 15701 15702 /** 15703 * Get the animation currently associated with this view. 15704 * 15705 * @return The animation that is currently playing or 15706 * scheduled to play for this view. 15707 */ 15708 public Animation getAnimation() { 15709 return mCurrentAnimation; 15710 } 15711 15712 /** 15713 * Start the specified animation now. 15714 * 15715 * @param animation the animation to start now 15716 */ 15717 public void startAnimation(Animation animation) { 15718 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 15719 setAnimation(animation); 15720 invalidateParentCaches(); 15721 invalidate(true); 15722 } 15723 15724 /** 15725 * Cancels any animations for this view. 15726 */ 15727 public void clearAnimation() { 15728 if (mCurrentAnimation != null) { 15729 mCurrentAnimation.detach(); 15730 } 15731 mCurrentAnimation = null; 15732 invalidateParentIfNeeded(); 15733 } 15734 15735 /** 15736 * Sets the next animation to play for this view. 15737 * If you want the animation to play immediately, use 15738 * {@link #startAnimation(android.view.animation.Animation)} instead. 15739 * This method provides allows fine-grained 15740 * control over the start time and invalidation, but you 15741 * must make sure that 1) the animation has a start time set, and 15742 * 2) the view's parent (which controls animations on its children) 15743 * will be invalidated when the animation is supposed to 15744 * start. 15745 * 15746 * @param animation The next animation, or null. 15747 */ 15748 public void setAnimation(Animation animation) { 15749 mCurrentAnimation = animation; 15750 15751 if (animation != null) { 15752 // If the screen is off assume the animation start time is now instead of 15753 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 15754 // would cause the animation to start when the screen turns back on 15755 if (mAttachInfo != null && !mAttachInfo.mScreenOn && 15756 animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 15757 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 15758 } 15759 animation.reset(); 15760 } 15761 } 15762 15763 /** 15764 * Invoked by a parent ViewGroup to notify the start of the animation 15765 * currently associated with this view. If you override this method, 15766 * always call super.onAnimationStart(); 15767 * 15768 * @see #setAnimation(android.view.animation.Animation) 15769 * @see #getAnimation() 15770 */ 15771 protected void onAnimationStart() { 15772 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 15773 } 15774 15775 /** 15776 * Invoked by a parent ViewGroup to notify the end of the animation 15777 * currently associated with this view. If you override this method, 15778 * always call super.onAnimationEnd(); 15779 * 15780 * @see #setAnimation(android.view.animation.Animation) 15781 * @see #getAnimation() 15782 */ 15783 protected void onAnimationEnd() { 15784 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 15785 } 15786 15787 /** 15788 * Invoked if there is a Transform that involves alpha. Subclass that can 15789 * draw themselves with the specified alpha should return true, and then 15790 * respect that alpha when their onDraw() is called. If this returns false 15791 * then the view may be redirected to draw into an offscreen buffer to 15792 * fulfill the request, which will look fine, but may be slower than if the 15793 * subclass handles it internally. The default implementation returns false. 15794 * 15795 * @param alpha The alpha (0..255) to apply to the view's drawing 15796 * @return true if the view can draw with the specified alpha. 15797 */ 15798 protected boolean onSetAlpha(int alpha) { 15799 return false; 15800 } 15801 15802 /** 15803 * This is used by the RootView to perform an optimization when 15804 * the view hierarchy contains one or several SurfaceView. 15805 * SurfaceView is always considered transparent, but its children are not, 15806 * therefore all View objects remove themselves from the global transparent 15807 * region (passed as a parameter to this function). 15808 * 15809 * @param region The transparent region for this ViewAncestor (window). 15810 * 15811 * @return Returns true if the effective visibility of the view at this 15812 * point is opaque, regardless of the transparent region; returns false 15813 * if it is possible for underlying windows to be seen behind the view. 15814 * 15815 * {@hide} 15816 */ 15817 public boolean gatherTransparentRegion(Region region) { 15818 final AttachInfo attachInfo = mAttachInfo; 15819 if (region != null && attachInfo != null) { 15820 final int pflags = mPrivateFlags; 15821 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 15822 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 15823 // remove it from the transparent region. 15824 final int[] location = attachInfo.mTransparentLocation; 15825 getLocationInWindow(location); 15826 region.op(location[0], location[1], location[0] + mRight - mLeft, 15827 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 15828 } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) { 15829 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 15830 // exists, so we remove the background drawable's non-transparent 15831 // parts from this transparent region. 15832 applyDrawableToTransparentRegion(mBackground, region); 15833 } 15834 } 15835 return true; 15836 } 15837 15838 /** 15839 * Play a sound effect for this view. 15840 * 15841 * <p>The framework will play sound effects for some built in actions, such as 15842 * clicking, but you may wish to play these effects in your widget, 15843 * for instance, for internal navigation. 15844 * 15845 * <p>The sound effect will only be played if sound effects are enabled by the user, and 15846 * {@link #isSoundEffectsEnabled()} is true. 15847 * 15848 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 15849 */ 15850 public void playSoundEffect(int soundConstant) { 15851 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 15852 return; 15853 } 15854 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 15855 } 15856 15857 /** 15858 * BZZZTT!!1! 15859 * 15860 * <p>Provide haptic feedback to the user for this view. 15861 * 15862 * <p>The framework will provide haptic feedback for some built in actions, 15863 * such as long presses, but you may wish to provide feedback for your 15864 * own widget. 15865 * 15866 * <p>The feedback will only be performed if 15867 * {@link #isHapticFeedbackEnabled()} is true. 15868 * 15869 * @param feedbackConstant One of the constants defined in 15870 * {@link HapticFeedbackConstants} 15871 */ 15872 public boolean performHapticFeedback(int feedbackConstant) { 15873 return performHapticFeedback(feedbackConstant, 0); 15874 } 15875 15876 /** 15877 * BZZZTT!!1! 15878 * 15879 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 15880 * 15881 * @param feedbackConstant One of the constants defined in 15882 * {@link HapticFeedbackConstants} 15883 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 15884 */ 15885 public boolean performHapticFeedback(int feedbackConstant, int flags) { 15886 if (mAttachInfo == null) { 15887 return false; 15888 } 15889 //noinspection SimplifiableIfStatement 15890 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 15891 && !isHapticFeedbackEnabled()) { 15892 return false; 15893 } 15894 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 15895 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 15896 } 15897 15898 /** 15899 * Request that the visibility of the status bar or other screen/window 15900 * decorations be changed. 15901 * 15902 * <p>This method is used to put the over device UI into temporary modes 15903 * where the user's attention is focused more on the application content, 15904 * by dimming or hiding surrounding system affordances. This is typically 15905 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 15906 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 15907 * to be placed behind the action bar (and with these flags other system 15908 * affordances) so that smooth transitions between hiding and showing them 15909 * can be done. 15910 * 15911 * <p>Two representative examples of the use of system UI visibility is 15912 * implementing a content browsing application (like a magazine reader) 15913 * and a video playing application. 15914 * 15915 * <p>The first code shows a typical implementation of a View in a content 15916 * browsing application. In this implementation, the application goes 15917 * into a content-oriented mode by hiding the status bar and action bar, 15918 * and putting the navigation elements into lights out mode. The user can 15919 * then interact with content while in this mode. Such an application should 15920 * provide an easy way for the user to toggle out of the mode (such as to 15921 * check information in the status bar or access notifications). In the 15922 * implementation here, this is done simply by tapping on the content. 15923 * 15924 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 15925 * content} 15926 * 15927 * <p>This second code sample shows a typical implementation of a View 15928 * in a video playing application. In this situation, while the video is 15929 * playing the application would like to go into a complete full-screen mode, 15930 * to use as much of the display as possible for the video. When in this state 15931 * the user can not interact with the application; the system intercepts 15932 * touching on the screen to pop the UI out of full screen mode. See 15933 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 15934 * 15935 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 15936 * content} 15937 * 15938 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 15939 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 15940 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 15941 * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}. 15942 */ 15943 public void setSystemUiVisibility(int visibility) { 15944 if (visibility != mSystemUiVisibility) { 15945 mSystemUiVisibility = visibility; 15946 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 15947 mParent.recomputeViewAttributes(this); 15948 } 15949 } 15950 } 15951 15952 /** 15953 * Returns the last {@link #setSystemUiVisibility(int) that this view has requested. 15954 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 15955 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 15956 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 15957 * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}. 15958 */ 15959 public int getSystemUiVisibility() { 15960 return mSystemUiVisibility; 15961 } 15962 15963 /** 15964 * Returns the current system UI visibility that is currently set for 15965 * the entire window. This is the combination of the 15966 * {@link #setSystemUiVisibility(int)} values supplied by all of the 15967 * views in the window. 15968 */ 15969 public int getWindowSystemUiVisibility() { 15970 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 15971 } 15972 15973 /** 15974 * Override to find out when the window's requested system UI visibility 15975 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 15976 * This is different from the callbacks recieved through 15977 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 15978 * in that this is only telling you about the local request of the window, 15979 * not the actual values applied by the system. 15980 */ 15981 public void onWindowSystemUiVisibilityChanged(int visible) { 15982 } 15983 15984 /** 15985 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 15986 * the view hierarchy. 15987 */ 15988 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 15989 onWindowSystemUiVisibilityChanged(visible); 15990 } 15991 15992 /** 15993 * Set a listener to receive callbacks when the visibility of the system bar changes. 15994 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 15995 */ 15996 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 15997 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 15998 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 15999 mParent.recomputeViewAttributes(this); 16000 } 16001 } 16002 16003 /** 16004 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 16005 * the view hierarchy. 16006 */ 16007 public void dispatchSystemUiVisibilityChanged(int visibility) { 16008 ListenerInfo li = mListenerInfo; 16009 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 16010 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 16011 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 16012 } 16013 } 16014 16015 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 16016 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 16017 if (val != mSystemUiVisibility) { 16018 setSystemUiVisibility(val); 16019 return true; 16020 } 16021 return false; 16022 } 16023 16024 /** @hide */ 16025 public void setDisabledSystemUiVisibility(int flags) { 16026 if (mAttachInfo != null) { 16027 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 16028 mAttachInfo.mDisabledSystemUiVisibility = flags; 16029 if (mParent != null) { 16030 mParent.recomputeViewAttributes(this); 16031 } 16032 } 16033 } 16034 } 16035 16036 /** 16037 * Creates an image that the system displays during the drag and drop 16038 * operation. This is called a "drag shadow". The default implementation 16039 * for a DragShadowBuilder based on a View returns an image that has exactly the same 16040 * appearance as the given View. The default also positions the center of the drag shadow 16041 * directly under the touch point. If no View is provided (the constructor with no parameters 16042 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 16043 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 16044 * default is an invisible drag shadow. 16045 * <p> 16046 * You are not required to use the View you provide to the constructor as the basis of the 16047 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 16048 * anything you want as the drag shadow. 16049 * </p> 16050 * <p> 16051 * You pass a DragShadowBuilder object to the system when you start the drag. The system 16052 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 16053 * size and position of the drag shadow. It uses this data to construct a 16054 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 16055 * so that your application can draw the shadow image in the Canvas. 16056 * </p> 16057 * 16058 * <div class="special reference"> 16059 * <h3>Developer Guides</h3> 16060 * <p>For a guide to implementing drag and drop features, read the 16061 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 16062 * </div> 16063 */ 16064 public static class DragShadowBuilder { 16065 private final WeakReference<View> mView; 16066 16067 /** 16068 * Constructs a shadow image builder based on a View. By default, the resulting drag 16069 * shadow will have the same appearance and dimensions as the View, with the touch point 16070 * over the center of the View. 16071 * @param view A View. Any View in scope can be used. 16072 */ 16073 public DragShadowBuilder(View view) { 16074 mView = new WeakReference<View>(view); 16075 } 16076 16077 /** 16078 * Construct a shadow builder object with no associated View. This 16079 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 16080 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 16081 * to supply the drag shadow's dimensions and appearance without 16082 * reference to any View object. If they are not overridden, then the result is an 16083 * invisible drag shadow. 16084 */ 16085 public DragShadowBuilder() { 16086 mView = new WeakReference<View>(null); 16087 } 16088 16089 /** 16090 * Returns the View object that had been passed to the 16091 * {@link #View.DragShadowBuilder(View)} 16092 * constructor. If that View parameter was {@code null} or if the 16093 * {@link #View.DragShadowBuilder()} 16094 * constructor was used to instantiate the builder object, this method will return 16095 * null. 16096 * 16097 * @return The View object associate with this builder object. 16098 */ 16099 @SuppressWarnings({"JavadocReference"}) 16100 final public View getView() { 16101 return mView.get(); 16102 } 16103 16104 /** 16105 * Provides the metrics for the shadow image. These include the dimensions of 16106 * the shadow image, and the point within that shadow that should 16107 * be centered under the touch location while dragging. 16108 * <p> 16109 * The default implementation sets the dimensions of the shadow to be the 16110 * same as the dimensions of the View itself and centers the shadow under 16111 * the touch point. 16112 * </p> 16113 * 16114 * @param shadowSize A {@link android.graphics.Point} containing the width and height 16115 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 16116 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 16117 * image. 16118 * 16119 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 16120 * shadow image that should be underneath the touch point during the drag and drop 16121 * operation. Your application must set {@link android.graphics.Point#x} to the 16122 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 16123 */ 16124 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 16125 final View view = mView.get(); 16126 if (view != null) { 16127 shadowSize.set(view.getWidth(), view.getHeight()); 16128 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 16129 } else { 16130 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 16131 } 16132 } 16133 16134 /** 16135 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 16136 * based on the dimensions it received from the 16137 * {@link #onProvideShadowMetrics(Point, Point)} callback. 16138 * 16139 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 16140 */ 16141 public void onDrawShadow(Canvas canvas) { 16142 final View view = mView.get(); 16143 if (view != null) { 16144 view.draw(canvas); 16145 } else { 16146 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 16147 } 16148 } 16149 } 16150 16151 /** 16152 * Starts a drag and drop operation. When your application calls this method, it passes a 16153 * {@link android.view.View.DragShadowBuilder} object to the system. The 16154 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 16155 * to get metrics for the drag shadow, and then calls the object's 16156 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 16157 * <p> 16158 * Once the system has the drag shadow, it begins the drag and drop operation by sending 16159 * drag events to all the View objects in your application that are currently visible. It does 16160 * this either by calling the View object's drag listener (an implementation of 16161 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 16162 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 16163 * Both are passed a {@link android.view.DragEvent} object that has a 16164 * {@link android.view.DragEvent#getAction()} value of 16165 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 16166 * </p> 16167 * <p> 16168 * Your application can invoke startDrag() on any attached View object. The View object does not 16169 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 16170 * be related to the View the user selected for dragging. 16171 * </p> 16172 * @param data A {@link android.content.ClipData} object pointing to the data to be 16173 * transferred by the drag and drop operation. 16174 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 16175 * drag shadow. 16176 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 16177 * drop operation. This Object is put into every DragEvent object sent by the system during the 16178 * current drag. 16179 * <p> 16180 * myLocalState is a lightweight mechanism for the sending information from the dragged View 16181 * to the target Views. For example, it can contain flags that differentiate between a 16182 * a copy operation and a move operation. 16183 * </p> 16184 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 16185 * so the parameter should be set to 0. 16186 * @return {@code true} if the method completes successfully, or 16187 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 16188 * do a drag, and so no drag operation is in progress. 16189 */ 16190 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 16191 Object myLocalState, int flags) { 16192 if (ViewDebug.DEBUG_DRAG) { 16193 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 16194 } 16195 boolean okay = false; 16196 16197 Point shadowSize = new Point(); 16198 Point shadowTouchPoint = new Point(); 16199 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 16200 16201 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 16202 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 16203 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 16204 } 16205 16206 if (ViewDebug.DEBUG_DRAG) { 16207 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 16208 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 16209 } 16210 Surface surface = new Surface(); 16211 try { 16212 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 16213 flags, shadowSize.x, shadowSize.y, surface); 16214 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 16215 + " surface=" + surface); 16216 if (token != null) { 16217 Canvas canvas = surface.lockCanvas(null); 16218 try { 16219 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 16220 shadowBuilder.onDrawShadow(canvas); 16221 } finally { 16222 surface.unlockCanvasAndPost(canvas); 16223 } 16224 16225 final ViewRootImpl root = getViewRootImpl(); 16226 16227 // Cache the local state object for delivery with DragEvents 16228 root.setLocalDragState(myLocalState); 16229 16230 // repurpose 'shadowSize' for the last touch point 16231 root.getLastTouchPoint(shadowSize); 16232 16233 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 16234 shadowSize.x, shadowSize.y, 16235 shadowTouchPoint.x, shadowTouchPoint.y, data); 16236 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 16237 16238 // Off and running! Release our local surface instance; the drag 16239 // shadow surface is now managed by the system process. 16240 surface.release(); 16241 } 16242 } catch (Exception e) { 16243 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 16244 surface.destroy(); 16245 } 16246 16247 return okay; 16248 } 16249 16250 /** 16251 * Handles drag events sent by the system following a call to 16252 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 16253 *<p> 16254 * When the system calls this method, it passes a 16255 * {@link android.view.DragEvent} object. A call to 16256 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 16257 * in DragEvent. The method uses these to determine what is happening in the drag and drop 16258 * operation. 16259 * @param event The {@link android.view.DragEvent} sent by the system. 16260 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 16261 * in DragEvent, indicating the type of drag event represented by this object. 16262 * @return {@code true} if the method was successful, otherwise {@code false}. 16263 * <p> 16264 * The method should return {@code true} in response to an action type of 16265 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 16266 * operation. 16267 * </p> 16268 * <p> 16269 * The method should also return {@code true} in response to an action type of 16270 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 16271 * {@code false} if it didn't. 16272 * </p> 16273 */ 16274 public boolean onDragEvent(DragEvent event) { 16275 return false; 16276 } 16277 16278 /** 16279 * Detects if this View is enabled and has a drag event listener. 16280 * If both are true, then it calls the drag event listener with the 16281 * {@link android.view.DragEvent} it received. If the drag event listener returns 16282 * {@code true}, then dispatchDragEvent() returns {@code true}. 16283 * <p> 16284 * For all other cases, the method calls the 16285 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 16286 * method and returns its result. 16287 * </p> 16288 * <p> 16289 * This ensures that a drag event is always consumed, even if the View does not have a drag 16290 * event listener. However, if the View has a listener and the listener returns true, then 16291 * onDragEvent() is not called. 16292 * </p> 16293 */ 16294 public boolean dispatchDragEvent(DragEvent event) { 16295 //noinspection SimplifiableIfStatement 16296 ListenerInfo li = mListenerInfo; 16297 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 16298 && li.mOnDragListener.onDrag(this, event)) { 16299 return true; 16300 } 16301 return onDragEvent(event); 16302 } 16303 16304 boolean canAcceptDrag() { 16305 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 16306 } 16307 16308 /** 16309 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 16310 * it is ever exposed at all. 16311 * @hide 16312 */ 16313 public void onCloseSystemDialogs(String reason) { 16314 } 16315 16316 /** 16317 * Given a Drawable whose bounds have been set to draw into this view, 16318 * update a Region being computed for 16319 * {@link #gatherTransparentRegion(android.graphics.Region)} so 16320 * that any non-transparent parts of the Drawable are removed from the 16321 * given transparent region. 16322 * 16323 * @param dr The Drawable whose transparency is to be applied to the region. 16324 * @param region A Region holding the current transparency information, 16325 * where any parts of the region that are set are considered to be 16326 * transparent. On return, this region will be modified to have the 16327 * transparency information reduced by the corresponding parts of the 16328 * Drawable that are not transparent. 16329 * {@hide} 16330 */ 16331 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 16332 if (DBG) { 16333 Log.i("View", "Getting transparent region for: " + this); 16334 } 16335 final Region r = dr.getTransparentRegion(); 16336 final Rect db = dr.getBounds(); 16337 final AttachInfo attachInfo = mAttachInfo; 16338 if (r != null && attachInfo != null) { 16339 final int w = getRight()-getLeft(); 16340 final int h = getBottom()-getTop(); 16341 if (db.left > 0) { 16342 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 16343 r.op(0, 0, db.left, h, Region.Op.UNION); 16344 } 16345 if (db.right < w) { 16346 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 16347 r.op(db.right, 0, w, h, Region.Op.UNION); 16348 } 16349 if (db.top > 0) { 16350 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 16351 r.op(0, 0, w, db.top, Region.Op.UNION); 16352 } 16353 if (db.bottom < h) { 16354 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 16355 r.op(0, db.bottom, w, h, Region.Op.UNION); 16356 } 16357 final int[] location = attachInfo.mTransparentLocation; 16358 getLocationInWindow(location); 16359 r.translate(location[0], location[1]); 16360 region.op(r, Region.Op.INTERSECT); 16361 } else { 16362 region.op(db, Region.Op.DIFFERENCE); 16363 } 16364 } 16365 16366 private void checkForLongClick(int delayOffset) { 16367 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 16368 mHasPerformedLongPress = false; 16369 16370 if (mPendingCheckForLongPress == null) { 16371 mPendingCheckForLongPress = new CheckForLongPress(); 16372 } 16373 mPendingCheckForLongPress.rememberWindowAttachCount(); 16374 postDelayed(mPendingCheckForLongPress, 16375 ViewConfiguration.getLongPressTimeout() - delayOffset); 16376 } 16377 } 16378 16379 /** 16380 * Inflate a view from an XML resource. This convenience method wraps the {@link 16381 * LayoutInflater} class, which provides a full range of options for view inflation. 16382 * 16383 * @param context The Context object for your activity or application. 16384 * @param resource The resource ID to inflate 16385 * @param root A view group that will be the parent. Used to properly inflate the 16386 * layout_* parameters. 16387 * @see LayoutInflater 16388 */ 16389 public static View inflate(Context context, int resource, ViewGroup root) { 16390 LayoutInflater factory = LayoutInflater.from(context); 16391 return factory.inflate(resource, root); 16392 } 16393 16394 /** 16395 * Scroll the view with standard behavior for scrolling beyond the normal 16396 * content boundaries. Views that call this method should override 16397 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 16398 * results of an over-scroll operation. 16399 * 16400 * Views can use this method to handle any touch or fling-based scrolling. 16401 * 16402 * @param deltaX Change in X in pixels 16403 * @param deltaY Change in Y in pixels 16404 * @param scrollX Current X scroll value in pixels before applying deltaX 16405 * @param scrollY Current Y scroll value in pixels before applying deltaY 16406 * @param scrollRangeX Maximum content scroll range along the X axis 16407 * @param scrollRangeY Maximum content scroll range along the Y axis 16408 * @param maxOverScrollX Number of pixels to overscroll by in either direction 16409 * along the X axis. 16410 * @param maxOverScrollY Number of pixels to overscroll by in either direction 16411 * along the Y axis. 16412 * @param isTouchEvent true if this scroll operation is the result of a touch event. 16413 * @return true if scrolling was clamped to an over-scroll boundary along either 16414 * axis, false otherwise. 16415 */ 16416 @SuppressWarnings({"UnusedParameters"}) 16417 protected boolean overScrollBy(int deltaX, int deltaY, 16418 int scrollX, int scrollY, 16419 int scrollRangeX, int scrollRangeY, 16420 int maxOverScrollX, int maxOverScrollY, 16421 boolean isTouchEvent) { 16422 final int overScrollMode = mOverScrollMode; 16423 final boolean canScrollHorizontal = 16424 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 16425 final boolean canScrollVertical = 16426 computeVerticalScrollRange() > computeVerticalScrollExtent(); 16427 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 16428 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 16429 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 16430 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 16431 16432 int newScrollX = scrollX + deltaX; 16433 if (!overScrollHorizontal) { 16434 maxOverScrollX = 0; 16435 } 16436 16437 int newScrollY = scrollY + deltaY; 16438 if (!overScrollVertical) { 16439 maxOverScrollY = 0; 16440 } 16441 16442 // Clamp values if at the limits and record 16443 final int left = -maxOverScrollX; 16444 final int right = maxOverScrollX + scrollRangeX; 16445 final int top = -maxOverScrollY; 16446 final int bottom = maxOverScrollY + scrollRangeY; 16447 16448 boolean clampedX = false; 16449 if (newScrollX > right) { 16450 newScrollX = right; 16451 clampedX = true; 16452 } else if (newScrollX < left) { 16453 newScrollX = left; 16454 clampedX = true; 16455 } 16456 16457 boolean clampedY = false; 16458 if (newScrollY > bottom) { 16459 newScrollY = bottom; 16460 clampedY = true; 16461 } else if (newScrollY < top) { 16462 newScrollY = top; 16463 clampedY = true; 16464 } 16465 16466 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 16467 16468 return clampedX || clampedY; 16469 } 16470 16471 /** 16472 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 16473 * respond to the results of an over-scroll operation. 16474 * 16475 * @param scrollX New X scroll value in pixels 16476 * @param scrollY New Y scroll value in pixels 16477 * @param clampedX True if scrollX was clamped to an over-scroll boundary 16478 * @param clampedY True if scrollY was clamped to an over-scroll boundary 16479 */ 16480 protected void onOverScrolled(int scrollX, int scrollY, 16481 boolean clampedX, boolean clampedY) { 16482 // Intentionally empty. 16483 } 16484 16485 /** 16486 * Returns the over-scroll mode for this view. The result will be 16487 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 16488 * (allow over-scrolling only if the view content is larger than the container), 16489 * or {@link #OVER_SCROLL_NEVER}. 16490 * 16491 * @return This view's over-scroll mode. 16492 */ 16493 public int getOverScrollMode() { 16494 return mOverScrollMode; 16495 } 16496 16497 /** 16498 * Set the over-scroll mode for this view. Valid over-scroll modes are 16499 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 16500 * (allow over-scrolling only if the view content is larger than the container), 16501 * or {@link #OVER_SCROLL_NEVER}. 16502 * 16503 * Setting the over-scroll mode of a view will have an effect only if the 16504 * view is capable of scrolling. 16505 * 16506 * @param overScrollMode The new over-scroll mode for this view. 16507 */ 16508 public void setOverScrollMode(int overScrollMode) { 16509 if (overScrollMode != OVER_SCROLL_ALWAYS && 16510 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 16511 overScrollMode != OVER_SCROLL_NEVER) { 16512 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 16513 } 16514 mOverScrollMode = overScrollMode; 16515 } 16516 16517 /** 16518 * Gets a scale factor that determines the distance the view should scroll 16519 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 16520 * @return The vertical scroll scale factor. 16521 * @hide 16522 */ 16523 protected float getVerticalScrollFactor() { 16524 if (mVerticalScrollFactor == 0) { 16525 TypedValue outValue = new TypedValue(); 16526 if (!mContext.getTheme().resolveAttribute( 16527 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 16528 throw new IllegalStateException( 16529 "Expected theme to define listPreferredItemHeight."); 16530 } 16531 mVerticalScrollFactor = outValue.getDimension( 16532 mContext.getResources().getDisplayMetrics()); 16533 } 16534 return mVerticalScrollFactor; 16535 } 16536 16537 /** 16538 * Gets a scale factor that determines the distance the view should scroll 16539 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 16540 * @return The horizontal scroll scale factor. 16541 * @hide 16542 */ 16543 protected float getHorizontalScrollFactor() { 16544 // TODO: Should use something else. 16545 return getVerticalScrollFactor(); 16546 } 16547 16548 /** 16549 * Return the value specifying the text direction or policy that was set with 16550 * {@link #setTextDirection(int)}. 16551 * 16552 * @return the defined text direction. It can be one of: 16553 * 16554 * {@link #TEXT_DIRECTION_INHERIT}, 16555 * {@link #TEXT_DIRECTION_FIRST_STRONG} 16556 * {@link #TEXT_DIRECTION_ANY_RTL}, 16557 * {@link #TEXT_DIRECTION_LTR}, 16558 * {@link #TEXT_DIRECTION_RTL}, 16559 * {@link #TEXT_DIRECTION_LOCALE} 16560 * 16561 * @hide 16562 */ 16563 @ViewDebug.ExportedProperty(category = "text", mapping = { 16564 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 16565 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 16566 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 16567 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 16568 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 16569 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 16570 }) 16571 public int getRawTextDirection() { 16572 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 16573 } 16574 16575 /** 16576 * Set the text direction. 16577 * 16578 * @param textDirection the direction to set. Should be one of: 16579 * 16580 * {@link #TEXT_DIRECTION_INHERIT}, 16581 * {@link #TEXT_DIRECTION_FIRST_STRONG} 16582 * {@link #TEXT_DIRECTION_ANY_RTL}, 16583 * {@link #TEXT_DIRECTION_LTR}, 16584 * {@link #TEXT_DIRECTION_RTL}, 16585 * {@link #TEXT_DIRECTION_LOCALE} 16586 */ 16587 public void setTextDirection(int textDirection) { 16588 if (getRawTextDirection() != textDirection) { 16589 // Reset the current text direction and the resolved one 16590 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 16591 resetResolvedTextDirection(); 16592 // Set the new text direction 16593 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 16594 // Notify change 16595 onRtlPropertiesChanged(); 16596 // Refresh 16597 requestLayout(); 16598 invalidate(true); 16599 } 16600 } 16601 16602 /** 16603 * Return the resolved text direction. 16604 * 16605 * This needs resolution if the value is TEXT_DIRECTION_INHERIT. The resolution matches what has 16606 * been set by {@link #setTextDirection(int)} if it is not TEXT_DIRECTION_INHERIT, otherwise the 16607 * resolution proceeds up the parent chain of the view. If there is no parent, then it will 16608 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 16609 * 16610 * @return the resolved text direction. Returns one of: 16611 * 16612 * {@link #TEXT_DIRECTION_FIRST_STRONG} 16613 * {@link #TEXT_DIRECTION_ANY_RTL}, 16614 * {@link #TEXT_DIRECTION_LTR}, 16615 * {@link #TEXT_DIRECTION_RTL}, 16616 * {@link #TEXT_DIRECTION_LOCALE} 16617 */ 16618 public int getTextDirection() { 16619 // The text direction will be resolved only if needed 16620 if ((mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) != PFLAG2_TEXT_DIRECTION_RESOLVED) { 16621 resolveTextDirection(); 16622 } 16623 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 16624 } 16625 16626 /** 16627 * Resolve the text direction. 16628 * 16629 * @hide 16630 */ 16631 public void resolveTextDirection() { 16632 // Reset any previous text direction resolution 16633 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 16634 16635 if (hasRtlSupport()) { 16636 // Set resolved text direction flag depending on text direction flag 16637 final int textDirection = getRawTextDirection(); 16638 switch(textDirection) { 16639 case TEXT_DIRECTION_INHERIT: 16640 if (canResolveTextDirection()) { 16641 ViewGroup viewGroup = ((ViewGroup) mParent); 16642 16643 // Set current resolved direction to the same value as the parent's one 16644 final int parentResolvedDirection = viewGroup.getTextDirection(); 16645 switch (parentResolvedDirection) { 16646 case TEXT_DIRECTION_FIRST_STRONG: 16647 case TEXT_DIRECTION_ANY_RTL: 16648 case TEXT_DIRECTION_LTR: 16649 case TEXT_DIRECTION_RTL: 16650 case TEXT_DIRECTION_LOCALE: 16651 mPrivateFlags2 |= 16652 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 16653 break; 16654 default: 16655 // Default resolved direction is "first strong" heuristic 16656 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 16657 } 16658 } else { 16659 // We cannot do the resolution if there is no parent, so use the default one 16660 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 16661 } 16662 break; 16663 case TEXT_DIRECTION_FIRST_STRONG: 16664 case TEXT_DIRECTION_ANY_RTL: 16665 case TEXT_DIRECTION_LTR: 16666 case TEXT_DIRECTION_RTL: 16667 case TEXT_DIRECTION_LOCALE: 16668 // Resolved direction is the same as text direction 16669 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 16670 break; 16671 default: 16672 // Default resolved direction is "first strong" heuristic 16673 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 16674 } 16675 } else { 16676 // Default resolved direction is "first strong" heuristic 16677 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 16678 } 16679 16680 // Set to resolved 16681 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 16682 } 16683 16684 /** 16685 * Check if text direction resolution can be done. 16686 * 16687 * @return true if text direction resolution can be done otherwise return false. 16688 */ 16689 private boolean canResolveTextDirection() { 16690 switch (getRawTextDirection()) { 16691 case TEXT_DIRECTION_INHERIT: 16692 return (mParent != null) && (mParent instanceof ViewGroup); 16693 default: 16694 return true; 16695 } 16696 } 16697 16698 /** 16699 * Reset resolved text direction. Text direction can be resolved with a call to 16700 * getTextDirection(). 16701 * 16702 * @hide 16703 */ 16704 public void resetResolvedTextDirection() { 16705 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 16706 } 16707 16708 /** 16709 * @hide 16710 */ 16711 public boolean isTextDirectionInherited() { 16712 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 16713 } 16714 16715 /** 16716 * Return the value specifying the text alignment or policy that was set with 16717 * {@link #setTextAlignment(int)}. 16718 * 16719 * @return the defined text alignment. It can be one of: 16720 * 16721 * {@link #TEXT_ALIGNMENT_INHERIT}, 16722 * {@link #TEXT_ALIGNMENT_GRAVITY}, 16723 * {@link #TEXT_ALIGNMENT_CENTER}, 16724 * {@link #TEXT_ALIGNMENT_TEXT_START}, 16725 * {@link #TEXT_ALIGNMENT_TEXT_END}, 16726 * {@link #TEXT_ALIGNMENT_VIEW_START}, 16727 * {@link #TEXT_ALIGNMENT_VIEW_END} 16728 * 16729 * @hide 16730 */ 16731 @ViewDebug.ExportedProperty(category = "text", mapping = { 16732 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 16733 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 16734 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 16735 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 16736 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 16737 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 16738 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 16739 }) 16740 public int getRawTextAlignment() { 16741 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 16742 } 16743 16744 /** 16745 * Set the text alignment. 16746 * 16747 * @param textAlignment The text alignment to set. Should be one of 16748 * 16749 * {@link #TEXT_ALIGNMENT_INHERIT}, 16750 * {@link #TEXT_ALIGNMENT_GRAVITY}, 16751 * {@link #TEXT_ALIGNMENT_CENTER}, 16752 * {@link #TEXT_ALIGNMENT_TEXT_START}, 16753 * {@link #TEXT_ALIGNMENT_TEXT_END}, 16754 * {@link #TEXT_ALIGNMENT_VIEW_START}, 16755 * {@link #TEXT_ALIGNMENT_VIEW_END} 16756 * 16757 * @attr ref android.R.styleable#View_textAlignment 16758 */ 16759 public void setTextAlignment(int textAlignment) { 16760 if (textAlignment != getRawTextAlignment()) { 16761 // Reset the current and resolved text alignment 16762 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 16763 resetResolvedTextAlignment(); 16764 // Set the new text alignment 16765 mPrivateFlags2 |= ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 16766 // Notify change 16767 onRtlPropertiesChanged(); 16768 // Refresh 16769 requestLayout(); 16770 invalidate(true); 16771 } 16772 } 16773 16774 /** 16775 * Return the resolved text alignment. 16776 * 16777 * The resolved text alignment. This needs resolution if the value is 16778 * TEXT_ALIGNMENT_INHERIT. The resolution matches {@link #setTextAlignment(int)} if it is 16779 * not TEXT_ALIGNMENT_INHERIT, otherwise resolution proceeds up the parent chain of the view. 16780 * 16781 * @return the resolved text alignment. Returns one of: 16782 * 16783 * {@link #TEXT_ALIGNMENT_GRAVITY}, 16784 * {@link #TEXT_ALIGNMENT_CENTER}, 16785 * {@link #TEXT_ALIGNMENT_TEXT_START}, 16786 * {@link #TEXT_ALIGNMENT_TEXT_END}, 16787 * {@link #TEXT_ALIGNMENT_VIEW_START}, 16788 * {@link #TEXT_ALIGNMENT_VIEW_END} 16789 */ 16790 @ViewDebug.ExportedProperty(category = "text", mapping = { 16791 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 16792 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 16793 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 16794 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 16795 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 16796 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 16797 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 16798 }) 16799 public int getTextAlignment() { 16800 // If text alignment is not resolved, then resolve it 16801 if ((mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) != PFLAG2_TEXT_ALIGNMENT_RESOLVED) { 16802 resolveTextAlignment(); 16803 } 16804 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 16805 } 16806 16807 /** 16808 * Resolve the text alignment. 16809 * 16810 * @hide 16811 */ 16812 public void resolveTextAlignment() { 16813 // Reset any previous text alignment resolution 16814 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 16815 16816 if (hasRtlSupport()) { 16817 // Set resolved text alignment flag depending on text alignment flag 16818 final int textAlignment = getRawTextAlignment(); 16819 switch (textAlignment) { 16820 case TEXT_ALIGNMENT_INHERIT: 16821 // Check if we can resolve the text alignment 16822 if (canResolveTextAlignment() && mParent instanceof View) { 16823 View view = (View) mParent; 16824 16825 final int parentResolvedTextAlignment = view.getTextAlignment(); 16826 switch (parentResolvedTextAlignment) { 16827 case TEXT_ALIGNMENT_GRAVITY: 16828 case TEXT_ALIGNMENT_TEXT_START: 16829 case TEXT_ALIGNMENT_TEXT_END: 16830 case TEXT_ALIGNMENT_CENTER: 16831 case TEXT_ALIGNMENT_VIEW_START: 16832 case TEXT_ALIGNMENT_VIEW_END: 16833 // Resolved text alignment is the same as the parent resolved 16834 // text alignment 16835 mPrivateFlags2 |= 16836 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 16837 break; 16838 default: 16839 // Use default resolved text alignment 16840 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 16841 } 16842 } 16843 else { 16844 // We cannot do the resolution if there is no parent so use the default 16845 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 16846 } 16847 break; 16848 case TEXT_ALIGNMENT_GRAVITY: 16849 case TEXT_ALIGNMENT_TEXT_START: 16850 case TEXT_ALIGNMENT_TEXT_END: 16851 case TEXT_ALIGNMENT_CENTER: 16852 case TEXT_ALIGNMENT_VIEW_START: 16853 case TEXT_ALIGNMENT_VIEW_END: 16854 // Resolved text alignment is the same as text alignment 16855 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 16856 break; 16857 default: 16858 // Use default resolved text alignment 16859 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 16860 } 16861 } else { 16862 // Use default resolved text alignment 16863 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 16864 } 16865 16866 // Set the resolved 16867 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 16868 } 16869 16870 /** 16871 * Check if text alignment resolution can be done. 16872 * 16873 * @return true if text alignment resolution can be done otherwise return false. 16874 */ 16875 private boolean canResolveTextAlignment() { 16876 switch (getRawTextAlignment()) { 16877 case TEXT_DIRECTION_INHERIT: 16878 return (mParent != null); 16879 default: 16880 return true; 16881 } 16882 } 16883 16884 /** 16885 * Reset resolved text alignment. 16886 * 16887 * @hide 16888 */ 16889 public void resetResolvedTextAlignment() { 16890 // Reset any previous text alignment resolution 16891 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 16892 } 16893 16894 /** 16895 * @hide 16896 */ 16897 public boolean isTextAlignmentInherited() { 16898 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 16899 } 16900 16901 /** 16902 * Generate a value suitable for use in {@link #setId(int)}. 16903 * This value will not collide with ID values generated at build time by aapt for R.id. 16904 * 16905 * @return a generated ID value 16906 */ 16907 public static int generateViewId() { 16908 for (;;) { 16909 final int result = sNextGeneratedId.get(); 16910 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 16911 int newValue = result + 1; 16912 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 16913 if (sNextGeneratedId.compareAndSet(result, newValue)) { 16914 return result; 16915 } 16916 } 16917 } 16918 16919 // 16920 // Properties 16921 // 16922 /** 16923 * A Property wrapper around the <code>alpha</code> functionality handled by the 16924 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 16925 */ 16926 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 16927 @Override 16928 public void setValue(View object, float value) { 16929 object.setAlpha(value); 16930 } 16931 16932 @Override 16933 public Float get(View object) { 16934 return object.getAlpha(); 16935 } 16936 }; 16937 16938 /** 16939 * A Property wrapper around the <code>translationX</code> functionality handled by the 16940 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 16941 */ 16942 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 16943 @Override 16944 public void setValue(View object, float value) { 16945 object.setTranslationX(value); 16946 } 16947 16948 @Override 16949 public Float get(View object) { 16950 return object.getTranslationX(); 16951 } 16952 }; 16953 16954 /** 16955 * A Property wrapper around the <code>translationY</code> functionality handled by the 16956 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 16957 */ 16958 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 16959 @Override 16960 public void setValue(View object, float value) { 16961 object.setTranslationY(value); 16962 } 16963 16964 @Override 16965 public Float get(View object) { 16966 return object.getTranslationY(); 16967 } 16968 }; 16969 16970 /** 16971 * A Property wrapper around the <code>x</code> functionality handled by the 16972 * {@link View#setX(float)} and {@link View#getX()} methods. 16973 */ 16974 public static final Property<View, Float> X = new FloatProperty<View>("x") { 16975 @Override 16976 public void setValue(View object, float value) { 16977 object.setX(value); 16978 } 16979 16980 @Override 16981 public Float get(View object) { 16982 return object.getX(); 16983 } 16984 }; 16985 16986 /** 16987 * A Property wrapper around the <code>y</code> functionality handled by the 16988 * {@link View#setY(float)} and {@link View#getY()} methods. 16989 */ 16990 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 16991 @Override 16992 public void setValue(View object, float value) { 16993 object.setY(value); 16994 } 16995 16996 @Override 16997 public Float get(View object) { 16998 return object.getY(); 16999 } 17000 }; 17001 17002 /** 17003 * A Property wrapper around the <code>rotation</code> functionality handled by the 17004 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 17005 */ 17006 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 17007 @Override 17008 public void setValue(View object, float value) { 17009 object.setRotation(value); 17010 } 17011 17012 @Override 17013 public Float get(View object) { 17014 return object.getRotation(); 17015 } 17016 }; 17017 17018 /** 17019 * A Property wrapper around the <code>rotationX</code> functionality handled by the 17020 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 17021 */ 17022 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 17023 @Override 17024 public void setValue(View object, float value) { 17025 object.setRotationX(value); 17026 } 17027 17028 @Override 17029 public Float get(View object) { 17030 return object.getRotationX(); 17031 } 17032 }; 17033 17034 /** 17035 * A Property wrapper around the <code>rotationY</code> functionality handled by the 17036 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 17037 */ 17038 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 17039 @Override 17040 public void setValue(View object, float value) { 17041 object.setRotationY(value); 17042 } 17043 17044 @Override 17045 public Float get(View object) { 17046 return object.getRotationY(); 17047 } 17048 }; 17049 17050 /** 17051 * A Property wrapper around the <code>scaleX</code> functionality handled by the 17052 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 17053 */ 17054 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 17055 @Override 17056 public void setValue(View object, float value) { 17057 object.setScaleX(value); 17058 } 17059 17060 @Override 17061 public Float get(View object) { 17062 return object.getScaleX(); 17063 } 17064 }; 17065 17066 /** 17067 * A Property wrapper around the <code>scaleY</code> functionality handled by the 17068 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 17069 */ 17070 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 17071 @Override 17072 public void setValue(View object, float value) { 17073 object.setScaleY(value); 17074 } 17075 17076 @Override 17077 public Float get(View object) { 17078 return object.getScaleY(); 17079 } 17080 }; 17081 17082 /** 17083 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 17084 * Each MeasureSpec represents a requirement for either the width or the height. 17085 * A MeasureSpec is comprised of a size and a mode. There are three possible 17086 * modes: 17087 * <dl> 17088 * <dt>UNSPECIFIED</dt> 17089 * <dd> 17090 * The parent has not imposed any constraint on the child. It can be whatever size 17091 * it wants. 17092 * </dd> 17093 * 17094 * <dt>EXACTLY</dt> 17095 * <dd> 17096 * The parent has determined an exact size for the child. The child is going to be 17097 * given those bounds regardless of how big it wants to be. 17098 * </dd> 17099 * 17100 * <dt>AT_MOST</dt> 17101 * <dd> 17102 * The child can be as large as it wants up to the specified size. 17103 * </dd> 17104 * </dl> 17105 * 17106 * MeasureSpecs are implemented as ints to reduce object allocation. This class 17107 * is provided to pack and unpack the <size, mode> tuple into the int. 17108 */ 17109 public static class MeasureSpec { 17110 private static final int MODE_SHIFT = 30; 17111 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 17112 17113 /** 17114 * Measure specification mode: The parent has not imposed any constraint 17115 * on the child. It can be whatever size it wants. 17116 */ 17117 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 17118 17119 /** 17120 * Measure specification mode: The parent has determined an exact size 17121 * for the child. The child is going to be given those bounds regardless 17122 * of how big it wants to be. 17123 */ 17124 public static final int EXACTLY = 1 << MODE_SHIFT; 17125 17126 /** 17127 * Measure specification mode: The child can be as large as it wants up 17128 * to the specified size. 17129 */ 17130 public static final int AT_MOST = 2 << MODE_SHIFT; 17131 17132 /** 17133 * Creates a measure specification based on the supplied size and mode. 17134 * 17135 * The mode must always be one of the following: 17136 * <ul> 17137 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 17138 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 17139 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 17140 * </ul> 17141 * 17142 * @param size the size of the measure specification 17143 * @param mode the mode of the measure specification 17144 * @return the measure specification based on size and mode 17145 */ 17146 public static int makeMeasureSpec(int size, int mode) { 17147 return size + mode; 17148 } 17149 17150 /** 17151 * Extracts the mode from the supplied measure specification. 17152 * 17153 * @param measureSpec the measure specification to extract the mode from 17154 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 17155 * {@link android.view.View.MeasureSpec#AT_MOST} or 17156 * {@link android.view.View.MeasureSpec#EXACTLY} 17157 */ 17158 public static int getMode(int measureSpec) { 17159 return (measureSpec & MODE_MASK); 17160 } 17161 17162 /** 17163 * Extracts the size from the supplied measure specification. 17164 * 17165 * @param measureSpec the measure specification to extract the size from 17166 * @return the size in pixels defined in the supplied measure specification 17167 */ 17168 public static int getSize(int measureSpec) { 17169 return (measureSpec & ~MODE_MASK); 17170 } 17171 17172 static int adjust(int measureSpec, int delta) { 17173 return makeMeasureSpec(getSize(measureSpec + delta), getMode(measureSpec)); 17174 } 17175 17176 /** 17177 * Returns a String representation of the specified measure 17178 * specification. 17179 * 17180 * @param measureSpec the measure specification to convert to a String 17181 * @return a String with the following format: "MeasureSpec: MODE SIZE" 17182 */ 17183 public static String toString(int measureSpec) { 17184 int mode = getMode(measureSpec); 17185 int size = getSize(measureSpec); 17186 17187 StringBuilder sb = new StringBuilder("MeasureSpec: "); 17188 17189 if (mode == UNSPECIFIED) 17190 sb.append("UNSPECIFIED "); 17191 else if (mode == EXACTLY) 17192 sb.append("EXACTLY "); 17193 else if (mode == AT_MOST) 17194 sb.append("AT_MOST "); 17195 else 17196 sb.append(mode).append(" "); 17197 17198 sb.append(size); 17199 return sb.toString(); 17200 } 17201 } 17202 17203 class CheckForLongPress implements Runnable { 17204 17205 private int mOriginalWindowAttachCount; 17206 17207 public void run() { 17208 if (isPressed() && (mParent != null) 17209 && mOriginalWindowAttachCount == mWindowAttachCount) { 17210 if (performLongClick()) { 17211 mHasPerformedLongPress = true; 17212 } 17213 } 17214 } 17215 17216 public void rememberWindowAttachCount() { 17217 mOriginalWindowAttachCount = mWindowAttachCount; 17218 } 17219 } 17220 17221 private final class CheckForTap implements Runnable { 17222 public void run() { 17223 mPrivateFlags &= ~PFLAG_PREPRESSED; 17224 setPressed(true); 17225 checkForLongClick(ViewConfiguration.getTapTimeout()); 17226 } 17227 } 17228 17229 private final class PerformClick implements Runnable { 17230 public void run() { 17231 performClick(); 17232 } 17233 } 17234 17235 /** @hide */ 17236 public void hackTurnOffWindowResizeAnim(boolean off) { 17237 mAttachInfo.mTurnOffWindowResizeAnim = off; 17238 } 17239 17240 /** 17241 * This method returns a ViewPropertyAnimator object, which can be used to animate 17242 * specific properties on this View. 17243 * 17244 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 17245 */ 17246 public ViewPropertyAnimator animate() { 17247 if (mAnimator == null) { 17248 mAnimator = new ViewPropertyAnimator(this); 17249 } 17250 return mAnimator; 17251 } 17252 17253 /** 17254 * Interface definition for a callback to be invoked when a hardware key event is 17255 * dispatched to this view. The callback will be invoked before the key event is 17256 * given to the view. This is only useful for hardware keyboards; a software input 17257 * method has no obligation to trigger this listener. 17258 */ 17259 public interface OnKeyListener { 17260 /** 17261 * Called when a hardware key is dispatched to a view. This allows listeners to 17262 * get a chance to respond before the target view. 17263 * <p>Key presses in software keyboards will generally NOT trigger this method, 17264 * although some may elect to do so in some situations. Do not assume a 17265 * software input method has to be key-based; even if it is, it may use key presses 17266 * in a different way than you expect, so there is no way to reliably catch soft 17267 * input key presses. 17268 * 17269 * @param v The view the key has been dispatched to. 17270 * @param keyCode The code for the physical key that was pressed 17271 * @param event The KeyEvent object containing full information about 17272 * the event. 17273 * @return True if the listener has consumed the event, false otherwise. 17274 */ 17275 boolean onKey(View v, int keyCode, KeyEvent event); 17276 } 17277 17278 /** 17279 * Interface definition for a callback to be invoked when a touch event is 17280 * dispatched to this view. The callback will be invoked before the touch 17281 * event is given to the view. 17282 */ 17283 public interface OnTouchListener { 17284 /** 17285 * Called when a touch event is dispatched to a view. This allows listeners to 17286 * get a chance to respond before the target view. 17287 * 17288 * @param v The view the touch event has been dispatched to. 17289 * @param event The MotionEvent object containing full information about 17290 * the event. 17291 * @return True if the listener has consumed the event, false otherwise. 17292 */ 17293 boolean onTouch(View v, MotionEvent event); 17294 } 17295 17296 /** 17297 * Interface definition for a callback to be invoked when a hover event is 17298 * dispatched to this view. The callback will be invoked before the hover 17299 * event is given to the view. 17300 */ 17301 public interface OnHoverListener { 17302 /** 17303 * Called when a hover event is dispatched to a view. This allows listeners to 17304 * get a chance to respond before the target view. 17305 * 17306 * @param v The view the hover event has been dispatched to. 17307 * @param event The MotionEvent object containing full information about 17308 * the event. 17309 * @return True if the listener has consumed the event, false otherwise. 17310 */ 17311 boolean onHover(View v, MotionEvent event); 17312 } 17313 17314 /** 17315 * Interface definition for a callback to be invoked when a generic motion event is 17316 * dispatched to this view. The callback will be invoked before the generic motion 17317 * event is given to the view. 17318 */ 17319 public interface OnGenericMotionListener { 17320 /** 17321 * Called when a generic motion event is dispatched to a view. This allows listeners to 17322 * get a chance to respond before the target view. 17323 * 17324 * @param v The view the generic motion event has been dispatched to. 17325 * @param event The MotionEvent object containing full information about 17326 * the event. 17327 * @return True if the listener has consumed the event, false otherwise. 17328 */ 17329 boolean onGenericMotion(View v, MotionEvent event); 17330 } 17331 17332 /** 17333 * Interface definition for a callback to be invoked when a view has been clicked and held. 17334 */ 17335 public interface OnLongClickListener { 17336 /** 17337 * Called when a view has been clicked and held. 17338 * 17339 * @param v The view that was clicked and held. 17340 * 17341 * @return true if the callback consumed the long click, false otherwise. 17342 */ 17343 boolean onLongClick(View v); 17344 } 17345 17346 /** 17347 * Interface definition for a callback to be invoked when a drag is being dispatched 17348 * to this view. The callback will be invoked before the hosting view's own 17349 * onDrag(event) method. If the listener wants to fall back to the hosting view's 17350 * onDrag(event) behavior, it should return 'false' from this callback. 17351 * 17352 * <div class="special reference"> 17353 * <h3>Developer Guides</h3> 17354 * <p>For a guide to implementing drag and drop features, read the 17355 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 17356 * </div> 17357 */ 17358 public interface OnDragListener { 17359 /** 17360 * Called when a drag event is dispatched to a view. This allows listeners 17361 * to get a chance to override base View behavior. 17362 * 17363 * @param v The View that received the drag event. 17364 * @param event The {@link android.view.DragEvent} object for the drag event. 17365 * @return {@code true} if the drag event was handled successfully, or {@code false} 17366 * if the drag event was not handled. Note that {@code false} will trigger the View 17367 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 17368 */ 17369 boolean onDrag(View v, DragEvent event); 17370 } 17371 17372 /** 17373 * Interface definition for a callback to be invoked when the focus state of 17374 * a view changed. 17375 */ 17376 public interface OnFocusChangeListener { 17377 /** 17378 * Called when the focus state of a view has changed. 17379 * 17380 * @param v The view whose state has changed. 17381 * @param hasFocus The new focus state of v. 17382 */ 17383 void onFocusChange(View v, boolean hasFocus); 17384 } 17385 17386 /** 17387 * Interface definition for a callback to be invoked when a view is clicked. 17388 */ 17389 public interface OnClickListener { 17390 /** 17391 * Called when a view has been clicked. 17392 * 17393 * @param v The view that was clicked. 17394 */ 17395 void onClick(View v); 17396 } 17397 17398 /** 17399 * Interface definition for a callback to be invoked when the context menu 17400 * for this view is being built. 17401 */ 17402 public interface OnCreateContextMenuListener { 17403 /** 17404 * Called when the context menu for this view is being built. It is not 17405 * safe to hold onto the menu after this method returns. 17406 * 17407 * @param menu The context menu that is being built 17408 * @param v The view for which the context menu is being built 17409 * @param menuInfo Extra information about the item for which the 17410 * context menu should be shown. This information will vary 17411 * depending on the class of v. 17412 */ 17413 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 17414 } 17415 17416 /** 17417 * Interface definition for a callback to be invoked when the status bar changes 17418 * visibility. This reports <strong>global</strong> changes to the system UI 17419 * state, not what the application is requesting. 17420 * 17421 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 17422 */ 17423 public interface OnSystemUiVisibilityChangeListener { 17424 /** 17425 * Called when the status bar changes visibility because of a call to 17426 * {@link View#setSystemUiVisibility(int)}. 17427 * 17428 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 17429 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 17430 * This tells you the <strong>global</strong> state of these UI visibility 17431 * flags, not what your app is currently applying. 17432 */ 17433 public void onSystemUiVisibilityChange(int visibility); 17434 } 17435 17436 /** 17437 * Interface definition for a callback to be invoked when this view is attached 17438 * or detached from its window. 17439 */ 17440 public interface OnAttachStateChangeListener { 17441 /** 17442 * Called when the view is attached to a window. 17443 * @param v The view that was attached 17444 */ 17445 public void onViewAttachedToWindow(View v); 17446 /** 17447 * Called when the view is detached from a window. 17448 * @param v The view that was detached 17449 */ 17450 public void onViewDetachedFromWindow(View v); 17451 } 17452 17453 private final class UnsetPressedState implements Runnable { 17454 public void run() { 17455 setPressed(false); 17456 } 17457 } 17458 17459 /** 17460 * Base class for derived classes that want to save and restore their own 17461 * state in {@link android.view.View#onSaveInstanceState()}. 17462 */ 17463 public static class BaseSavedState extends AbsSavedState { 17464 /** 17465 * Constructor used when reading from a parcel. Reads the state of the superclass. 17466 * 17467 * @param source 17468 */ 17469 public BaseSavedState(Parcel source) { 17470 super(source); 17471 } 17472 17473 /** 17474 * Constructor called by derived classes when creating their SavedState objects 17475 * 17476 * @param superState The state of the superclass of this view 17477 */ 17478 public BaseSavedState(Parcelable superState) { 17479 super(superState); 17480 } 17481 17482 public static final Parcelable.Creator<BaseSavedState> CREATOR = 17483 new Parcelable.Creator<BaseSavedState>() { 17484 public BaseSavedState createFromParcel(Parcel in) { 17485 return new BaseSavedState(in); 17486 } 17487 17488 public BaseSavedState[] newArray(int size) { 17489 return new BaseSavedState[size]; 17490 } 17491 }; 17492 } 17493 17494 /** 17495 * A set of information given to a view when it is attached to its parent 17496 * window. 17497 */ 17498 static class AttachInfo { 17499 interface Callbacks { 17500 void playSoundEffect(int effectId); 17501 boolean performHapticFeedback(int effectId, boolean always); 17502 } 17503 17504 /** 17505 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 17506 * to a Handler. This class contains the target (View) to invalidate and 17507 * the coordinates of the dirty rectangle. 17508 * 17509 * For performance purposes, this class also implements a pool of up to 17510 * POOL_LIMIT objects that get reused. This reduces memory allocations 17511 * whenever possible. 17512 */ 17513 static class InvalidateInfo implements Poolable<InvalidateInfo> { 17514 private static final int POOL_LIMIT = 10; 17515 private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool( 17516 Pools.finitePool(new PoolableManager<InvalidateInfo>() { 17517 public InvalidateInfo newInstance() { 17518 return new InvalidateInfo(); 17519 } 17520 17521 public void onAcquired(InvalidateInfo element) { 17522 } 17523 17524 public void onReleased(InvalidateInfo element) { 17525 element.target = null; 17526 } 17527 }, POOL_LIMIT) 17528 ); 17529 17530 private InvalidateInfo mNext; 17531 private boolean mIsPooled; 17532 17533 View target; 17534 17535 int left; 17536 int top; 17537 int right; 17538 int bottom; 17539 17540 public void setNextPoolable(InvalidateInfo element) { 17541 mNext = element; 17542 } 17543 17544 public InvalidateInfo getNextPoolable() { 17545 return mNext; 17546 } 17547 17548 static InvalidateInfo acquire() { 17549 return sPool.acquire(); 17550 } 17551 17552 void release() { 17553 sPool.release(this); 17554 } 17555 17556 public boolean isPooled() { 17557 return mIsPooled; 17558 } 17559 17560 public void setPooled(boolean isPooled) { 17561 mIsPooled = isPooled; 17562 } 17563 } 17564 17565 final IWindowSession mSession; 17566 17567 final IWindow mWindow; 17568 17569 final IBinder mWindowToken; 17570 17571 final Display mDisplay; 17572 17573 final Callbacks mRootCallbacks; 17574 17575 HardwareCanvas mHardwareCanvas; 17576 17577 /** 17578 * The top view of the hierarchy. 17579 */ 17580 View mRootView; 17581 17582 IBinder mPanelParentWindowToken; 17583 Surface mSurface; 17584 17585 boolean mHardwareAccelerated; 17586 boolean mHardwareAccelerationRequested; 17587 HardwareRenderer mHardwareRenderer; 17588 17589 boolean mScreenOn; 17590 17591 /** 17592 * Scale factor used by the compatibility mode 17593 */ 17594 float mApplicationScale; 17595 17596 /** 17597 * Indicates whether the application is in compatibility mode 17598 */ 17599 boolean mScalingRequired; 17600 17601 /** 17602 * If set, ViewAncestor doesn't use its lame animation for when the window resizes. 17603 */ 17604 boolean mTurnOffWindowResizeAnim; 17605 17606 /** 17607 * Left position of this view's window 17608 */ 17609 int mWindowLeft; 17610 17611 /** 17612 * Top position of this view's window 17613 */ 17614 int mWindowTop; 17615 17616 /** 17617 * Indicates whether views need to use 32-bit drawing caches 17618 */ 17619 boolean mUse32BitDrawingCache; 17620 17621 /** 17622 * For windows that are full-screen but using insets to layout inside 17623 * of the screen decorations, these are the current insets for the 17624 * content of the window. 17625 */ 17626 final Rect mContentInsets = new Rect(); 17627 17628 /** 17629 * For windows that are full-screen but using insets to layout inside 17630 * of the screen decorations, these are the current insets for the 17631 * actual visible parts of the window. 17632 */ 17633 final Rect mVisibleInsets = new Rect(); 17634 17635 /** 17636 * The internal insets given by this window. This value is 17637 * supplied by the client (through 17638 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 17639 * be given to the window manager when changed to be used in laying 17640 * out windows behind it. 17641 */ 17642 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 17643 = new ViewTreeObserver.InternalInsetsInfo(); 17644 17645 /** 17646 * All views in the window's hierarchy that serve as scroll containers, 17647 * used to determine if the window can be resized or must be panned 17648 * to adjust for a soft input area. 17649 */ 17650 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 17651 17652 final KeyEvent.DispatcherState mKeyDispatchState 17653 = new KeyEvent.DispatcherState(); 17654 17655 /** 17656 * Indicates whether the view's window currently has the focus. 17657 */ 17658 boolean mHasWindowFocus; 17659 17660 /** 17661 * The current visibility of the window. 17662 */ 17663 int mWindowVisibility; 17664 17665 /** 17666 * Indicates the time at which drawing started to occur. 17667 */ 17668 long mDrawingTime; 17669 17670 /** 17671 * Indicates whether or not ignoring the DIRTY_MASK flags. 17672 */ 17673 boolean mIgnoreDirtyState; 17674 17675 /** 17676 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 17677 * to avoid clearing that flag prematurely. 17678 */ 17679 boolean mSetIgnoreDirtyState = false; 17680 17681 /** 17682 * Indicates whether the view's window is currently in touch mode. 17683 */ 17684 boolean mInTouchMode; 17685 17686 /** 17687 * Indicates that ViewAncestor should trigger a global layout change 17688 * the next time it performs a traversal 17689 */ 17690 boolean mRecomputeGlobalAttributes; 17691 17692 /** 17693 * Always report new attributes at next traversal. 17694 */ 17695 boolean mForceReportNewAttributes; 17696 17697 /** 17698 * Set during a traveral if any views want to keep the screen on. 17699 */ 17700 boolean mKeepScreenOn; 17701 17702 /** 17703 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 17704 */ 17705 int mSystemUiVisibility; 17706 17707 /** 17708 * Hack to force certain system UI visibility flags to be cleared. 17709 */ 17710 int mDisabledSystemUiVisibility; 17711 17712 /** 17713 * Last global system UI visibility reported by the window manager. 17714 */ 17715 int mGlobalSystemUiVisibility; 17716 17717 /** 17718 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 17719 * attached. 17720 */ 17721 boolean mHasSystemUiListeners; 17722 17723 /** 17724 * Set if the visibility of any views has changed. 17725 */ 17726 boolean mViewVisibilityChanged; 17727 17728 /** 17729 * Set to true if a view has been scrolled. 17730 */ 17731 boolean mViewScrollChanged; 17732 17733 /** 17734 * Global to the view hierarchy used as a temporary for dealing with 17735 * x/y points in the transparent region computations. 17736 */ 17737 final int[] mTransparentLocation = new int[2]; 17738 17739 /** 17740 * Global to the view hierarchy used as a temporary for dealing with 17741 * x/y points in the ViewGroup.invalidateChild implementation. 17742 */ 17743 final int[] mInvalidateChildLocation = new int[2]; 17744 17745 17746 /** 17747 * Global to the view hierarchy used as a temporary for dealing with 17748 * x/y location when view is transformed. 17749 */ 17750 final float[] mTmpTransformLocation = new float[2]; 17751 17752 /** 17753 * The view tree observer used to dispatch global events like 17754 * layout, pre-draw, touch mode change, etc. 17755 */ 17756 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 17757 17758 /** 17759 * A Canvas used by the view hierarchy to perform bitmap caching. 17760 */ 17761 Canvas mCanvas; 17762 17763 /** 17764 * The view root impl. 17765 */ 17766 final ViewRootImpl mViewRootImpl; 17767 17768 /** 17769 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 17770 * handler can be used to pump events in the UI events queue. 17771 */ 17772 final Handler mHandler; 17773 17774 /** 17775 * Temporary for use in computing invalidate rectangles while 17776 * calling up the hierarchy. 17777 */ 17778 final Rect mTmpInvalRect = new Rect(); 17779 17780 /** 17781 * Temporary for use in computing hit areas with transformed views 17782 */ 17783 final RectF mTmpTransformRect = new RectF(); 17784 17785 /** 17786 * Temporary for use in transforming invalidation rect 17787 */ 17788 final Matrix mTmpMatrix = new Matrix(); 17789 17790 /** 17791 * Temporary for use in transforming invalidation rect 17792 */ 17793 final Transformation mTmpTransformation = new Transformation(); 17794 17795 /** 17796 * Temporary list for use in collecting focusable descendents of a view. 17797 */ 17798 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 17799 17800 /** 17801 * The id of the window for accessibility purposes. 17802 */ 17803 int mAccessibilityWindowId = View.NO_ID; 17804 17805 /** 17806 * Whether to ingore not exposed for accessibility Views when 17807 * reporting the view tree to accessibility services. 17808 */ 17809 boolean mIncludeNotImportantViews; 17810 17811 /** 17812 * The drawable for highlighting accessibility focus. 17813 */ 17814 Drawable mAccessibilityFocusDrawable; 17815 17816 /** 17817 * Show where the margins, bounds and layout bounds are for each view. 17818 */ 17819 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 17820 17821 /** 17822 * Point used to compute visible regions. 17823 */ 17824 final Point mPoint = new Point(); 17825 17826 /** 17827 * Creates a new set of attachment information with the specified 17828 * events handler and thread. 17829 * 17830 * @param handler the events handler the view must use 17831 */ 17832 AttachInfo(IWindowSession session, IWindow window, Display display, 17833 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) { 17834 mSession = session; 17835 mWindow = window; 17836 mWindowToken = window.asBinder(); 17837 mDisplay = display; 17838 mViewRootImpl = viewRootImpl; 17839 mHandler = handler; 17840 mRootCallbacks = effectPlayer; 17841 } 17842 } 17843 17844 /** 17845 * <p>ScrollabilityCache holds various fields used by a View when scrolling 17846 * is supported. This avoids keeping too many unused fields in most 17847 * instances of View.</p> 17848 */ 17849 private static class ScrollabilityCache implements Runnable { 17850 17851 /** 17852 * Scrollbars are not visible 17853 */ 17854 public static final int OFF = 0; 17855 17856 /** 17857 * Scrollbars are visible 17858 */ 17859 public static final int ON = 1; 17860 17861 /** 17862 * Scrollbars are fading away 17863 */ 17864 public static final int FADING = 2; 17865 17866 public boolean fadeScrollBars; 17867 17868 public int fadingEdgeLength; 17869 public int scrollBarDefaultDelayBeforeFade; 17870 public int scrollBarFadeDuration; 17871 17872 public int scrollBarSize; 17873 public ScrollBarDrawable scrollBar; 17874 public float[] interpolatorValues; 17875 public View host; 17876 17877 public final Paint paint; 17878 public final Matrix matrix; 17879 public Shader shader; 17880 17881 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 17882 17883 private static final float[] OPAQUE = { 255 }; 17884 private static final float[] TRANSPARENT = { 0.0f }; 17885 17886 /** 17887 * When fading should start. This time moves into the future every time 17888 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 17889 */ 17890 public long fadeStartTime; 17891 17892 17893 /** 17894 * The current state of the scrollbars: ON, OFF, or FADING 17895 */ 17896 public int state = OFF; 17897 17898 private int mLastColor; 17899 17900 public ScrollabilityCache(ViewConfiguration configuration, View host) { 17901 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 17902 scrollBarSize = configuration.getScaledScrollBarSize(); 17903 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 17904 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 17905 17906 paint = new Paint(); 17907 matrix = new Matrix(); 17908 // use use a height of 1, and then wack the matrix each time we 17909 // actually use it. 17910 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 17911 paint.setShader(shader); 17912 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 17913 17914 this.host = host; 17915 } 17916 17917 public void setFadeColor(int color) { 17918 if (color != mLastColor) { 17919 mLastColor = color; 17920 17921 if (color != 0) { 17922 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 17923 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 17924 paint.setShader(shader); 17925 // Restore the default transfer mode (src_over) 17926 paint.setXfermode(null); 17927 } else { 17928 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 17929 paint.setShader(shader); 17930 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 17931 } 17932 } 17933 } 17934 17935 public void run() { 17936 long now = AnimationUtils.currentAnimationTimeMillis(); 17937 if (now >= fadeStartTime) { 17938 17939 // the animation fades the scrollbars out by changing 17940 // the opacity (alpha) from fully opaque to fully 17941 // transparent 17942 int nextFrame = (int) now; 17943 int framesCount = 0; 17944 17945 Interpolator interpolator = scrollBarInterpolator; 17946 17947 // Start opaque 17948 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 17949 17950 // End transparent 17951 nextFrame += scrollBarFadeDuration; 17952 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 17953 17954 state = FADING; 17955 17956 // Kick off the fade animation 17957 host.invalidate(true); 17958 } 17959 } 17960 } 17961 17962 /** 17963 * Resuable callback for sending 17964 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 17965 */ 17966 private class SendViewScrolledAccessibilityEvent implements Runnable { 17967 public volatile boolean mIsPending; 17968 17969 public void run() { 17970 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 17971 mIsPending = false; 17972 } 17973 } 17974 17975 /** 17976 * <p> 17977 * This class represents a delegate that can be registered in a {@link View} 17978 * to enhance accessibility support via composition rather via inheritance. 17979 * It is specifically targeted to widget developers that extend basic View 17980 * classes i.e. classes in package android.view, that would like their 17981 * applications to be backwards compatible. 17982 * </p> 17983 * <div class="special reference"> 17984 * <h3>Developer Guides</h3> 17985 * <p>For more information about making applications accessible, read the 17986 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 17987 * developer guide.</p> 17988 * </div> 17989 * <p> 17990 * A scenario in which a developer would like to use an accessibility delegate 17991 * is overriding a method introduced in a later API version then the minimal API 17992 * version supported by the application. For example, the method 17993 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 17994 * in API version 4 when the accessibility APIs were first introduced. If a 17995 * developer would like his application to run on API version 4 devices (assuming 17996 * all other APIs used by the application are version 4 or lower) and take advantage 17997 * of this method, instead of overriding the method which would break the application's 17998 * backwards compatibility, he can override the corresponding method in this 17999 * delegate and register the delegate in the target View if the API version of 18000 * the system is high enough i.e. the API version is same or higher to the API 18001 * version that introduced 18002 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 18003 * </p> 18004 * <p> 18005 * Here is an example implementation: 18006 * </p> 18007 * <code><pre><p> 18008 * if (Build.VERSION.SDK_INT >= 14) { 18009 * // If the API version is equal of higher than the version in 18010 * // which onInitializeAccessibilityNodeInfo was introduced we 18011 * // register a delegate with a customized implementation. 18012 * View view = findViewById(R.id.view_id); 18013 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 18014 * public void onInitializeAccessibilityNodeInfo(View host, 18015 * AccessibilityNodeInfo info) { 18016 * // Let the default implementation populate the info. 18017 * super.onInitializeAccessibilityNodeInfo(host, info); 18018 * // Set some other information. 18019 * info.setEnabled(host.isEnabled()); 18020 * } 18021 * }); 18022 * } 18023 * </code></pre></p> 18024 * <p> 18025 * This delegate contains methods that correspond to the accessibility methods 18026 * in View. If a delegate has been specified the implementation in View hands 18027 * off handling to the corresponding method in this delegate. The default 18028 * implementation the delegate methods behaves exactly as the corresponding 18029 * method in View for the case of no accessibility delegate been set. Hence, 18030 * to customize the behavior of a View method, clients can override only the 18031 * corresponding delegate method without altering the behavior of the rest 18032 * accessibility related methods of the host view. 18033 * </p> 18034 */ 18035 public static class AccessibilityDelegate { 18036 18037 /** 18038 * Sends an accessibility event of the given type. If accessibility is not 18039 * enabled this method has no effect. 18040 * <p> 18041 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 18042 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 18043 * been set. 18044 * </p> 18045 * 18046 * @param host The View hosting the delegate. 18047 * @param eventType The type of the event to send. 18048 * 18049 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 18050 */ 18051 public void sendAccessibilityEvent(View host, int eventType) { 18052 host.sendAccessibilityEventInternal(eventType); 18053 } 18054 18055 /** 18056 * Performs the specified accessibility action on the view. For 18057 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 18058 * <p> 18059 * The default implementation behaves as 18060 * {@link View#performAccessibilityAction(int, Bundle) 18061 * View#performAccessibilityAction(int, Bundle)} for the case of 18062 * no accessibility delegate been set. 18063 * </p> 18064 * 18065 * @param action The action to perform. 18066 * @return Whether the action was performed. 18067 * 18068 * @see View#performAccessibilityAction(int, Bundle) 18069 * View#performAccessibilityAction(int, Bundle) 18070 */ 18071 public boolean performAccessibilityAction(View host, int action, Bundle args) { 18072 return host.performAccessibilityActionInternal(action, args); 18073 } 18074 18075 /** 18076 * Sends an accessibility event. This method behaves exactly as 18077 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 18078 * empty {@link AccessibilityEvent} and does not perform a check whether 18079 * accessibility is enabled. 18080 * <p> 18081 * The default implementation behaves as 18082 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 18083 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 18084 * the case of no accessibility delegate been set. 18085 * </p> 18086 * 18087 * @param host The View hosting the delegate. 18088 * @param event The event to send. 18089 * 18090 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 18091 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 18092 */ 18093 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 18094 host.sendAccessibilityEventUncheckedInternal(event); 18095 } 18096 18097 /** 18098 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 18099 * to its children for adding their text content to the event. 18100 * <p> 18101 * The default implementation behaves as 18102 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 18103 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 18104 * the case of no accessibility delegate been set. 18105 * </p> 18106 * 18107 * @param host The View hosting the delegate. 18108 * @param event The event. 18109 * @return True if the event population was completed. 18110 * 18111 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 18112 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 18113 */ 18114 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 18115 return host.dispatchPopulateAccessibilityEventInternal(event); 18116 } 18117 18118 /** 18119 * Gives a chance to the host View to populate the accessibility event with its 18120 * text content. 18121 * <p> 18122 * The default implementation behaves as 18123 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 18124 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 18125 * the case of no accessibility delegate been set. 18126 * </p> 18127 * 18128 * @param host The View hosting the delegate. 18129 * @param event The accessibility event which to populate. 18130 * 18131 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 18132 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 18133 */ 18134 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 18135 host.onPopulateAccessibilityEventInternal(event); 18136 } 18137 18138 /** 18139 * Initializes an {@link AccessibilityEvent} with information about the 18140 * the host View which is the event source. 18141 * <p> 18142 * The default implementation behaves as 18143 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 18144 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 18145 * the case of no accessibility delegate been set. 18146 * </p> 18147 * 18148 * @param host The View hosting the delegate. 18149 * @param event The event to initialize. 18150 * 18151 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 18152 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 18153 */ 18154 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 18155 host.onInitializeAccessibilityEventInternal(event); 18156 } 18157 18158 /** 18159 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 18160 * <p> 18161 * The default implementation behaves as 18162 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 18163 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 18164 * the case of no accessibility delegate been set. 18165 * </p> 18166 * 18167 * @param host The View hosting the delegate. 18168 * @param info The instance to initialize. 18169 * 18170 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 18171 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 18172 */ 18173 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 18174 host.onInitializeAccessibilityNodeInfoInternal(info); 18175 } 18176 18177 /** 18178 * Called when a child of the host View has requested sending an 18179 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 18180 * to augment the event. 18181 * <p> 18182 * The default implementation behaves as 18183 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 18184 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 18185 * the case of no accessibility delegate been set. 18186 * </p> 18187 * 18188 * @param host The View hosting the delegate. 18189 * @param child The child which requests sending the event. 18190 * @param event The event to be sent. 18191 * @return True if the event should be sent 18192 * 18193 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 18194 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 18195 */ 18196 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 18197 AccessibilityEvent event) { 18198 return host.onRequestSendAccessibilityEventInternal(child, event); 18199 } 18200 18201 /** 18202 * Gets the provider for managing a virtual view hierarchy rooted at this View 18203 * and reported to {@link android.accessibilityservice.AccessibilityService}s 18204 * that explore the window content. 18205 * <p> 18206 * The default implementation behaves as 18207 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 18208 * the case of no accessibility delegate been set. 18209 * </p> 18210 * 18211 * @return The provider. 18212 * 18213 * @see AccessibilityNodeProvider 18214 */ 18215 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 18216 return null; 18217 } 18218 } 18219 18220 private class MatchIdPredicate implements Predicate<View> { 18221 public int mId; 18222 18223 @Override 18224 public boolean apply(View view) { 18225 return (view.mID == mId); 18226 } 18227 } 18228 18229 private class MatchLabelForPredicate implements Predicate<View> { 18230 private int mLabeledId; 18231 18232 @Override 18233 public boolean apply(View view) { 18234 return (view.mLabelForId == mLabeledId); 18235 } 18236 } 18237 18238 /** 18239 * Dump all private flags in readable format, useful for documentation and 18240 * sanity checking. 18241 */ 18242 private static void dumpFlags() { 18243 final HashMap<String, String> found = Maps.newHashMap(); 18244 try { 18245 for (Field field : View.class.getDeclaredFields()) { 18246 final int modifiers = field.getModifiers(); 18247 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 18248 if (field.getType().equals(int.class)) { 18249 final int value = field.getInt(null); 18250 dumpFlag(found, field.getName(), value); 18251 } else if (field.getType().equals(int[].class)) { 18252 final int[] values = (int[]) field.get(null); 18253 for (int i = 0; i < values.length; i++) { 18254 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 18255 } 18256 } 18257 } 18258 } 18259 } catch (IllegalAccessException e) { 18260 throw new RuntimeException(e); 18261 } 18262 18263 final ArrayList<String> keys = Lists.newArrayList(); 18264 keys.addAll(found.keySet()); 18265 Collections.sort(keys); 18266 for (String key : keys) { 18267 Log.d(VIEW_LOG_TAG, found.get(key)); 18268 } 18269 } 18270 18271 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 18272 // Sort flags by prefix, then by bits, always keeping unique keys 18273 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 18274 final int prefix = name.indexOf('_'); 18275 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 18276 final String output = bits + " " + name; 18277 found.put(key, output); 18278 } 18279} 18280