View.java revision d09d5f9e4cb9cd03c47eab0f1e9256dc1e2a7527
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.annotation.IntDef; 20import android.annotation.NonNull; 21import android.annotation.Nullable; 22import android.content.ClipData; 23import android.content.Context; 24import android.content.res.Configuration; 25import android.content.res.Resources; 26import android.content.res.TypedArray; 27import android.graphics.Bitmap; 28import android.graphics.Camera; 29import android.graphics.Canvas; 30import android.graphics.Insets; 31import android.graphics.Interpolator; 32import android.graphics.LinearGradient; 33import android.graphics.Matrix; 34import android.graphics.Paint; 35import android.graphics.PixelFormat; 36import android.graphics.Point; 37import android.graphics.PorterDuff; 38import android.graphics.PorterDuffXfermode; 39import android.graphics.Rect; 40import android.graphics.RectF; 41import android.graphics.Region; 42import android.graphics.Shader; 43import android.graphics.drawable.ColorDrawable; 44import android.graphics.drawable.Drawable; 45import android.hardware.display.DisplayManagerGlobal; 46import android.os.Bundle; 47import android.os.Handler; 48import android.os.IBinder; 49import android.os.Parcel; 50import android.os.Parcelable; 51import android.os.RemoteException; 52import android.os.SystemClock; 53import android.os.SystemProperties; 54import android.text.TextUtils; 55import android.util.AttributeSet; 56import android.util.FloatProperty; 57import android.util.LayoutDirection; 58import android.util.Log; 59import android.util.LongSparseLongArray; 60import android.util.Pools.SynchronizedPool; 61import android.util.Property; 62import android.util.SparseArray; 63import android.util.SuperNotCalledException; 64import android.util.TypedValue; 65import android.view.ContextMenu.ContextMenuInfo; 66import android.view.AccessibilityIterators.TextSegmentIterator; 67import android.view.AccessibilityIterators.CharacterTextSegmentIterator; 68import android.view.AccessibilityIterators.WordTextSegmentIterator; 69import android.view.AccessibilityIterators.ParagraphTextSegmentIterator; 70import android.view.accessibility.AccessibilityEvent; 71import android.view.accessibility.AccessibilityEventSource; 72import android.view.accessibility.AccessibilityManager; 73import android.view.accessibility.AccessibilityNodeInfo; 74import android.view.accessibility.AccessibilityNodeProvider; 75import android.view.animation.Animation; 76import android.view.animation.AnimationUtils; 77import android.view.animation.Transformation; 78import android.view.inputmethod.EditorInfo; 79import android.view.inputmethod.InputConnection; 80import android.view.inputmethod.InputMethodManager; 81import android.widget.ScrollBarDrawable; 82 83import static android.os.Build.VERSION_CODES.*; 84import static java.lang.Math.max; 85 86import com.android.internal.R; 87import com.android.internal.util.Predicate; 88import com.android.internal.view.menu.MenuBuilder; 89import com.google.android.collect.Lists; 90import com.google.android.collect.Maps; 91 92import java.lang.annotation.Retention; 93import java.lang.annotation.RetentionPolicy; 94import java.lang.ref.WeakReference; 95import java.lang.reflect.Field; 96import java.lang.reflect.InvocationTargetException; 97import java.lang.reflect.Method; 98import java.lang.reflect.Modifier; 99import java.util.ArrayList; 100import java.util.Arrays; 101import java.util.Collections; 102import java.util.HashMap; 103import java.util.Locale; 104import java.util.concurrent.CopyOnWriteArrayList; 105import java.util.concurrent.atomic.AtomicInteger; 106 107/** 108 * <p> 109 * This class represents the basic building block for user interface components. A View 110 * occupies a rectangular area on the screen and is responsible for drawing and 111 * event handling. View is the base class for <em>widgets</em>, which are 112 * used to create interactive UI components (buttons, text fields, etc.). The 113 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 114 * are invisible containers that hold other Views (or other ViewGroups) and define 115 * their layout properties. 116 * </p> 117 * 118 * <div class="special reference"> 119 * <h3>Developer Guides</h3> 120 * <p>For information about using this class to develop your application's user interface, 121 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide. 122 * </div> 123 * 124 * <a name="Using"></a> 125 * <h3>Using Views</h3> 126 * <p> 127 * All of the views in a window are arranged in a single tree. You can add views 128 * either from code or by specifying a tree of views in one or more XML layout 129 * files. There are many specialized subclasses of views that act as controls or 130 * are capable of displaying text, images, or other content. 131 * </p> 132 * <p> 133 * Once you have created a tree of views, there are typically a few types of 134 * common operations you may wish to perform: 135 * <ul> 136 * <li><strong>Set properties:</strong> for example setting the text of a 137 * {@link android.widget.TextView}. The available properties and the methods 138 * that set them will vary among the different subclasses of views. Note that 139 * properties that are known at build time can be set in the XML layout 140 * files.</li> 141 * <li><strong>Set focus:</strong> The framework will handled moving focus in 142 * response to user input. To force focus to a specific view, call 143 * {@link #requestFocus}.</li> 144 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 145 * that will be notified when something interesting happens to the view. For 146 * example, all views will let you set a listener to be notified when the view 147 * gains or loses focus. You can register such a listener using 148 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 149 * Other view subclasses offer more specialized listeners. For example, a Button 150 * exposes a listener to notify clients when the button is clicked.</li> 151 * <li><strong>Set visibility:</strong> You can hide or show views using 152 * {@link #setVisibility(int)}.</li> 153 * </ul> 154 * </p> 155 * <p><em> 156 * Note: The Android framework is responsible for measuring, laying out and 157 * drawing views. You should not call methods that perform these actions on 158 * views yourself unless you are actually implementing a 159 * {@link android.view.ViewGroup}. 160 * </em></p> 161 * 162 * <a name="Lifecycle"></a> 163 * <h3>Implementing a Custom View</h3> 164 * 165 * <p> 166 * To implement a custom view, you will usually begin by providing overrides for 167 * some of the standard methods that the framework calls on all views. You do 168 * not need to override all of these methods. In fact, you can start by just 169 * overriding {@link #onDraw(android.graphics.Canvas)}. 170 * <table border="2" width="85%" align="center" cellpadding="5"> 171 * <thead> 172 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 173 * </thead> 174 * 175 * <tbody> 176 * <tr> 177 * <td rowspan="2">Creation</td> 178 * <td>Constructors</td> 179 * <td>There is a form of the constructor that are called when the view 180 * is created from code and a form that is called when the view is 181 * inflated from a layout file. The second form should parse and apply 182 * any attributes defined in the layout file. 183 * </td> 184 * </tr> 185 * <tr> 186 * <td><code>{@link #onFinishInflate()}</code></td> 187 * <td>Called after a view and all of its children has been inflated 188 * from XML.</td> 189 * </tr> 190 * 191 * <tr> 192 * <td rowspan="3">Layout</td> 193 * <td><code>{@link #onMeasure(int, int)}</code></td> 194 * <td>Called to determine the size requirements for this view and all 195 * of its children. 196 * </td> 197 * </tr> 198 * <tr> 199 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 200 * <td>Called when this view should assign a size and position to all 201 * of its children. 202 * </td> 203 * </tr> 204 * <tr> 205 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 206 * <td>Called when the size of this view has changed. 207 * </td> 208 * </tr> 209 * 210 * <tr> 211 * <td>Drawing</td> 212 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 213 * <td>Called when the view should render its content. 214 * </td> 215 * </tr> 216 * 217 * <tr> 218 * <td rowspan="4">Event processing</td> 219 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 220 * <td>Called when a new hardware key event occurs. 221 * </td> 222 * </tr> 223 * <tr> 224 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 225 * <td>Called when a hardware key up event occurs. 226 * </td> 227 * </tr> 228 * <tr> 229 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 230 * <td>Called when a trackball motion event occurs. 231 * </td> 232 * </tr> 233 * <tr> 234 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 235 * <td>Called when a touch screen motion event occurs. 236 * </td> 237 * </tr> 238 * 239 * <tr> 240 * <td rowspan="2">Focus</td> 241 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 242 * <td>Called when the view gains or loses focus. 243 * </td> 244 * </tr> 245 * 246 * <tr> 247 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 248 * <td>Called when the window containing the view gains or loses focus. 249 * </td> 250 * </tr> 251 * 252 * <tr> 253 * <td rowspan="3">Attaching</td> 254 * <td><code>{@link #onAttachedToWindow()}</code></td> 255 * <td>Called when the view is attached to a window. 256 * </td> 257 * </tr> 258 * 259 * <tr> 260 * <td><code>{@link #onDetachedFromWindow}</code></td> 261 * <td>Called when the view is detached from its window. 262 * </td> 263 * </tr> 264 * 265 * <tr> 266 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 267 * <td>Called when the visibility of the window containing the view 268 * has changed. 269 * </td> 270 * </tr> 271 * </tbody> 272 * 273 * </table> 274 * </p> 275 * 276 * <a name="IDs"></a> 277 * <h3>IDs</h3> 278 * Views may have an integer id associated with them. These ids are typically 279 * assigned in the layout XML files, and are used to find specific views within 280 * the view tree. A common pattern is to: 281 * <ul> 282 * <li>Define a Button in the layout file and assign it a unique ID. 283 * <pre> 284 * <Button 285 * android:id="@+id/my_button" 286 * android:layout_width="wrap_content" 287 * android:layout_height="wrap_content" 288 * android:text="@string/my_button_text"/> 289 * </pre></li> 290 * <li>From the onCreate method of an Activity, find the Button 291 * <pre class="prettyprint"> 292 * Button myButton = (Button) findViewById(R.id.my_button); 293 * </pre></li> 294 * </ul> 295 * <p> 296 * View IDs need not be unique throughout the tree, but it is good practice to 297 * ensure that they are at least unique within the part of the tree you are 298 * searching. 299 * </p> 300 * 301 * <a name="Position"></a> 302 * <h3>Position</h3> 303 * <p> 304 * The geometry of a view is that of a rectangle. A view has a location, 305 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 306 * two dimensions, expressed as a width and a height. The unit for location 307 * and dimensions is the pixel. 308 * </p> 309 * 310 * <p> 311 * It is possible to retrieve the location of a view by invoking the methods 312 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 313 * coordinate of the rectangle representing the view. The latter returns the 314 * top, or Y, coordinate of the rectangle representing the view. These methods 315 * both return the location of the view relative to its parent. For instance, 316 * when getLeft() returns 20, that means the view is located 20 pixels to the 317 * right of the left edge of its direct parent. 318 * </p> 319 * 320 * <p> 321 * In addition, several convenience methods are offered to avoid unnecessary 322 * computations, namely {@link #getRight()} and {@link #getBottom()}. 323 * These methods return the coordinates of the right and bottom edges of the 324 * rectangle representing the view. For instance, calling {@link #getRight()} 325 * is similar to the following computation: <code>getLeft() + getWidth()</code> 326 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 327 * </p> 328 * 329 * <a name="SizePaddingMargins"></a> 330 * <h3>Size, padding and margins</h3> 331 * <p> 332 * The size of a view is expressed with a width and a height. A view actually 333 * possess two pairs of width and height values. 334 * </p> 335 * 336 * <p> 337 * The first pair is known as <em>measured width</em> and 338 * <em>measured height</em>. These dimensions define how big a view wants to be 339 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 340 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 341 * and {@link #getMeasuredHeight()}. 342 * </p> 343 * 344 * <p> 345 * The second pair is simply known as <em>width</em> and <em>height</em>, or 346 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 347 * dimensions define the actual size of the view on screen, at drawing time and 348 * after layout. These values may, but do not have to, be different from the 349 * measured width and height. The width and height can be obtained by calling 350 * {@link #getWidth()} and {@link #getHeight()}. 351 * </p> 352 * 353 * <p> 354 * To measure its dimensions, a view takes into account its padding. The padding 355 * is expressed in pixels for the left, top, right and bottom parts of the view. 356 * Padding can be used to offset the content of the view by a specific amount of 357 * pixels. For instance, a left padding of 2 will push the view's content by 358 * 2 pixels to the right of the left edge. Padding can be set using the 359 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)} 360 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 361 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()}, 362 * {@link #getPaddingEnd()}. 363 * </p> 364 * 365 * <p> 366 * Even though a view can define a padding, it does not provide any support for 367 * margins. However, view groups provide such a support. Refer to 368 * {@link android.view.ViewGroup} and 369 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 370 * </p> 371 * 372 * <a name="Layout"></a> 373 * <h3>Layout</h3> 374 * <p> 375 * Layout is a two pass process: a measure pass and a layout pass. The measuring 376 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 377 * of the view tree. Each view pushes dimension specifications down the tree 378 * during the recursion. At the end of the measure pass, every view has stored 379 * its measurements. The second pass happens in 380 * {@link #layout(int,int,int,int)} and is also top-down. During 381 * this pass each parent is responsible for positioning all of its children 382 * using the sizes computed in the measure pass. 383 * </p> 384 * 385 * <p> 386 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 387 * {@link #getMeasuredHeight()} values must be set, along with those for all of 388 * that view's descendants. A view's measured width and measured height values 389 * must respect the constraints imposed by the view's parents. This guarantees 390 * that at the end of the measure pass, all parents accept all of their 391 * children's measurements. A parent view may call measure() more than once on 392 * its children. For example, the parent may measure each child once with 393 * unspecified dimensions to find out how big they want to be, then call 394 * measure() on them again with actual numbers if the sum of all the children's 395 * unconstrained sizes is too big or too small. 396 * </p> 397 * 398 * <p> 399 * The measure pass uses two classes to communicate dimensions. The 400 * {@link MeasureSpec} class is used by views to tell their parents how they 401 * want to be measured and positioned. The base LayoutParams class just 402 * describes how big the view wants to be for both width and height. For each 403 * dimension, it can specify one of: 404 * <ul> 405 * <li> an exact number 406 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 407 * (minus padding) 408 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 409 * enclose its content (plus padding). 410 * </ul> 411 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 412 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 413 * an X and Y value. 414 * </p> 415 * 416 * <p> 417 * MeasureSpecs are used to push requirements down the tree from parent to 418 * child. A MeasureSpec can be in one of three modes: 419 * <ul> 420 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 421 * of a child view. For example, a LinearLayout may call measure() on its child 422 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 423 * tall the child view wants to be given a width of 240 pixels. 424 * <li>EXACTLY: This is used by the parent to impose an exact size on the 425 * child. The child must use this size, and guarantee that all of its 426 * descendants will fit within this size. 427 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 428 * child. The child must gurantee that it and all of its descendants will fit 429 * within this size. 430 * </ul> 431 * </p> 432 * 433 * <p> 434 * To intiate a layout, call {@link #requestLayout}. This method is typically 435 * called by a view on itself when it believes that is can no longer fit within 436 * its current bounds. 437 * </p> 438 * 439 * <a name="Drawing"></a> 440 * <h3>Drawing</h3> 441 * <p> 442 * Drawing is handled by walking the tree and rendering each view that 443 * intersects the invalid region. Because the tree is traversed in-order, 444 * this means that parents will draw before (i.e., behind) their children, with 445 * siblings drawn in the order they appear in the tree. 446 * If you set a background drawable for a View, then the View will draw it for you 447 * before calling back to its <code>onDraw()</code> method. 448 * </p> 449 * 450 * <p> 451 * Note that the framework will not draw views that are not in the invalid region. 452 * </p> 453 * 454 * <p> 455 * To force a view to draw, call {@link #invalidate()}. 456 * </p> 457 * 458 * <a name="EventHandlingThreading"></a> 459 * <h3>Event Handling and Threading</h3> 460 * <p> 461 * The basic cycle of a view is as follows: 462 * <ol> 463 * <li>An event comes in and is dispatched to the appropriate view. The view 464 * handles the event and notifies any listeners.</li> 465 * <li>If in the course of processing the event, the view's bounds may need 466 * to be changed, the view will call {@link #requestLayout()}.</li> 467 * <li>Similarly, if in the course of processing the event the view's appearance 468 * may need to be changed, the view will call {@link #invalidate()}.</li> 469 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 470 * the framework will take care of measuring, laying out, and drawing the tree 471 * as appropriate.</li> 472 * </ol> 473 * </p> 474 * 475 * <p><em>Note: The entire view tree is single threaded. You must always be on 476 * the UI thread when calling any method on any view.</em> 477 * If you are doing work on other threads and want to update the state of a view 478 * from that thread, you should use a {@link Handler}. 479 * </p> 480 * 481 * <a name="FocusHandling"></a> 482 * <h3>Focus Handling</h3> 483 * <p> 484 * The framework will handle routine focus movement in response to user input. 485 * This includes changing the focus as views are removed or hidden, or as new 486 * views become available. Views indicate their willingness to take focus 487 * through the {@link #isFocusable} method. To change whether a view can take 488 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 489 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 490 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 491 * </p> 492 * <p> 493 * Focus movement is based on an algorithm which finds the nearest neighbor in a 494 * given direction. In rare cases, the default algorithm may not match the 495 * intended behavior of the developer. In these situations, you can provide 496 * explicit overrides by using these XML attributes in the layout file: 497 * <pre> 498 * nextFocusDown 499 * nextFocusLeft 500 * nextFocusRight 501 * nextFocusUp 502 * </pre> 503 * </p> 504 * 505 * 506 * <p> 507 * To get a particular view to take focus, call {@link #requestFocus()}. 508 * </p> 509 * 510 * <a name="TouchMode"></a> 511 * <h3>Touch Mode</h3> 512 * <p> 513 * When a user is navigating a user interface via directional keys such as a D-pad, it is 514 * necessary to give focus to actionable items such as buttons so the user can see 515 * what will take input. If the device has touch capabilities, however, and the user 516 * begins interacting with the interface by touching it, it is no longer necessary to 517 * always highlight, or give focus to, a particular view. This motivates a mode 518 * for interaction named 'touch mode'. 519 * </p> 520 * <p> 521 * For a touch capable device, once the user touches the screen, the device 522 * will enter touch mode. From this point onward, only views for which 523 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 524 * Other views that are touchable, like buttons, will not take focus when touched; they will 525 * only fire the on click listeners. 526 * </p> 527 * <p> 528 * Any time a user hits a directional key, such as a D-pad direction, the view device will 529 * exit touch mode, and find a view to take focus, so that the user may resume interacting 530 * with the user interface without touching the screen again. 531 * </p> 532 * <p> 533 * The touch mode state is maintained across {@link android.app.Activity}s. Call 534 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 535 * </p> 536 * 537 * <a name="Scrolling"></a> 538 * <h3>Scrolling</h3> 539 * <p> 540 * The framework provides basic support for views that wish to internally 541 * scroll their content. This includes keeping track of the X and Y scroll 542 * offset as well as mechanisms for drawing scrollbars. See 543 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 544 * {@link #awakenScrollBars()} for more details. 545 * </p> 546 * 547 * <a name="Tags"></a> 548 * <h3>Tags</h3> 549 * <p> 550 * Unlike IDs, tags are not used to identify views. Tags are essentially an 551 * extra piece of information that can be associated with a view. They are most 552 * often used as a convenience to store data related to views in the views 553 * themselves rather than by putting them in a separate structure. 554 * </p> 555 * 556 * <a name="Properties"></a> 557 * <h3>Properties</h3> 558 * <p> 559 * The View class exposes an {@link #ALPHA} property, as well as several transform-related 560 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are 561 * available both in the {@link Property} form as well as in similarly-named setter/getter 562 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can 563 * be used to set persistent state associated with these rendering-related properties on the view. 564 * The properties and methods can also be used in conjunction with 565 * {@link android.animation.Animator Animator}-based animations, described more in the 566 * <a href="#Animation">Animation</a> section. 567 * </p> 568 * 569 * <a name="Animation"></a> 570 * <h3>Animation</h3> 571 * <p> 572 * Starting with Android 3.0, the preferred way of animating views is to use the 573 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based 574 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and 575 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0 576 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only 577 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class 578 * makes animating these View properties particularly easy and efficient. 579 * </p> 580 * <p> 581 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered. 582 * You can attach an {@link Animation} object to a view using 583 * {@link #setAnimation(Animation)} or 584 * {@link #startAnimation(Animation)}. The animation can alter the scale, 585 * rotation, translation and alpha of a view over time. If the animation is 586 * attached to a view that has children, the animation will affect the entire 587 * subtree rooted by that node. When an animation is started, the framework will 588 * take care of redrawing the appropriate views until the animation completes. 589 * </p> 590 * 591 * <a name="Security"></a> 592 * <h3>Security</h3> 593 * <p> 594 * Sometimes it is essential that an application be able to verify that an action 595 * is being performed with the full knowledge and consent of the user, such as 596 * granting a permission request, making a purchase or clicking on an advertisement. 597 * Unfortunately, a malicious application could try to spoof the user into 598 * performing these actions, unaware, by concealing the intended purpose of the view. 599 * As a remedy, the framework offers a touch filtering mechanism that can be used to 600 * improve the security of views that provide access to sensitive functionality. 601 * </p><p> 602 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 603 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 604 * will discard touches that are received whenever the view's window is obscured by 605 * another visible window. As a result, the view will not receive touches whenever a 606 * toast, dialog or other window appears above the view's window. 607 * </p><p> 608 * For more fine-grained control over security, consider overriding the 609 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 610 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 611 * </p> 612 * 613 * @attr ref android.R.styleable#View_alpha 614 * @attr ref android.R.styleable#View_background 615 * @attr ref android.R.styleable#View_clickable 616 * @attr ref android.R.styleable#View_contentDescription 617 * @attr ref android.R.styleable#View_drawingCacheQuality 618 * @attr ref android.R.styleable#View_duplicateParentState 619 * @attr ref android.R.styleable#View_id 620 * @attr ref android.R.styleable#View_requiresFadingEdge 621 * @attr ref android.R.styleable#View_fadeScrollbars 622 * @attr ref android.R.styleable#View_fadingEdgeLength 623 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 624 * @attr ref android.R.styleable#View_fitsSystemWindows 625 * @attr ref android.R.styleable#View_isScrollContainer 626 * @attr ref android.R.styleable#View_focusable 627 * @attr ref android.R.styleable#View_focusableInTouchMode 628 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 629 * @attr ref android.R.styleable#View_keepScreenOn 630 * @attr ref android.R.styleable#View_layerType 631 * @attr ref android.R.styleable#View_layoutDirection 632 * @attr ref android.R.styleable#View_longClickable 633 * @attr ref android.R.styleable#View_minHeight 634 * @attr ref android.R.styleable#View_minWidth 635 * @attr ref android.R.styleable#View_nextFocusDown 636 * @attr ref android.R.styleable#View_nextFocusLeft 637 * @attr ref android.R.styleable#View_nextFocusRight 638 * @attr ref android.R.styleable#View_nextFocusUp 639 * @attr ref android.R.styleable#View_onClick 640 * @attr ref android.R.styleable#View_padding 641 * @attr ref android.R.styleable#View_paddingBottom 642 * @attr ref android.R.styleable#View_paddingLeft 643 * @attr ref android.R.styleable#View_paddingRight 644 * @attr ref android.R.styleable#View_paddingTop 645 * @attr ref android.R.styleable#View_paddingStart 646 * @attr ref android.R.styleable#View_paddingEnd 647 * @attr ref android.R.styleable#View_saveEnabled 648 * @attr ref android.R.styleable#View_rotation 649 * @attr ref android.R.styleable#View_rotationX 650 * @attr ref android.R.styleable#View_rotationY 651 * @attr ref android.R.styleable#View_scaleX 652 * @attr ref android.R.styleable#View_scaleY 653 * @attr ref android.R.styleable#View_scrollX 654 * @attr ref android.R.styleable#View_scrollY 655 * @attr ref android.R.styleable#View_scrollbarSize 656 * @attr ref android.R.styleable#View_scrollbarStyle 657 * @attr ref android.R.styleable#View_scrollbars 658 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 659 * @attr ref android.R.styleable#View_scrollbarFadeDuration 660 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 661 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 662 * @attr ref android.R.styleable#View_scrollbarThumbVertical 663 * @attr ref android.R.styleable#View_scrollbarTrackVertical 664 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 665 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 666 * @attr ref android.R.styleable#View_soundEffectsEnabled 667 * @attr ref android.R.styleable#View_tag 668 * @attr ref android.R.styleable#View_textAlignment 669 * @attr ref android.R.styleable#View_textDirection 670 * @attr ref android.R.styleable#View_transformPivotX 671 * @attr ref android.R.styleable#View_transformPivotY 672 * @attr ref android.R.styleable#View_translationX 673 * @attr ref android.R.styleable#View_translationY 674 * @attr ref android.R.styleable#View_visibility 675 * 676 * @see android.view.ViewGroup 677 */ 678public class View implements Drawable.Callback, KeyEvent.Callback, 679 AccessibilityEventSource { 680 private static final boolean DBG = false; 681 682 /** 683 * The logging tag used by this class with android.util.Log. 684 */ 685 protected static final String VIEW_LOG_TAG = "View"; 686 687 /** 688 * When set to true, apps will draw debugging information about their layouts. 689 * 690 * @hide 691 */ 692 public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout"; 693 694 /** 695 * Used to mark a View that has no ID. 696 */ 697 public static final int NO_ID = -1; 698 699 private static boolean sUseBrokenMakeMeasureSpec = false; 700 701 /** 702 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 703 * calling setFlags. 704 */ 705 private static final int NOT_FOCUSABLE = 0x00000000; 706 707 /** 708 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 709 * setFlags. 710 */ 711 private static final int FOCUSABLE = 0x00000001; 712 713 /** 714 * Mask for use with setFlags indicating bits used for focus. 715 */ 716 private static final int FOCUSABLE_MASK = 0x00000001; 717 718 /** 719 * This view will adjust its padding to fit sytem windows (e.g. status bar) 720 */ 721 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 722 723 /** @hide */ 724 @IntDef({VISIBLE, INVISIBLE, GONE}) 725 @Retention(RetentionPolicy.SOURCE) 726 public @interface Visibility {} 727 728 /** 729 * This view is visible. 730 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 731 * android:visibility}. 732 */ 733 public static final int VISIBLE = 0x00000000; 734 735 /** 736 * This view is invisible, but it still takes up space for layout purposes. 737 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 738 * android:visibility}. 739 */ 740 public static final int INVISIBLE = 0x00000004; 741 742 /** 743 * This view is invisible, and it doesn't take any space for layout 744 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 745 * android:visibility}. 746 */ 747 public static final int GONE = 0x00000008; 748 749 /** 750 * Mask for use with setFlags indicating bits used for visibility. 751 * {@hide} 752 */ 753 static final int VISIBILITY_MASK = 0x0000000C; 754 755 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 756 757 /** 758 * This view is enabled. Interpretation varies by subclass. 759 * Use with ENABLED_MASK when calling setFlags. 760 * {@hide} 761 */ 762 static final int ENABLED = 0x00000000; 763 764 /** 765 * This view is disabled. Interpretation varies by subclass. 766 * Use with ENABLED_MASK when calling setFlags. 767 * {@hide} 768 */ 769 static final int DISABLED = 0x00000020; 770 771 /** 772 * Mask for use with setFlags indicating bits used for indicating whether 773 * this view is enabled 774 * {@hide} 775 */ 776 static final int ENABLED_MASK = 0x00000020; 777 778 /** 779 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 780 * called and further optimizations will be performed. It is okay to have 781 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 782 * {@hide} 783 */ 784 static final int WILL_NOT_DRAW = 0x00000080; 785 786 /** 787 * Mask for use with setFlags indicating bits used for indicating whether 788 * this view is will draw 789 * {@hide} 790 */ 791 static final int DRAW_MASK = 0x00000080; 792 793 /** 794 * <p>This view doesn't show scrollbars.</p> 795 * {@hide} 796 */ 797 static final int SCROLLBARS_NONE = 0x00000000; 798 799 /** 800 * <p>This view shows horizontal scrollbars.</p> 801 * {@hide} 802 */ 803 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 804 805 /** 806 * <p>This view shows vertical scrollbars.</p> 807 * {@hide} 808 */ 809 static final int SCROLLBARS_VERTICAL = 0x00000200; 810 811 /** 812 * <p>Mask for use with setFlags indicating bits used for indicating which 813 * scrollbars are enabled.</p> 814 * {@hide} 815 */ 816 static final int SCROLLBARS_MASK = 0x00000300; 817 818 /** 819 * Indicates that the view should filter touches when its window is obscured. 820 * Refer to the class comments for more information about this security feature. 821 * {@hide} 822 */ 823 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 824 825 /** 826 * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate 827 * that they are optional and should be skipped if the window has 828 * requested system UI flags that ignore those insets for layout. 829 */ 830 static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800; 831 832 /** 833 * <p>This view doesn't show fading edges.</p> 834 * {@hide} 835 */ 836 static final int FADING_EDGE_NONE = 0x00000000; 837 838 /** 839 * <p>This view shows horizontal fading edges.</p> 840 * {@hide} 841 */ 842 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 843 844 /** 845 * <p>This view shows vertical fading edges.</p> 846 * {@hide} 847 */ 848 static final int FADING_EDGE_VERTICAL = 0x00002000; 849 850 /** 851 * <p>Mask for use with setFlags indicating bits used for indicating which 852 * fading edges are enabled.</p> 853 * {@hide} 854 */ 855 static final int FADING_EDGE_MASK = 0x00003000; 856 857 /** 858 * <p>Indicates this view can be clicked. When clickable, a View reacts 859 * to clicks by notifying the OnClickListener.<p> 860 * {@hide} 861 */ 862 static final int CLICKABLE = 0x00004000; 863 864 /** 865 * <p>Indicates this view is caching its drawing into a bitmap.</p> 866 * {@hide} 867 */ 868 static final int DRAWING_CACHE_ENABLED = 0x00008000; 869 870 /** 871 * <p>Indicates that no icicle should be saved for this view.<p> 872 * {@hide} 873 */ 874 static final int SAVE_DISABLED = 0x000010000; 875 876 /** 877 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 878 * property.</p> 879 * {@hide} 880 */ 881 static final int SAVE_DISABLED_MASK = 0x000010000; 882 883 /** 884 * <p>Indicates that no drawing cache should ever be created for this view.<p> 885 * {@hide} 886 */ 887 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 888 889 /** 890 * <p>Indicates this view can take / keep focus when int touch mode.</p> 891 * {@hide} 892 */ 893 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 894 895 /** @hide */ 896 @Retention(RetentionPolicy.SOURCE) 897 @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO}) 898 public @interface DrawingCacheQuality {} 899 900 /** 901 * <p>Enables low quality mode for the drawing cache.</p> 902 */ 903 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 904 905 /** 906 * <p>Enables high quality mode for the drawing cache.</p> 907 */ 908 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 909 910 /** 911 * <p>Enables automatic quality mode for the drawing cache.</p> 912 */ 913 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 914 915 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 916 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 917 }; 918 919 /** 920 * <p>Mask for use with setFlags indicating bits used for the cache 921 * quality property.</p> 922 * {@hide} 923 */ 924 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 925 926 /** 927 * <p> 928 * Indicates this view can be long clicked. When long clickable, a View 929 * reacts to long clicks by notifying the OnLongClickListener or showing a 930 * context menu. 931 * </p> 932 * {@hide} 933 */ 934 static final int LONG_CLICKABLE = 0x00200000; 935 936 /** 937 * <p>Indicates that this view gets its drawable states from its direct parent 938 * and ignores its original internal states.</p> 939 * 940 * @hide 941 */ 942 static final int DUPLICATE_PARENT_STATE = 0x00400000; 943 944 /** @hide */ 945 @IntDef({ 946 SCROLLBARS_INSIDE_OVERLAY, 947 SCROLLBARS_INSIDE_INSET, 948 SCROLLBARS_OUTSIDE_OVERLAY, 949 SCROLLBARS_OUTSIDE_INSET 950 }) 951 @Retention(RetentionPolicy.SOURCE) 952 public @interface ScrollBarStyle {} 953 954 /** 955 * The scrollbar style to display the scrollbars inside the content area, 956 * without increasing the padding. The scrollbars will be overlaid with 957 * translucency on the view's content. 958 */ 959 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 960 961 /** 962 * The scrollbar style to display the scrollbars inside the padded area, 963 * increasing the padding of the view. The scrollbars will not overlap the 964 * content area of the view. 965 */ 966 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 967 968 /** 969 * The scrollbar style to display the scrollbars at the edge of the view, 970 * without increasing the padding. The scrollbars will be overlaid with 971 * translucency. 972 */ 973 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 974 975 /** 976 * The scrollbar style to display the scrollbars at the edge of the view, 977 * increasing the padding of the view. The scrollbars will only overlap the 978 * background, if any. 979 */ 980 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 981 982 /** 983 * Mask to check if the scrollbar style is overlay or inset. 984 * {@hide} 985 */ 986 static final int SCROLLBARS_INSET_MASK = 0x01000000; 987 988 /** 989 * Mask to check if the scrollbar style is inside or outside. 990 * {@hide} 991 */ 992 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 993 994 /** 995 * Mask for scrollbar style. 996 * {@hide} 997 */ 998 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 999 1000 /** 1001 * View flag indicating that the screen should remain on while the 1002 * window containing this view is visible to the user. This effectively 1003 * takes care of automatically setting the WindowManager's 1004 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 1005 */ 1006 public static final int KEEP_SCREEN_ON = 0x04000000; 1007 1008 /** 1009 * View flag indicating whether this view should have sound effects enabled 1010 * for events such as clicking and touching. 1011 */ 1012 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 1013 1014 /** 1015 * View flag indicating whether this view should have haptic feedback 1016 * enabled for events such as long presses. 1017 */ 1018 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 1019 1020 /** 1021 * <p>Indicates that the view hierarchy should stop saving state when 1022 * it reaches this view. If state saving is initiated immediately at 1023 * the view, it will be allowed. 1024 * {@hide} 1025 */ 1026 static final int PARENT_SAVE_DISABLED = 0x20000000; 1027 1028 /** 1029 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 1030 * {@hide} 1031 */ 1032 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 1033 1034 /** @hide */ 1035 @IntDef(flag = true, 1036 value = { 1037 FOCUSABLES_ALL, 1038 FOCUSABLES_TOUCH_MODE 1039 }) 1040 @Retention(RetentionPolicy.SOURCE) 1041 public @interface FocusableMode {} 1042 1043 /** 1044 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1045 * should add all focusable Views regardless if they are focusable in touch mode. 1046 */ 1047 public static final int FOCUSABLES_ALL = 0x00000000; 1048 1049 /** 1050 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1051 * should add only Views focusable in touch mode. 1052 */ 1053 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1054 1055 /** @hide */ 1056 @IntDef({ 1057 FOCUS_BACKWARD, 1058 FOCUS_FORWARD, 1059 FOCUS_LEFT, 1060 FOCUS_UP, 1061 FOCUS_RIGHT, 1062 FOCUS_DOWN 1063 }) 1064 @Retention(RetentionPolicy.SOURCE) 1065 public @interface FocusDirection {} 1066 1067 /** @hide */ 1068 @IntDef({ 1069 FOCUS_LEFT, 1070 FOCUS_UP, 1071 FOCUS_RIGHT, 1072 FOCUS_DOWN 1073 }) 1074 @Retention(RetentionPolicy.SOURCE) 1075 public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward 1076 1077 /** 1078 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1079 * item. 1080 */ 1081 public static final int FOCUS_BACKWARD = 0x00000001; 1082 1083 /** 1084 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1085 * item. 1086 */ 1087 public static final int FOCUS_FORWARD = 0x00000002; 1088 1089 /** 1090 * Use with {@link #focusSearch(int)}. Move focus to the left. 1091 */ 1092 public static final int FOCUS_LEFT = 0x00000011; 1093 1094 /** 1095 * Use with {@link #focusSearch(int)}. Move focus up. 1096 */ 1097 public static final int FOCUS_UP = 0x00000021; 1098 1099 /** 1100 * Use with {@link #focusSearch(int)}. Move focus to the right. 1101 */ 1102 public static final int FOCUS_RIGHT = 0x00000042; 1103 1104 /** 1105 * Use with {@link #focusSearch(int)}. Move focus down. 1106 */ 1107 public static final int FOCUS_DOWN = 0x00000082; 1108 1109 /** 1110 * Bits of {@link #getMeasuredWidthAndState()} and 1111 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1112 */ 1113 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1114 1115 /** 1116 * Bits of {@link #getMeasuredWidthAndState()} and 1117 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1118 */ 1119 public static final int MEASURED_STATE_MASK = 0xff000000; 1120 1121 /** 1122 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1123 * for functions that combine both width and height into a single int, 1124 * such as {@link #getMeasuredState()} and the childState argument of 1125 * {@link #resolveSizeAndState(int, int, int)}. 1126 */ 1127 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1128 1129 /** 1130 * Bit of {@link #getMeasuredWidthAndState()} and 1131 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1132 * is smaller that the space the view would like to have. 1133 */ 1134 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1135 1136 /** 1137 * Base View state sets 1138 */ 1139 // Singles 1140 /** 1141 * Indicates the view has no states set. States are used with 1142 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1143 * view depending on its state. 1144 * 1145 * @see android.graphics.drawable.Drawable 1146 * @see #getDrawableState() 1147 */ 1148 protected static final int[] EMPTY_STATE_SET; 1149 /** 1150 * Indicates the view is enabled. States are used with 1151 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1152 * view depending on its state. 1153 * 1154 * @see android.graphics.drawable.Drawable 1155 * @see #getDrawableState() 1156 */ 1157 protected static final int[] ENABLED_STATE_SET; 1158 /** 1159 * Indicates the view is focused. States are used with 1160 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1161 * view depending on its state. 1162 * 1163 * @see android.graphics.drawable.Drawable 1164 * @see #getDrawableState() 1165 */ 1166 protected static final int[] FOCUSED_STATE_SET; 1167 /** 1168 * Indicates the view is selected. States are used with 1169 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1170 * view depending on its state. 1171 * 1172 * @see android.graphics.drawable.Drawable 1173 * @see #getDrawableState() 1174 */ 1175 protected static final int[] SELECTED_STATE_SET; 1176 /** 1177 * Indicates the view is pressed. States are used with 1178 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1179 * view depending on its state. 1180 * 1181 * @see android.graphics.drawable.Drawable 1182 * @see #getDrawableState() 1183 */ 1184 protected static final int[] PRESSED_STATE_SET; 1185 /** 1186 * Indicates the view's window has focus. States are used with 1187 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1188 * view depending on its state. 1189 * 1190 * @see android.graphics.drawable.Drawable 1191 * @see #getDrawableState() 1192 */ 1193 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1194 // Doubles 1195 /** 1196 * Indicates the view is enabled and has the focus. 1197 * 1198 * @see #ENABLED_STATE_SET 1199 * @see #FOCUSED_STATE_SET 1200 */ 1201 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1202 /** 1203 * Indicates the view is enabled and selected. 1204 * 1205 * @see #ENABLED_STATE_SET 1206 * @see #SELECTED_STATE_SET 1207 */ 1208 protected static final int[] ENABLED_SELECTED_STATE_SET; 1209 /** 1210 * Indicates the view is enabled and that its window has focus. 1211 * 1212 * @see #ENABLED_STATE_SET 1213 * @see #WINDOW_FOCUSED_STATE_SET 1214 */ 1215 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1216 /** 1217 * Indicates the view is focused and selected. 1218 * 1219 * @see #FOCUSED_STATE_SET 1220 * @see #SELECTED_STATE_SET 1221 */ 1222 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1223 /** 1224 * Indicates the view has the focus and that its window has the focus. 1225 * 1226 * @see #FOCUSED_STATE_SET 1227 * @see #WINDOW_FOCUSED_STATE_SET 1228 */ 1229 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1230 /** 1231 * Indicates the view is selected and that its window has the focus. 1232 * 1233 * @see #SELECTED_STATE_SET 1234 * @see #WINDOW_FOCUSED_STATE_SET 1235 */ 1236 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1237 // Triples 1238 /** 1239 * Indicates the view is enabled, focused and selected. 1240 * 1241 * @see #ENABLED_STATE_SET 1242 * @see #FOCUSED_STATE_SET 1243 * @see #SELECTED_STATE_SET 1244 */ 1245 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1246 /** 1247 * Indicates the view is enabled, focused and its window has the focus. 1248 * 1249 * @see #ENABLED_STATE_SET 1250 * @see #FOCUSED_STATE_SET 1251 * @see #WINDOW_FOCUSED_STATE_SET 1252 */ 1253 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1254 /** 1255 * Indicates the view is enabled, selected and its window has the focus. 1256 * 1257 * @see #ENABLED_STATE_SET 1258 * @see #SELECTED_STATE_SET 1259 * @see #WINDOW_FOCUSED_STATE_SET 1260 */ 1261 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1262 /** 1263 * Indicates the view is focused, selected and its window has the focus. 1264 * 1265 * @see #FOCUSED_STATE_SET 1266 * @see #SELECTED_STATE_SET 1267 * @see #WINDOW_FOCUSED_STATE_SET 1268 */ 1269 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1270 /** 1271 * Indicates the view is enabled, focused, selected and its window 1272 * has the focus. 1273 * 1274 * @see #ENABLED_STATE_SET 1275 * @see #FOCUSED_STATE_SET 1276 * @see #SELECTED_STATE_SET 1277 * @see #WINDOW_FOCUSED_STATE_SET 1278 */ 1279 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1280 /** 1281 * Indicates the view is pressed and its window has the focus. 1282 * 1283 * @see #PRESSED_STATE_SET 1284 * @see #WINDOW_FOCUSED_STATE_SET 1285 */ 1286 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1287 /** 1288 * Indicates the view is pressed and selected. 1289 * 1290 * @see #PRESSED_STATE_SET 1291 * @see #SELECTED_STATE_SET 1292 */ 1293 protected static final int[] PRESSED_SELECTED_STATE_SET; 1294 /** 1295 * Indicates the view is pressed, selected and its window has the focus. 1296 * 1297 * @see #PRESSED_STATE_SET 1298 * @see #SELECTED_STATE_SET 1299 * @see #WINDOW_FOCUSED_STATE_SET 1300 */ 1301 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1302 /** 1303 * Indicates the view is pressed and focused. 1304 * 1305 * @see #PRESSED_STATE_SET 1306 * @see #FOCUSED_STATE_SET 1307 */ 1308 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1309 /** 1310 * Indicates the view is pressed, focused and its window has the focus. 1311 * 1312 * @see #PRESSED_STATE_SET 1313 * @see #FOCUSED_STATE_SET 1314 * @see #WINDOW_FOCUSED_STATE_SET 1315 */ 1316 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1317 /** 1318 * Indicates the view is pressed, focused and selected. 1319 * 1320 * @see #PRESSED_STATE_SET 1321 * @see #SELECTED_STATE_SET 1322 * @see #FOCUSED_STATE_SET 1323 */ 1324 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1325 /** 1326 * Indicates the view is pressed, focused, selected and its window has the focus. 1327 * 1328 * @see #PRESSED_STATE_SET 1329 * @see #FOCUSED_STATE_SET 1330 * @see #SELECTED_STATE_SET 1331 * @see #WINDOW_FOCUSED_STATE_SET 1332 */ 1333 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1334 /** 1335 * Indicates the view is pressed and enabled. 1336 * 1337 * @see #PRESSED_STATE_SET 1338 * @see #ENABLED_STATE_SET 1339 */ 1340 protected static final int[] PRESSED_ENABLED_STATE_SET; 1341 /** 1342 * Indicates the view is pressed, enabled and its window has the focus. 1343 * 1344 * @see #PRESSED_STATE_SET 1345 * @see #ENABLED_STATE_SET 1346 * @see #WINDOW_FOCUSED_STATE_SET 1347 */ 1348 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1349 /** 1350 * Indicates the view is pressed, enabled and selected. 1351 * 1352 * @see #PRESSED_STATE_SET 1353 * @see #ENABLED_STATE_SET 1354 * @see #SELECTED_STATE_SET 1355 */ 1356 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1357 /** 1358 * Indicates the view is pressed, enabled, selected and its window has the 1359 * focus. 1360 * 1361 * @see #PRESSED_STATE_SET 1362 * @see #ENABLED_STATE_SET 1363 * @see #SELECTED_STATE_SET 1364 * @see #WINDOW_FOCUSED_STATE_SET 1365 */ 1366 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1367 /** 1368 * Indicates the view is pressed, enabled and focused. 1369 * 1370 * @see #PRESSED_STATE_SET 1371 * @see #ENABLED_STATE_SET 1372 * @see #FOCUSED_STATE_SET 1373 */ 1374 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1375 /** 1376 * Indicates the view is pressed, enabled, focused and its window has the 1377 * focus. 1378 * 1379 * @see #PRESSED_STATE_SET 1380 * @see #ENABLED_STATE_SET 1381 * @see #FOCUSED_STATE_SET 1382 * @see #WINDOW_FOCUSED_STATE_SET 1383 */ 1384 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1385 /** 1386 * Indicates the view is pressed, enabled, focused and selected. 1387 * 1388 * @see #PRESSED_STATE_SET 1389 * @see #ENABLED_STATE_SET 1390 * @see #SELECTED_STATE_SET 1391 * @see #FOCUSED_STATE_SET 1392 */ 1393 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1394 /** 1395 * Indicates the view is pressed, enabled, focused, selected and its window 1396 * has the focus. 1397 * 1398 * @see #PRESSED_STATE_SET 1399 * @see #ENABLED_STATE_SET 1400 * @see #SELECTED_STATE_SET 1401 * @see #FOCUSED_STATE_SET 1402 * @see #WINDOW_FOCUSED_STATE_SET 1403 */ 1404 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1405 1406 /** 1407 * The order here is very important to {@link #getDrawableState()} 1408 */ 1409 private static final int[][] VIEW_STATE_SETS; 1410 1411 static final int VIEW_STATE_WINDOW_FOCUSED = 1; 1412 static final int VIEW_STATE_SELECTED = 1 << 1; 1413 static final int VIEW_STATE_FOCUSED = 1 << 2; 1414 static final int VIEW_STATE_ENABLED = 1 << 3; 1415 static final int VIEW_STATE_PRESSED = 1 << 4; 1416 static final int VIEW_STATE_ACTIVATED = 1 << 5; 1417 static final int VIEW_STATE_ACCELERATED = 1 << 6; 1418 static final int VIEW_STATE_HOVERED = 1 << 7; 1419 static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8; 1420 static final int VIEW_STATE_DRAG_HOVERED = 1 << 9; 1421 1422 static final int[] VIEW_STATE_IDS = new int[] { 1423 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED, 1424 R.attr.state_selected, VIEW_STATE_SELECTED, 1425 R.attr.state_focused, VIEW_STATE_FOCUSED, 1426 R.attr.state_enabled, VIEW_STATE_ENABLED, 1427 R.attr.state_pressed, VIEW_STATE_PRESSED, 1428 R.attr.state_activated, VIEW_STATE_ACTIVATED, 1429 R.attr.state_accelerated, VIEW_STATE_ACCELERATED, 1430 R.attr.state_hovered, VIEW_STATE_HOVERED, 1431 R.attr.state_drag_can_accept, VIEW_STATE_DRAG_CAN_ACCEPT, 1432 R.attr.state_drag_hovered, VIEW_STATE_DRAG_HOVERED 1433 }; 1434 1435 static { 1436 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) { 1437 throw new IllegalStateException( 1438 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array"); 1439 } 1440 int[] orderedIds = new int[VIEW_STATE_IDS.length]; 1441 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) { 1442 int viewState = R.styleable.ViewDrawableStates[i]; 1443 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) { 1444 if (VIEW_STATE_IDS[j] == viewState) { 1445 orderedIds[i * 2] = viewState; 1446 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1]; 1447 } 1448 } 1449 } 1450 final int NUM_BITS = VIEW_STATE_IDS.length / 2; 1451 VIEW_STATE_SETS = new int[1 << NUM_BITS][]; 1452 for (int i = 0; i < VIEW_STATE_SETS.length; i++) { 1453 int numBits = Integer.bitCount(i); 1454 int[] set = new int[numBits]; 1455 int pos = 0; 1456 for (int j = 0; j < orderedIds.length; j += 2) { 1457 if ((i & orderedIds[j+1]) != 0) { 1458 set[pos++] = orderedIds[j]; 1459 } 1460 } 1461 VIEW_STATE_SETS[i] = set; 1462 } 1463 1464 EMPTY_STATE_SET = VIEW_STATE_SETS[0]; 1465 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED]; 1466 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED]; 1467 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1468 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED]; 1469 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED]; 1470 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1471 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED]; 1472 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1473 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED]; 1474 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1475 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1476 | VIEW_STATE_FOCUSED]; 1477 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED]; 1478 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1479 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED]; 1480 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1481 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED]; 1482 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1483 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1484 | VIEW_STATE_ENABLED]; 1485 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1486 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED]; 1487 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1488 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1489 | VIEW_STATE_ENABLED]; 1490 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1491 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1492 | VIEW_STATE_ENABLED]; 1493 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1494 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1495 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED]; 1496 1497 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED]; 1498 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1499 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED]; 1500 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1501 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED]; 1502 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1503 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1504 | VIEW_STATE_PRESSED]; 1505 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1506 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1507 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1508 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1509 | VIEW_STATE_PRESSED]; 1510 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1511 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1512 | VIEW_STATE_PRESSED]; 1513 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1514 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1515 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1516 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[ 1517 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1518 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1519 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED 1520 | VIEW_STATE_PRESSED]; 1521 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1522 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED 1523 | VIEW_STATE_PRESSED]; 1524 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1525 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1526 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1527 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1528 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED 1529 | VIEW_STATE_PRESSED]; 1530 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1531 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1532 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1533 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1534 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1535 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1536 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1537 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1538 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED 1539 | VIEW_STATE_PRESSED]; 1540 } 1541 1542 /** 1543 * Accessibility event types that are dispatched for text population. 1544 */ 1545 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 1546 AccessibilityEvent.TYPE_VIEW_CLICKED 1547 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 1548 | AccessibilityEvent.TYPE_VIEW_SELECTED 1549 | AccessibilityEvent.TYPE_VIEW_FOCUSED 1550 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 1551 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 1552 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 1553 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 1554 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED 1555 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED 1556 | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY; 1557 1558 /** 1559 * Temporary Rect currently for use in setBackground(). This will probably 1560 * be extended in the future to hold our own class with more than just 1561 * a Rect. :) 1562 */ 1563 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1564 1565 /** 1566 * Map used to store views' tags. 1567 */ 1568 private SparseArray<Object> mKeyedTags; 1569 1570 /** 1571 * The next available accessibility id. 1572 */ 1573 private static int sNextAccessibilityViewId; 1574 1575 /** 1576 * The animation currently associated with this view. 1577 * @hide 1578 */ 1579 protected Animation mCurrentAnimation = null; 1580 1581 /** 1582 * Width as measured during measure pass. 1583 * {@hide} 1584 */ 1585 @ViewDebug.ExportedProperty(category = "measurement") 1586 int mMeasuredWidth; 1587 1588 /** 1589 * Height as measured during measure pass. 1590 * {@hide} 1591 */ 1592 @ViewDebug.ExportedProperty(category = "measurement") 1593 int mMeasuredHeight; 1594 1595 /** 1596 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1597 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1598 * its display list. This flag, used only when hw accelerated, allows us to clear the 1599 * flag while retaining this information until it's needed (at getDisplayList() time and 1600 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1601 * 1602 * {@hide} 1603 */ 1604 boolean mRecreateDisplayList = false; 1605 1606 /** 1607 * The view's identifier. 1608 * {@hide} 1609 * 1610 * @see #setId(int) 1611 * @see #getId() 1612 */ 1613 @ViewDebug.ExportedProperty(resolveId = true) 1614 int mID = NO_ID; 1615 1616 /** 1617 * The stable ID of this view for accessibility purposes. 1618 */ 1619 int mAccessibilityViewId = NO_ID; 1620 1621 private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 1622 1623 SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent; 1624 1625 /** 1626 * The view's tag. 1627 * {@hide} 1628 * 1629 * @see #setTag(Object) 1630 * @see #getTag() 1631 */ 1632 protected Object mTag; 1633 1634 // for mPrivateFlags: 1635 /** {@hide} */ 1636 static final int PFLAG_WANTS_FOCUS = 0x00000001; 1637 /** {@hide} */ 1638 static final int PFLAG_FOCUSED = 0x00000002; 1639 /** {@hide} */ 1640 static final int PFLAG_SELECTED = 0x00000004; 1641 /** {@hide} */ 1642 static final int PFLAG_IS_ROOT_NAMESPACE = 0x00000008; 1643 /** {@hide} */ 1644 static final int PFLAG_HAS_BOUNDS = 0x00000010; 1645 /** {@hide} */ 1646 static final int PFLAG_DRAWN = 0x00000020; 1647 /** 1648 * When this flag is set, this view is running an animation on behalf of its 1649 * children and should therefore not cancel invalidate requests, even if they 1650 * lie outside of this view's bounds. 1651 * 1652 * {@hide} 1653 */ 1654 static final int PFLAG_DRAW_ANIMATION = 0x00000040; 1655 /** {@hide} */ 1656 static final int PFLAG_SKIP_DRAW = 0x00000080; 1657 /** {@hide} */ 1658 static final int PFLAG_ONLY_DRAWS_BACKGROUND = 0x00000100; 1659 /** {@hide} */ 1660 static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1661 /** {@hide} */ 1662 static final int PFLAG_DRAWABLE_STATE_DIRTY = 0x00000400; 1663 /** {@hide} */ 1664 static final int PFLAG_MEASURED_DIMENSION_SET = 0x00000800; 1665 /** {@hide} */ 1666 static final int PFLAG_FORCE_LAYOUT = 0x00001000; 1667 /** {@hide} */ 1668 static final int PFLAG_LAYOUT_REQUIRED = 0x00002000; 1669 1670 private static final int PFLAG_PRESSED = 0x00004000; 1671 1672 /** {@hide} */ 1673 static final int PFLAG_DRAWING_CACHE_VALID = 0x00008000; 1674 /** 1675 * Flag used to indicate that this view should be drawn once more (and only once 1676 * more) after its animation has completed. 1677 * {@hide} 1678 */ 1679 static final int PFLAG_ANIMATION_STARTED = 0x00010000; 1680 1681 private static final int PFLAG_SAVE_STATE_CALLED = 0x00020000; 1682 1683 /** 1684 * Indicates that the View returned true when onSetAlpha() was called and that 1685 * the alpha must be restored. 1686 * {@hide} 1687 */ 1688 static final int PFLAG_ALPHA_SET = 0x00040000; 1689 1690 /** 1691 * Set by {@link #setScrollContainer(boolean)}. 1692 */ 1693 static final int PFLAG_SCROLL_CONTAINER = 0x00080000; 1694 1695 /** 1696 * Set by {@link #setScrollContainer(boolean)}. 1697 */ 1698 static final int PFLAG_SCROLL_CONTAINER_ADDED = 0x00100000; 1699 1700 /** 1701 * View flag indicating whether this view was invalidated (fully or partially.) 1702 * 1703 * @hide 1704 */ 1705 static final int PFLAG_DIRTY = 0x00200000; 1706 1707 /** 1708 * View flag indicating whether this view was invalidated by an opaque 1709 * invalidate request. 1710 * 1711 * @hide 1712 */ 1713 static final int PFLAG_DIRTY_OPAQUE = 0x00400000; 1714 1715 /** 1716 * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}. 1717 * 1718 * @hide 1719 */ 1720 static final int PFLAG_DIRTY_MASK = 0x00600000; 1721 1722 /** 1723 * Indicates whether the background is opaque. 1724 * 1725 * @hide 1726 */ 1727 static final int PFLAG_OPAQUE_BACKGROUND = 0x00800000; 1728 1729 /** 1730 * Indicates whether the scrollbars are opaque. 1731 * 1732 * @hide 1733 */ 1734 static final int PFLAG_OPAQUE_SCROLLBARS = 0x01000000; 1735 1736 /** 1737 * Indicates whether the view is opaque. 1738 * 1739 * @hide 1740 */ 1741 static final int PFLAG_OPAQUE_MASK = 0x01800000; 1742 1743 /** 1744 * Indicates a prepressed state; 1745 * the short time between ACTION_DOWN and recognizing 1746 * a 'real' press. Prepressed is used to recognize quick taps 1747 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1748 * 1749 * @hide 1750 */ 1751 private static final int PFLAG_PREPRESSED = 0x02000000; 1752 1753 /** 1754 * Indicates whether the view is temporarily detached. 1755 * 1756 * @hide 1757 */ 1758 static final int PFLAG_CANCEL_NEXT_UP_EVENT = 0x04000000; 1759 1760 /** 1761 * Indicates that we should awaken scroll bars once attached 1762 * 1763 * @hide 1764 */ 1765 private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1766 1767 /** 1768 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1769 * @hide 1770 */ 1771 private static final int PFLAG_HOVERED = 0x10000000; 1772 1773 /** 1774 * Indicates that pivotX or pivotY were explicitly set and we should not assume the center 1775 * for transform operations 1776 * 1777 * @hide 1778 */ 1779 private static final int PFLAG_PIVOT_EXPLICITLY_SET = 0x20000000; 1780 1781 /** {@hide} */ 1782 static final int PFLAG_ACTIVATED = 0x40000000; 1783 1784 /** 1785 * Indicates that this view was specifically invalidated, not just dirtied because some 1786 * child view was invalidated. The flag is used to determine when we need to recreate 1787 * a view's display list (as opposed to just returning a reference to its existing 1788 * display list). 1789 * 1790 * @hide 1791 */ 1792 static final int PFLAG_INVALIDATED = 0x80000000; 1793 1794 /** 1795 * Masks for mPrivateFlags2, as generated by dumpFlags(): 1796 * 1797 * -------|-------|-------|-------| 1798 * PFLAG2_TEXT_ALIGNMENT_FLAGS[0] 1799 * PFLAG2_TEXT_DIRECTION_FLAGS[0] 1800 * 1 PFLAG2_DRAG_CAN_ACCEPT 1801 * 1 PFLAG2_DRAG_HOVERED 1802 * 1 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT 1803 * 11 PFLAG2_TEXT_DIRECTION_MASK_SHIFT 1804 * 1 1 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT 1805 * 11 PFLAG2_LAYOUT_DIRECTION_MASK 1806 * 11 1 PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 1807 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL 1808 * 1 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT 1809 * 1 1 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT 1810 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED 1811 * 11 PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK 1812 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[1] 1813 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[2] 1814 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[3] 1815 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[4] 1816 * 1 1 PFLAG2_TEXT_DIRECTION_FLAGS[5] 1817 * 111 PFLAG2_TEXT_DIRECTION_MASK 1818 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED 1819 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT 1820 * 111 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK 1821 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[1] 1822 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[2] 1823 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[3] 1824 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[4] 1825 * 1 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[5] 1826 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[6] 1827 * 111 PFLAG2_TEXT_ALIGNMENT_MASK 1828 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED 1829 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT 1830 * 111 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK 1831 * 11 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK 1832 * 1 PFLAG2_HAS_TRANSIENT_STATE 1833 * 1 PFLAG2_ACCESSIBILITY_FOCUSED 1834 * 1 PFLAG2_ACCESSIBILITY_STATE_CHANGED 1835 * 1 PFLAG2_VIEW_QUICK_REJECTED 1836 * 1 PFLAG2_PADDING_RESOLVED 1837 * -------|-------|-------|-------| 1838 */ 1839 1840 /** 1841 * Indicates that this view has reported that it can accept the current drag's content. 1842 * Cleared when the drag operation concludes. 1843 * @hide 1844 */ 1845 static final int PFLAG2_DRAG_CAN_ACCEPT = 0x00000001; 1846 1847 /** 1848 * Indicates that this view is currently directly under the drag location in a 1849 * drag-and-drop operation involving content that it can accept. Cleared when 1850 * the drag exits the view, or when the drag operation concludes. 1851 * @hide 1852 */ 1853 static final int PFLAG2_DRAG_HOVERED = 0x00000002; 1854 1855 /** @hide */ 1856 @IntDef({ 1857 LAYOUT_DIRECTION_LTR, 1858 LAYOUT_DIRECTION_RTL, 1859 LAYOUT_DIRECTION_INHERIT, 1860 LAYOUT_DIRECTION_LOCALE 1861 }) 1862 @Retention(RetentionPolicy.SOURCE) 1863 // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection 1864 public @interface LayoutDir {} 1865 1866 /** @hide */ 1867 @IntDef({ 1868 LAYOUT_DIRECTION_LTR, 1869 LAYOUT_DIRECTION_RTL 1870 }) 1871 @Retention(RetentionPolicy.SOURCE) 1872 public @interface ResolvedLayoutDir {} 1873 1874 /** 1875 * Horizontal layout direction of this view is from Left to Right. 1876 * Use with {@link #setLayoutDirection}. 1877 */ 1878 public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR; 1879 1880 /** 1881 * Horizontal layout direction of this view is from Right to Left. 1882 * Use with {@link #setLayoutDirection}. 1883 */ 1884 public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL; 1885 1886 /** 1887 * Horizontal layout direction of this view is inherited from its parent. 1888 * Use with {@link #setLayoutDirection}. 1889 */ 1890 public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT; 1891 1892 /** 1893 * Horizontal layout direction of this view is from deduced from the default language 1894 * script for the locale. Use with {@link #setLayoutDirection}. 1895 */ 1896 public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE; 1897 1898 /** 1899 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1900 * @hide 1901 */ 1902 static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2; 1903 1904 /** 1905 * Mask for use with private flags indicating bits used for horizontal layout direction. 1906 * @hide 1907 */ 1908 static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1909 1910 /** 1911 * Indicates whether the view horizontal layout direction has been resolved and drawn to the 1912 * right-to-left direction. 1913 * @hide 1914 */ 1915 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1916 1917 /** 1918 * Indicates whether the view horizontal layout direction has been resolved. 1919 * @hide 1920 */ 1921 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1922 1923 /** 1924 * Mask for use with private flags indicating bits used for resolved horizontal layout direction. 1925 * @hide 1926 */ 1927 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C 1928 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1929 1930 /* 1931 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct 1932 * flag value. 1933 * @hide 1934 */ 1935 private static final int[] LAYOUT_DIRECTION_FLAGS = { 1936 LAYOUT_DIRECTION_LTR, 1937 LAYOUT_DIRECTION_RTL, 1938 LAYOUT_DIRECTION_INHERIT, 1939 LAYOUT_DIRECTION_LOCALE 1940 }; 1941 1942 /** 1943 * Default horizontal layout direction. 1944 */ 1945 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 1946 1947 /** 1948 * Default horizontal layout direction. 1949 * @hide 1950 */ 1951 static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR; 1952 1953 /** 1954 * Indicates that the view is tracking some sort of transient state 1955 * that the app should not need to be aware of, but that the framework 1956 * should take special care to preserve. 1957 * 1958 * @hide 1959 */ 1960 static final int PFLAG2_HAS_TRANSIENT_STATE = 0x1 << 22; 1961 1962 /** 1963 * Text direction is inherited thru {@link ViewGroup} 1964 */ 1965 public static final int TEXT_DIRECTION_INHERIT = 0; 1966 1967 /** 1968 * Text direction is using "first strong algorithm". The first strong directional character 1969 * determines the paragraph direction. If there is no strong directional character, the 1970 * paragraph direction is the view's resolved layout direction. 1971 */ 1972 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 1973 1974 /** 1975 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 1976 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 1977 * If there are neither, the paragraph direction is the view's resolved layout direction. 1978 */ 1979 public static final int TEXT_DIRECTION_ANY_RTL = 2; 1980 1981 /** 1982 * Text direction is forced to LTR. 1983 */ 1984 public static final int TEXT_DIRECTION_LTR = 3; 1985 1986 /** 1987 * Text direction is forced to RTL. 1988 */ 1989 public static final int TEXT_DIRECTION_RTL = 4; 1990 1991 /** 1992 * Text direction is coming from the system Locale. 1993 */ 1994 public static final int TEXT_DIRECTION_LOCALE = 5; 1995 1996 /** 1997 * Default text direction is inherited 1998 */ 1999 private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT; 2000 2001 /** 2002 * Default resolved text direction 2003 * @hide 2004 */ 2005 static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG; 2006 2007 /** 2008 * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED) 2009 * @hide 2010 */ 2011 static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6; 2012 2013 /** 2014 * Mask for use with private flags indicating bits used for text direction. 2015 * @hide 2016 */ 2017 static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007 2018 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2019 2020 /** 2021 * Array of text direction flags for mapping attribute "textDirection" to correct 2022 * flag value. 2023 * @hide 2024 */ 2025 private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = { 2026 TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2027 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2028 TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2029 TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2030 TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2031 TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT 2032 }; 2033 2034 /** 2035 * Indicates whether the view text direction has been resolved. 2036 * @hide 2037 */ 2038 static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008 2039 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2040 2041 /** 2042 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2043 * @hide 2044 */ 2045 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10; 2046 2047 /** 2048 * Mask for use with private flags indicating bits used for resolved text direction. 2049 * @hide 2050 */ 2051 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 2052 << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2053 2054 /** 2055 * Indicates whether the view text direction has been resolved to the "first strong" heuristic. 2056 * @hide 2057 */ 2058 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT = 2059 TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2060 2061 /** @hide */ 2062 @IntDef({ 2063 TEXT_ALIGNMENT_INHERIT, 2064 TEXT_ALIGNMENT_GRAVITY, 2065 TEXT_ALIGNMENT_CENTER, 2066 TEXT_ALIGNMENT_TEXT_START, 2067 TEXT_ALIGNMENT_TEXT_END, 2068 TEXT_ALIGNMENT_VIEW_START, 2069 TEXT_ALIGNMENT_VIEW_END 2070 }) 2071 @Retention(RetentionPolicy.SOURCE) 2072 public @interface TextAlignment {} 2073 2074 /** 2075 * Default text alignment. The text alignment of this View is inherited from its parent. 2076 * Use with {@link #setTextAlignment(int)} 2077 */ 2078 public static final int TEXT_ALIGNMENT_INHERIT = 0; 2079 2080 /** 2081 * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL, 2082 * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction. 2083 * 2084 * Use with {@link #setTextAlignment(int)} 2085 */ 2086 public static final int TEXT_ALIGNMENT_GRAVITY = 1; 2087 2088 /** 2089 * Align to the start of the paragraph, e.g. ALIGN_NORMAL. 2090 * 2091 * Use with {@link #setTextAlignment(int)} 2092 */ 2093 public static final int TEXT_ALIGNMENT_TEXT_START = 2; 2094 2095 /** 2096 * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE. 2097 * 2098 * Use with {@link #setTextAlignment(int)} 2099 */ 2100 public static final int TEXT_ALIGNMENT_TEXT_END = 3; 2101 2102 /** 2103 * Center the paragraph, e.g. ALIGN_CENTER. 2104 * 2105 * Use with {@link #setTextAlignment(int)} 2106 */ 2107 public static final int TEXT_ALIGNMENT_CENTER = 4; 2108 2109 /** 2110 * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved 2111 * layoutDirection is LTR, and ALIGN_RIGHT otherwise. 2112 * 2113 * Use with {@link #setTextAlignment(int)} 2114 */ 2115 public static final int TEXT_ALIGNMENT_VIEW_START = 5; 2116 2117 /** 2118 * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved 2119 * layoutDirection is LTR, and ALIGN_LEFT otherwise. 2120 * 2121 * Use with {@link #setTextAlignment(int)} 2122 */ 2123 public static final int TEXT_ALIGNMENT_VIEW_END = 6; 2124 2125 /** 2126 * Default text alignment is inherited 2127 */ 2128 private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2129 2130 /** 2131 * Default resolved text alignment 2132 * @hide 2133 */ 2134 static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2135 2136 /** 2137 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2138 * @hide 2139 */ 2140 static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13; 2141 2142 /** 2143 * Mask for use with private flags indicating bits used for text alignment. 2144 * @hide 2145 */ 2146 static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2147 2148 /** 2149 * Array of text direction flags for mapping attribute "textAlignment" to correct 2150 * flag value. 2151 * @hide 2152 */ 2153 private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = { 2154 TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2155 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2156 TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2157 TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2158 TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2159 TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2160 TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 2161 }; 2162 2163 /** 2164 * Indicates whether the view text alignment has been resolved. 2165 * @hide 2166 */ 2167 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2168 2169 /** 2170 * Bit shift to get the resolved text alignment. 2171 * @hide 2172 */ 2173 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17; 2174 2175 /** 2176 * Mask for use with private flags indicating bits used for text alignment. 2177 * @hide 2178 */ 2179 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 2180 << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2181 2182 /** 2183 * Indicates whether if the view text alignment has been resolved to gravity 2184 */ 2185 private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT = 2186 TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2187 2188 // Accessiblity constants for mPrivateFlags2 2189 2190 /** 2191 * Shift for the bits in {@link #mPrivateFlags2} related to the 2192 * "importantForAccessibility" attribute. 2193 */ 2194 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20; 2195 2196 /** 2197 * Automatically determine whether a view is important for accessibility. 2198 */ 2199 public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000; 2200 2201 /** 2202 * The view is important for accessibility. 2203 */ 2204 public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001; 2205 2206 /** 2207 * The view is not important for accessibility. 2208 */ 2209 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002; 2210 2211 /** 2212 * The default whether the view is important for accessibility. 2213 */ 2214 static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO; 2215 2216 /** 2217 * Mask for obtainig the bits which specify how to determine 2218 * whether a view is important for accessibility. 2219 */ 2220 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO 2221 | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO) 2222 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2223 2224 /** 2225 * Shift for the bits in {@link #mPrivateFlags2} related to the 2226 * "accessibilityLiveRegion" attribute. 2227 */ 2228 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 22; 2229 2230 /** 2231 * Live region mode specifying that accessibility services should not 2232 * automatically announce changes to this view. This is the default live 2233 * region mode for most views. 2234 * <p> 2235 * Use with {@link #setAccessibilityLiveRegion(int)}. 2236 */ 2237 public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000; 2238 2239 /** 2240 * Live region mode specifying that accessibility services should announce 2241 * changes to this view. 2242 * <p> 2243 * Use with {@link #setAccessibilityLiveRegion(int)}. 2244 */ 2245 public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001; 2246 2247 /** 2248 * Live region mode specifying that accessibility services should interrupt 2249 * ongoing speech to immediately announce changes to this view. 2250 * <p> 2251 * Use with {@link #setAccessibilityLiveRegion(int)}. 2252 */ 2253 public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002; 2254 2255 /** 2256 * The default whether the view is important for accessibility. 2257 */ 2258 static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE; 2259 2260 /** 2261 * Mask for obtaining the bits which specify a view's accessibility live 2262 * region mode. 2263 */ 2264 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE 2265 | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE) 2266 << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 2267 2268 /** 2269 * Flag indicating whether a view has accessibility focus. 2270 */ 2271 static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000; 2272 2273 /** 2274 * Flag whether the accessibility state of the subtree rooted at this view changed. 2275 */ 2276 static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000; 2277 2278 /** 2279 * Flag indicating whether a view failed the quickReject() check in draw(). This condition 2280 * is used to check whether later changes to the view's transform should invalidate the 2281 * view to force the quickReject test to run again. 2282 */ 2283 static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000; 2284 2285 /** 2286 * Flag indicating that start/end padding has been resolved into left/right padding 2287 * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()} 2288 * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved 2289 * during measurement. In some special cases this is required such as when an adapter-based 2290 * view measures prospective children without attaching them to a window. 2291 */ 2292 static final int PFLAG2_PADDING_RESOLVED = 0x20000000; 2293 2294 /** 2295 * Flag indicating that the start/end drawables has been resolved into left/right ones. 2296 */ 2297 static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000; 2298 2299 /** 2300 * Group of bits indicating that RTL properties resolution is done. 2301 */ 2302 static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED | 2303 PFLAG2_TEXT_DIRECTION_RESOLVED | 2304 PFLAG2_TEXT_ALIGNMENT_RESOLVED | 2305 PFLAG2_PADDING_RESOLVED | 2306 PFLAG2_DRAWABLE_RESOLVED; 2307 2308 // There are a couple of flags left in mPrivateFlags2 2309 2310 /* End of masks for mPrivateFlags2 */ 2311 2312 /* Masks for mPrivateFlags3 */ 2313 2314 /** 2315 * Flag indicating that view has a transform animation set on it. This is used to track whether 2316 * an animation is cleared between successive frames, in order to tell the associated 2317 * DisplayList to clear its animation matrix. 2318 */ 2319 static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1; 2320 2321 /** 2322 * Flag indicating that view has an alpha animation set on it. This is used to track whether an 2323 * animation is cleared between successive frames, in order to tell the associated 2324 * DisplayList to restore its alpha value. 2325 */ 2326 static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2; 2327 2328 /** 2329 * Flag indicating that the view has been through at least one layout since it 2330 * was last attached to a window. 2331 */ 2332 static final int PFLAG3_IS_LAID_OUT = 0x4; 2333 2334 /** 2335 * Flag indicating that a call to measure() was skipped and should be done 2336 * instead when layout() is invoked. 2337 */ 2338 static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8; 2339 2340 /** 2341 * Flag indicating that an overridden method correctly called down to 2342 * the superclass implementation as required by the API spec. 2343 */ 2344 static final int PFLAG3_CALLED_SUPER = 0x10; 2345 2346 2347 /* End of masks for mPrivateFlags3 */ 2348 2349 static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED; 2350 2351 /** 2352 * Always allow a user to over-scroll this view, provided it is a 2353 * view that can scroll. 2354 * 2355 * @see #getOverScrollMode() 2356 * @see #setOverScrollMode(int) 2357 */ 2358 public static final int OVER_SCROLL_ALWAYS = 0; 2359 2360 /** 2361 * Allow a user to over-scroll this view only if the content is large 2362 * enough to meaningfully scroll, provided it is a view that can scroll. 2363 * 2364 * @see #getOverScrollMode() 2365 * @see #setOverScrollMode(int) 2366 */ 2367 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 2368 2369 /** 2370 * Never allow a user to over-scroll this view. 2371 * 2372 * @see #getOverScrollMode() 2373 * @see #setOverScrollMode(int) 2374 */ 2375 public static final int OVER_SCROLL_NEVER = 2; 2376 2377 /** 2378 * Special constant for {@link #setSystemUiVisibility(int)}: View has 2379 * requested the system UI (status bar) to be visible (the default). 2380 * 2381 * @see #setSystemUiVisibility(int) 2382 */ 2383 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 2384 2385 /** 2386 * Flag for {@link #setSystemUiVisibility(int)}: View has requested the 2387 * system UI to enter an unobtrusive "low profile" mode. 2388 * 2389 * <p>This is for use in games, book readers, video players, or any other 2390 * "immersive" application where the usual system chrome is deemed too distracting. 2391 * 2392 * <p>In low profile mode, the status bar and/or navigation icons may dim. 2393 * 2394 * @see #setSystemUiVisibility(int) 2395 */ 2396 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 2397 2398 /** 2399 * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the 2400 * system navigation be temporarily hidden. 2401 * 2402 * <p>This is an even less obtrusive state than that called for by 2403 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 2404 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 2405 * those to disappear. This is useful (in conjunction with the 2406 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 2407 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 2408 * window flags) for displaying content using every last pixel on the display. 2409 * 2410 * <p>There is a limitation: because navigation controls are so important, the least user 2411 * interaction will cause them to reappear immediately. When this happens, both 2412 * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically, 2413 * so that both elements reappear at the same time. 2414 * 2415 * @see #setSystemUiVisibility(int) 2416 */ 2417 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 2418 2419 /** 2420 * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go 2421 * into the normal fullscreen mode so that its content can take over the screen 2422 * while still allowing the user to interact with the application. 2423 * 2424 * <p>This has the same visual effect as 2425 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN 2426 * WindowManager.LayoutParams.FLAG_FULLSCREEN}, 2427 * meaning that non-critical screen decorations (such as the status bar) will be 2428 * hidden while the user is in the View's window, focusing the experience on 2429 * that content. Unlike the window flag, if you are using ActionBar in 2430 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2431 * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also 2432 * hide the action bar. 2433 * 2434 * <p>This approach to going fullscreen is best used over the window flag when 2435 * it is a transient state -- that is, the application does this at certain 2436 * points in its user interaction where it wants to allow the user to focus 2437 * on content, but not as a continuous state. For situations where the application 2438 * would like to simply stay full screen the entire time (such as a game that 2439 * wants to take over the screen), the 2440 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag} 2441 * is usually a better approach. The state set here will be removed by the system 2442 * in various situations (such as the user moving to another application) like 2443 * the other system UI states. 2444 * 2445 * <p>When using this flag, the application should provide some easy facility 2446 * for the user to go out of it. A common example would be in an e-book 2447 * reader, where tapping on the screen brings back whatever screen and UI 2448 * decorations that had been hidden while the user was immersed in reading 2449 * the book. 2450 * 2451 * @see #setSystemUiVisibility(int) 2452 */ 2453 public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004; 2454 2455 /** 2456 * Flag for {@link #setSystemUiVisibility(int)}: When using other layout 2457 * flags, we would like a stable view of the content insets given to 2458 * {@link #fitSystemWindows(Rect)}. This means that the insets seen there 2459 * will always represent the worst case that the application can expect 2460 * as a continuous state. In the stock Android UI this is the space for 2461 * the system bar, nav bar, and status bar, but not more transient elements 2462 * such as an input method. 2463 * 2464 * The stable layout your UI sees is based on the system UI modes you can 2465 * switch to. That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 2466 * then you will get a stable layout for changes of the 2467 * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify 2468 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and 2469 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition 2470 * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} 2471 * with a stable layout. (Note that you should avoid using 2472 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.) 2473 * 2474 * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN} 2475 * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}), 2476 * then a hidden status bar will be considered a "stable" state for purposes 2477 * here. This allows your UI to continually hide the status bar, while still 2478 * using the system UI flags to hide the action bar while still retaining 2479 * a stable layout. Note that changing the window fullscreen flag will never 2480 * provide a stable layout for a clean transition. 2481 * 2482 * <p>If you are using ActionBar in 2483 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2484 * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the 2485 * insets it adds to those given to the application. 2486 */ 2487 public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100; 2488 2489 /** 2490 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2491 * to be layed out as if it has requested 2492 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't. This 2493 * allows it to avoid artifacts when switching in and out of that mode, at 2494 * the expense that some of its user interface may be covered by screen 2495 * decorations when they are shown. You can perform layout of your inner 2496 * UI elements to account for the navigation system UI through the 2497 * {@link #fitSystemWindows(Rect)} method. 2498 */ 2499 public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200; 2500 2501 /** 2502 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2503 * to be layed out as if it has requested 2504 * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't. This 2505 * allows it to avoid artifacts when switching in and out of that mode, at 2506 * the expense that some of its user interface may be covered by screen 2507 * decorations when they are shown. You can perform layout of your inner 2508 * UI elements to account for non-fullscreen system UI through the 2509 * {@link #fitSystemWindows(Rect)} method. 2510 */ 2511 public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400; 2512 2513 /** 2514 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2515 * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation 2516 * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. Use this flag to create an immersive 2517 * experience while also hiding the system bars. If this flag is not set, 2518 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user 2519 * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system 2520 * if the user swipes from the top of the screen. 2521 * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with 2522 * system gestures, such as swiping from the top of the screen. These transient system bars 2523 * will overlay app’s content, may have some degree of transparency, and will automatically 2524 * hide after a short timeout. 2525 * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and 2526 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination 2527 * with one or both of those flags.</p> 2528 */ 2529 public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800; 2530 2531 /** 2532 * Flag for {@link #setSystemUiVisibility(int)}: View would like the status bar to have 2533 * transparency. 2534 * 2535 * <p>The transparency request may be denied if the bar is in another mode with a specific 2536 * style, like {@link #SYSTEM_UI_FLAG_IMMERSIVE immersive mode}. 2537 */ 2538 public static final int SYSTEM_UI_FLAG_TRANSPARENT_STATUS = 0x00001000; 2539 2540 /** 2541 * Flag for {@link #setSystemUiVisibility(int)}: View would like the navigation bar to have 2542 * transparency. 2543 * 2544 * <p>The transparency request may be denied if the bar is in another mode with a specific 2545 * style, like {@link #SYSTEM_UI_FLAG_IMMERSIVE immersive mode}. 2546 */ 2547 public static final int SYSTEM_UI_FLAG_TRANSPARENT_NAVIGATION = 0x00002000; 2548 2549 /** 2550 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 2551 */ 2552 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 2553 2554 /** 2555 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 2556 */ 2557 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 2558 2559 /** 2560 * @hide 2561 * 2562 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2563 * out of the public fields to keep the undefined bits out of the developer's way. 2564 * 2565 * Flag to make the status bar not expandable. Unless you also 2566 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 2567 */ 2568 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 2569 2570 /** 2571 * @hide 2572 * 2573 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2574 * out of the public fields to keep the undefined bits out of the developer's way. 2575 * 2576 * Flag to hide notification icons and scrolling ticker text. 2577 */ 2578 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 2579 2580 /** 2581 * @hide 2582 * 2583 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2584 * out of the public fields to keep the undefined bits out of the developer's way. 2585 * 2586 * Flag to disable incoming notification alerts. This will not block 2587 * icons, but it will block sound, vibrating and other visual or aural notifications. 2588 */ 2589 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 2590 2591 /** 2592 * @hide 2593 * 2594 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2595 * out of the public fields to keep the undefined bits out of the developer's way. 2596 * 2597 * Flag to hide only the scrolling ticker. Note that 2598 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 2599 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 2600 */ 2601 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 2602 2603 /** 2604 * @hide 2605 * 2606 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2607 * out of the public fields to keep the undefined bits out of the developer's way. 2608 * 2609 * Flag to hide the center system info area. 2610 */ 2611 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 2612 2613 /** 2614 * @hide 2615 * 2616 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2617 * out of the public fields to keep the undefined bits out of the developer's way. 2618 * 2619 * Flag to hide only the home button. Don't use this 2620 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2621 */ 2622 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 2623 2624 /** 2625 * @hide 2626 * 2627 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2628 * out of the public fields to keep the undefined bits out of the developer's way. 2629 * 2630 * Flag to hide only the back button. Don't use this 2631 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2632 */ 2633 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 2634 2635 /** 2636 * @hide 2637 * 2638 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2639 * out of the public fields to keep the undefined bits out of the developer's way. 2640 * 2641 * Flag to hide only the clock. You might use this if your activity has 2642 * its own clock making the status bar's clock redundant. 2643 */ 2644 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 2645 2646 /** 2647 * @hide 2648 * 2649 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2650 * out of the public fields to keep the undefined bits out of the developer's way. 2651 * 2652 * Flag to hide only the recent apps button. Don't use this 2653 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2654 */ 2655 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 2656 2657 /** 2658 * @hide 2659 * 2660 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2661 * out of the public fields to keep the undefined bits out of the developer's way. 2662 * 2663 * Flag to disable the global search gesture. Don't use this 2664 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2665 */ 2666 public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000; 2667 2668 /** 2669 * @hide 2670 * 2671 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2672 * out of the public fields to keep the undefined bits out of the developer's way. 2673 * 2674 * Flag to specify that the status bar is displayed in transient mode. 2675 */ 2676 public static final int STATUS_BAR_TRANSIENT = 0x04000000; 2677 2678 /** 2679 * @hide 2680 * 2681 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2682 * out of the public fields to keep the undefined bits out of the developer's way. 2683 * 2684 * Flag to specify that the navigation bar is displayed in transient mode. 2685 */ 2686 public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000; 2687 2688 /** 2689 * @hide 2690 * 2691 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2692 * out of the public fields to keep the undefined bits out of the developer's way. 2693 * 2694 * Flag to specify that the hidden status bar would like to be shown. 2695 */ 2696 public static final int STATUS_BAR_UNHIDE = 0x10000000; 2697 2698 /** 2699 * @hide 2700 * 2701 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2702 * out of the public fields to keep the undefined bits out of the developer's way. 2703 * 2704 * Flag to specify that the hidden navigation bar would like to be shown. 2705 */ 2706 public static final int NAVIGATION_BAR_UNHIDE = 0x20000000; 2707 2708 /** 2709 * @hide 2710 */ 2711 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF; 2712 2713 /** 2714 * These are the system UI flags that can be cleared by events outside 2715 * of an application. Currently this is just the ability to tap on the 2716 * screen while hiding the navigation bar to have it return. 2717 * @hide 2718 */ 2719 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 2720 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 2721 | SYSTEM_UI_FLAG_FULLSCREEN; 2722 2723 /** 2724 * Flags that can impact the layout in relation to system UI. 2725 */ 2726 public static final int SYSTEM_UI_LAYOUT_FLAGS = 2727 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 2728 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 2729 2730 /** @hide */ 2731 @IntDef(flag = true, 2732 value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION }) 2733 @Retention(RetentionPolicy.SOURCE) 2734 public @interface FindViewFlags {} 2735 2736 /** 2737 * Find views that render the specified text. 2738 * 2739 * @see #findViewsWithText(ArrayList, CharSequence, int) 2740 */ 2741 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 2742 2743 /** 2744 * Find find views that contain the specified content description. 2745 * 2746 * @see #findViewsWithText(ArrayList, CharSequence, int) 2747 */ 2748 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 2749 2750 /** 2751 * Find views that contain {@link AccessibilityNodeProvider}. Such 2752 * a View is a root of virtual view hierarchy and may contain the searched 2753 * text. If this flag is set Views with providers are automatically 2754 * added and it is a responsibility of the client to call the APIs of 2755 * the provider to determine whether the virtual tree rooted at this View 2756 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 2757 * representing the virtual views with this text. 2758 * 2759 * @see #findViewsWithText(ArrayList, CharSequence, int) 2760 * 2761 * @hide 2762 */ 2763 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 2764 2765 /** 2766 * The undefined cursor position. 2767 * 2768 * @hide 2769 */ 2770 public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1; 2771 2772 /** 2773 * Indicates that the screen has changed state and is now off. 2774 * 2775 * @see #onScreenStateChanged(int) 2776 */ 2777 public static final int SCREEN_STATE_OFF = 0x0; 2778 2779 /** 2780 * Indicates that the screen has changed state and is now on. 2781 * 2782 * @see #onScreenStateChanged(int) 2783 */ 2784 public static final int SCREEN_STATE_ON = 0x1; 2785 2786 /** 2787 * Controls the over-scroll mode for this view. 2788 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 2789 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 2790 * and {@link #OVER_SCROLL_NEVER}. 2791 */ 2792 private int mOverScrollMode; 2793 2794 /** 2795 * The parent this view is attached to. 2796 * {@hide} 2797 * 2798 * @see #getParent() 2799 */ 2800 protected ViewParent mParent; 2801 2802 /** 2803 * {@hide} 2804 */ 2805 AttachInfo mAttachInfo; 2806 2807 /** 2808 * {@hide} 2809 */ 2810 @ViewDebug.ExportedProperty(flagMapping = { 2811 @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT, 2812 name = "FORCE_LAYOUT"), 2813 @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED, 2814 name = "LAYOUT_REQUIRED"), 2815 @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID, 2816 name = "DRAWING_CACHE_INVALID", outputIf = false), 2817 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true), 2818 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false), 2819 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 2820 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY") 2821 }) 2822 int mPrivateFlags; 2823 int mPrivateFlags2; 2824 int mPrivateFlags3; 2825 2826 /** 2827 * This view's request for the visibility of the status bar. 2828 * @hide 2829 */ 2830 @ViewDebug.ExportedProperty(flagMapping = { 2831 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 2832 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 2833 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 2834 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2835 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2836 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 2837 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 2838 equals = SYSTEM_UI_FLAG_VISIBLE, 2839 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 2840 }) 2841 int mSystemUiVisibility; 2842 2843 /** 2844 * Reference count for transient state. 2845 * @see #setHasTransientState(boolean) 2846 */ 2847 int mTransientStateCount = 0; 2848 2849 /** 2850 * Count of how many windows this view has been attached to. 2851 */ 2852 int mWindowAttachCount; 2853 2854 /** 2855 * The layout parameters associated with this view and used by the parent 2856 * {@link android.view.ViewGroup} to determine how this view should be 2857 * laid out. 2858 * {@hide} 2859 */ 2860 protected ViewGroup.LayoutParams mLayoutParams; 2861 2862 /** 2863 * The view flags hold various views states. 2864 * {@hide} 2865 */ 2866 @ViewDebug.ExportedProperty 2867 int mViewFlags; 2868 2869 static class TransformationInfo { 2870 /** 2871 * The transform matrix for the View. This transform is calculated internally 2872 * based on the rotation, scaleX, and scaleY properties. The identity matrix 2873 * is used by default. Do *not* use this variable directly; instead call 2874 * getMatrix(), which will automatically recalculate the matrix if necessary 2875 * to get the correct matrix based on the latest rotation and scale properties. 2876 */ 2877 private final Matrix mMatrix = new Matrix(); 2878 2879 /** 2880 * The transform matrix for the View. This transform is calculated internally 2881 * based on the rotation, scaleX, and scaleY properties. The identity matrix 2882 * is used by default. Do *not* use this variable directly; instead call 2883 * getInverseMatrix(), which will automatically recalculate the matrix if necessary 2884 * to get the correct matrix based on the latest rotation and scale properties. 2885 */ 2886 private Matrix mInverseMatrix; 2887 2888 /** 2889 * An internal variable that tracks whether we need to recalculate the 2890 * transform matrix, based on whether the rotation or scaleX/Y properties 2891 * have changed since the matrix was last calculated. 2892 */ 2893 boolean mMatrixDirty = false; 2894 2895 /** 2896 * An internal variable that tracks whether we need to recalculate the 2897 * transform matrix, based on whether the rotation or scaleX/Y properties 2898 * have changed since the matrix was last calculated. 2899 */ 2900 private boolean mInverseMatrixDirty = true; 2901 2902 /** 2903 * A variable that tracks whether we need to recalculate the 2904 * transform matrix, based on whether the rotation or scaleX/Y properties 2905 * have changed since the matrix was last calculated. This variable 2906 * is only valid after a call to updateMatrix() or to a function that 2907 * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix(). 2908 */ 2909 private boolean mMatrixIsIdentity = true; 2910 2911 /** 2912 * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set. 2913 */ 2914 private Camera mCamera = null; 2915 2916 /** 2917 * This matrix is used when computing the matrix for 3D rotations. 2918 */ 2919 private Matrix matrix3D = null; 2920 2921 /** 2922 * These prev values are used to recalculate a centered pivot point when necessary. The 2923 * pivot point is only used in matrix operations (when rotation, scale, or translation are 2924 * set), so thes values are only used then as well. 2925 */ 2926 private int mPrevWidth = -1; 2927 private int mPrevHeight = -1; 2928 2929 /** 2930 * The degrees rotation around the vertical axis through the pivot point. 2931 */ 2932 @ViewDebug.ExportedProperty 2933 float mRotationY = 0f; 2934 2935 /** 2936 * The degrees rotation around the horizontal axis through the pivot point. 2937 */ 2938 @ViewDebug.ExportedProperty 2939 float mRotationX = 0f; 2940 2941 /** 2942 * The degrees rotation around the pivot point. 2943 */ 2944 @ViewDebug.ExportedProperty 2945 float mRotation = 0f; 2946 2947 /** 2948 * The amount of translation of the object away from its left property (post-layout). 2949 */ 2950 @ViewDebug.ExportedProperty 2951 float mTranslationX = 0f; 2952 2953 /** 2954 * The amount of translation of the object away from its top property (post-layout). 2955 */ 2956 @ViewDebug.ExportedProperty 2957 float mTranslationY = 0f; 2958 2959 /** 2960 * The amount of scale in the x direction around the pivot point. A 2961 * value of 1 means no scaling is applied. 2962 */ 2963 @ViewDebug.ExportedProperty 2964 float mScaleX = 1f; 2965 2966 /** 2967 * The amount of scale in the y direction around the pivot point. A 2968 * value of 1 means no scaling is applied. 2969 */ 2970 @ViewDebug.ExportedProperty 2971 float mScaleY = 1f; 2972 2973 /** 2974 * The x location of the point around which the view is rotated and scaled. 2975 */ 2976 @ViewDebug.ExportedProperty 2977 float mPivotX = 0f; 2978 2979 /** 2980 * The y location of the point around which the view is rotated and scaled. 2981 */ 2982 @ViewDebug.ExportedProperty 2983 float mPivotY = 0f; 2984 2985 /** 2986 * The opacity of the View. This is a value from 0 to 1, where 0 means 2987 * completely transparent and 1 means completely opaque. 2988 */ 2989 @ViewDebug.ExportedProperty 2990 float mAlpha = 1f; 2991 2992 /** 2993 * The opacity of the view as manipulated by the Fade transition. This is a hidden 2994 * property only used by transitions, which is composited with the other alpha 2995 * values to calculate the final visual alpha value. 2996 */ 2997 float mTransitionAlpha = 1f; 2998 } 2999 3000 TransformationInfo mTransformationInfo; 3001 3002 /** 3003 * Current clip bounds. to which all drawing of this view are constrained. 3004 */ 3005 private Rect mClipBounds = null; 3006 3007 private boolean mLastIsOpaque; 3008 3009 /** 3010 * Convenience value to check for float values that are close enough to zero to be considered 3011 * zero. 3012 */ 3013 private static final float NONZERO_EPSILON = .001f; 3014 3015 /** 3016 * The distance in pixels from the left edge of this view's parent 3017 * to the left edge of this view. 3018 * {@hide} 3019 */ 3020 @ViewDebug.ExportedProperty(category = "layout") 3021 protected int mLeft; 3022 /** 3023 * The distance in pixels from the left edge of this view's parent 3024 * to the right edge of this view. 3025 * {@hide} 3026 */ 3027 @ViewDebug.ExportedProperty(category = "layout") 3028 protected int mRight; 3029 /** 3030 * The distance in pixels from the top edge of this view's parent 3031 * to the top edge of this view. 3032 * {@hide} 3033 */ 3034 @ViewDebug.ExportedProperty(category = "layout") 3035 protected int mTop; 3036 /** 3037 * The distance in pixels from the top edge of this view's parent 3038 * to the bottom edge of this view. 3039 * {@hide} 3040 */ 3041 @ViewDebug.ExportedProperty(category = "layout") 3042 protected int mBottom; 3043 3044 /** 3045 * The offset, in pixels, by which the content of this view is scrolled 3046 * horizontally. 3047 * {@hide} 3048 */ 3049 @ViewDebug.ExportedProperty(category = "scrolling") 3050 protected int mScrollX; 3051 /** 3052 * The offset, in pixels, by which the content of this view is scrolled 3053 * vertically. 3054 * {@hide} 3055 */ 3056 @ViewDebug.ExportedProperty(category = "scrolling") 3057 protected int mScrollY; 3058 3059 /** 3060 * The left padding in pixels, that is the distance in pixels between the 3061 * left edge of this view and the left edge of its content. 3062 * {@hide} 3063 */ 3064 @ViewDebug.ExportedProperty(category = "padding") 3065 protected int mPaddingLeft = 0; 3066 /** 3067 * The right padding in pixels, that is the distance in pixels between the 3068 * right edge of this view and the right edge of its content. 3069 * {@hide} 3070 */ 3071 @ViewDebug.ExportedProperty(category = "padding") 3072 protected int mPaddingRight = 0; 3073 /** 3074 * The top padding in pixels, that is the distance in pixels between the 3075 * top edge of this view and the top edge of its content. 3076 * {@hide} 3077 */ 3078 @ViewDebug.ExportedProperty(category = "padding") 3079 protected int mPaddingTop; 3080 /** 3081 * The bottom padding in pixels, that is the distance in pixels between the 3082 * bottom edge of this view and the bottom edge of its content. 3083 * {@hide} 3084 */ 3085 @ViewDebug.ExportedProperty(category = "padding") 3086 protected int mPaddingBottom; 3087 3088 /** 3089 * The layout insets in pixels, that is the distance in pixels between the 3090 * visible edges of this view its bounds. 3091 */ 3092 private Insets mLayoutInsets; 3093 3094 /** 3095 * Briefly describes the view and is primarily used for accessibility support. 3096 */ 3097 private CharSequence mContentDescription; 3098 3099 /** 3100 * Specifies the id of a view for which this view serves as a label for 3101 * accessibility purposes. 3102 */ 3103 private int mLabelForId = View.NO_ID; 3104 3105 /** 3106 * Predicate for matching labeled view id with its label for 3107 * accessibility purposes. 3108 */ 3109 private MatchLabelForPredicate mMatchLabelForPredicate; 3110 3111 /** 3112 * Predicate for matching a view by its id. 3113 */ 3114 private MatchIdPredicate mMatchIdPredicate; 3115 3116 /** 3117 * Cache the paddingRight set by the user to append to the scrollbar's size. 3118 * 3119 * @hide 3120 */ 3121 @ViewDebug.ExportedProperty(category = "padding") 3122 protected int mUserPaddingRight; 3123 3124 /** 3125 * Cache the paddingBottom set by the user to append to the scrollbar's size. 3126 * 3127 * @hide 3128 */ 3129 @ViewDebug.ExportedProperty(category = "padding") 3130 protected int mUserPaddingBottom; 3131 3132 /** 3133 * Cache the paddingLeft set by the user to append to the scrollbar's size. 3134 * 3135 * @hide 3136 */ 3137 @ViewDebug.ExportedProperty(category = "padding") 3138 protected int mUserPaddingLeft; 3139 3140 /** 3141 * Cache the paddingStart set by the user to append to the scrollbar's size. 3142 * 3143 */ 3144 @ViewDebug.ExportedProperty(category = "padding") 3145 int mUserPaddingStart; 3146 3147 /** 3148 * Cache the paddingEnd set by the user to append to the scrollbar's size. 3149 * 3150 */ 3151 @ViewDebug.ExportedProperty(category = "padding") 3152 int mUserPaddingEnd; 3153 3154 /** 3155 * Cache initial left padding. 3156 * 3157 * @hide 3158 */ 3159 int mUserPaddingLeftInitial; 3160 3161 /** 3162 * Cache initial right padding. 3163 * 3164 * @hide 3165 */ 3166 int mUserPaddingRightInitial; 3167 3168 /** 3169 * Default undefined padding 3170 */ 3171 private static final int UNDEFINED_PADDING = Integer.MIN_VALUE; 3172 3173 /** 3174 * @hide 3175 */ 3176 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 3177 /** 3178 * @hide 3179 */ 3180 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 3181 3182 private LongSparseLongArray mMeasureCache; 3183 3184 @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_") 3185 private Drawable mBackground; 3186 3187 private int mBackgroundResource; 3188 private boolean mBackgroundSizeChanged; 3189 3190 static class ListenerInfo { 3191 /** 3192 * Listener used to dispatch focus change events. 3193 * This field should be made private, so it is hidden from the SDK. 3194 * {@hide} 3195 */ 3196 protected OnFocusChangeListener mOnFocusChangeListener; 3197 3198 /** 3199 * Listeners for layout change events. 3200 */ 3201 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 3202 3203 /** 3204 * Listeners for attach events. 3205 */ 3206 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 3207 3208 /** 3209 * Listener used to dispatch click events. 3210 * This field should be made private, so it is hidden from the SDK. 3211 * {@hide} 3212 */ 3213 public OnClickListener mOnClickListener; 3214 3215 /** 3216 * Listener used to dispatch long click events. 3217 * This field should be made private, so it is hidden from the SDK. 3218 * {@hide} 3219 */ 3220 protected OnLongClickListener mOnLongClickListener; 3221 3222 /** 3223 * Listener used to build the context menu. 3224 * This field should be made private, so it is hidden from the SDK. 3225 * {@hide} 3226 */ 3227 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 3228 3229 private OnKeyListener mOnKeyListener; 3230 3231 private OnTouchListener mOnTouchListener; 3232 3233 private OnHoverListener mOnHoverListener; 3234 3235 private OnGenericMotionListener mOnGenericMotionListener; 3236 3237 private OnDragListener mOnDragListener; 3238 3239 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 3240 } 3241 3242 ListenerInfo mListenerInfo; 3243 3244 /** 3245 * The application environment this view lives in. 3246 * This field should be made private, so it is hidden from the SDK. 3247 * {@hide} 3248 */ 3249 protected Context mContext; 3250 3251 private final Resources mResources; 3252 3253 private ScrollabilityCache mScrollCache; 3254 3255 private int[] mDrawableState = null; 3256 3257 /** 3258 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 3259 * the user may specify which view to go to next. 3260 */ 3261 private int mNextFocusLeftId = View.NO_ID; 3262 3263 /** 3264 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 3265 * the user may specify which view to go to next. 3266 */ 3267 private int mNextFocusRightId = View.NO_ID; 3268 3269 /** 3270 * When this view has focus and the next focus is {@link #FOCUS_UP}, 3271 * the user may specify which view to go to next. 3272 */ 3273 private int mNextFocusUpId = View.NO_ID; 3274 3275 /** 3276 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 3277 * the user may specify which view to go to next. 3278 */ 3279 private int mNextFocusDownId = View.NO_ID; 3280 3281 /** 3282 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 3283 * the user may specify which view to go to next. 3284 */ 3285 int mNextFocusForwardId = View.NO_ID; 3286 3287 private CheckForLongPress mPendingCheckForLongPress; 3288 private CheckForTap mPendingCheckForTap = null; 3289 private PerformClick mPerformClick; 3290 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 3291 3292 private UnsetPressedState mUnsetPressedState; 3293 3294 /** 3295 * Whether the long press's action has been invoked. The tap's action is invoked on the 3296 * up event while a long press is invoked as soon as the long press duration is reached, so 3297 * a long press could be performed before the tap is checked, in which case the tap's action 3298 * should not be invoked. 3299 */ 3300 private boolean mHasPerformedLongPress; 3301 3302 /** 3303 * The minimum height of the view. We'll try our best to have the height 3304 * of this view to at least this amount. 3305 */ 3306 @ViewDebug.ExportedProperty(category = "measurement") 3307 private int mMinHeight; 3308 3309 /** 3310 * The minimum width of the view. We'll try our best to have the width 3311 * of this view to at least this amount. 3312 */ 3313 @ViewDebug.ExportedProperty(category = "measurement") 3314 private int mMinWidth; 3315 3316 /** 3317 * The delegate to handle touch events that are physically in this view 3318 * but should be handled by another view. 3319 */ 3320 private TouchDelegate mTouchDelegate = null; 3321 3322 /** 3323 * Solid color to use as a background when creating the drawing cache. Enables 3324 * the cache to use 16 bit bitmaps instead of 32 bit. 3325 */ 3326 private int mDrawingCacheBackgroundColor = 0; 3327 3328 /** 3329 * Special tree observer used when mAttachInfo is null. 3330 */ 3331 private ViewTreeObserver mFloatingTreeObserver; 3332 3333 /** 3334 * Cache the touch slop from the context that created the view. 3335 */ 3336 private int mTouchSlop; 3337 3338 /** 3339 * Object that handles automatic animation of view properties. 3340 */ 3341 private ViewPropertyAnimator mAnimator = null; 3342 3343 /** 3344 * Flag indicating that a drag can cross window boundaries. When 3345 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 3346 * with this flag set, all visible applications will be able to participate 3347 * in the drag operation and receive the dragged content. 3348 * 3349 * @hide 3350 */ 3351 public static final int DRAG_FLAG_GLOBAL = 1; 3352 3353 /** 3354 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 3355 */ 3356 private float mVerticalScrollFactor; 3357 3358 /** 3359 * Position of the vertical scroll bar. 3360 */ 3361 private int mVerticalScrollbarPosition; 3362 3363 /** 3364 * Position the scroll bar at the default position as determined by the system. 3365 */ 3366 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 3367 3368 /** 3369 * Position the scroll bar along the left edge. 3370 */ 3371 public static final int SCROLLBAR_POSITION_LEFT = 1; 3372 3373 /** 3374 * Position the scroll bar along the right edge. 3375 */ 3376 public static final int SCROLLBAR_POSITION_RIGHT = 2; 3377 3378 /** 3379 * Indicates that the view does not have a layer. 3380 * 3381 * @see #getLayerType() 3382 * @see #setLayerType(int, android.graphics.Paint) 3383 * @see #LAYER_TYPE_SOFTWARE 3384 * @see #LAYER_TYPE_HARDWARE 3385 */ 3386 public static final int LAYER_TYPE_NONE = 0; 3387 3388 /** 3389 * <p>Indicates that the view has a software layer. A software layer is backed 3390 * by a bitmap and causes the view to be rendered using Android's software 3391 * rendering pipeline, even if hardware acceleration is enabled.</p> 3392 * 3393 * <p>Software layers have various usages:</p> 3394 * <p>When the application is not using hardware acceleration, a software layer 3395 * is useful to apply a specific color filter and/or blending mode and/or 3396 * translucency to a view and all its children.</p> 3397 * <p>When the application is using hardware acceleration, a software layer 3398 * is useful to render drawing primitives not supported by the hardware 3399 * accelerated pipeline. It can also be used to cache a complex view tree 3400 * into a texture and reduce the complexity of drawing operations. For instance, 3401 * when animating a complex view tree with a translation, a software layer can 3402 * be used to render the view tree only once.</p> 3403 * <p>Software layers should be avoided when the affected view tree updates 3404 * often. Every update will require to re-render the software layer, which can 3405 * potentially be slow (particularly when hardware acceleration is turned on 3406 * since the layer will have to be uploaded into a hardware texture after every 3407 * update.)</p> 3408 * 3409 * @see #getLayerType() 3410 * @see #setLayerType(int, android.graphics.Paint) 3411 * @see #LAYER_TYPE_NONE 3412 * @see #LAYER_TYPE_HARDWARE 3413 */ 3414 public static final int LAYER_TYPE_SOFTWARE = 1; 3415 3416 /** 3417 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 3418 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 3419 * OpenGL hardware) and causes the view to be rendered using Android's hardware 3420 * rendering pipeline, but only if hardware acceleration is turned on for the 3421 * view hierarchy. When hardware acceleration is turned off, hardware layers 3422 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 3423 * 3424 * <p>A hardware layer is useful to apply a specific color filter and/or 3425 * blending mode and/or translucency to a view and all its children.</p> 3426 * <p>A hardware layer can be used to cache a complex view tree into a 3427 * texture and reduce the complexity of drawing operations. For instance, 3428 * when animating a complex view tree with a translation, a hardware layer can 3429 * be used to render the view tree only once.</p> 3430 * <p>A hardware layer can also be used to increase the rendering quality when 3431 * rotation transformations are applied on a view. It can also be used to 3432 * prevent potential clipping issues when applying 3D transforms on a view.</p> 3433 * 3434 * @see #getLayerType() 3435 * @see #setLayerType(int, android.graphics.Paint) 3436 * @see #LAYER_TYPE_NONE 3437 * @see #LAYER_TYPE_SOFTWARE 3438 */ 3439 public static final int LAYER_TYPE_HARDWARE = 2; 3440 3441 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 3442 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 3443 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 3444 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 3445 }) 3446 int mLayerType = LAYER_TYPE_NONE; 3447 Paint mLayerPaint; 3448 Rect mLocalDirtyRect; 3449 private HardwareLayer mHardwareLayer; 3450 3451 /** 3452 * Set to true when drawing cache is enabled and cannot be created. 3453 * 3454 * @hide 3455 */ 3456 public boolean mCachingFailed; 3457 private Bitmap mDrawingCache; 3458 private Bitmap mUnscaledDrawingCache; 3459 3460 DisplayList mDisplayList; 3461 3462 /** 3463 * Set to true when the view is sending hover accessibility events because it 3464 * is the innermost hovered view. 3465 */ 3466 private boolean mSendingHoverAccessibilityEvents; 3467 3468 /** 3469 * Delegate for injecting accessibility functionality. 3470 */ 3471 AccessibilityDelegate mAccessibilityDelegate; 3472 3473 /** 3474 * The view's overlay layer. Developers get a reference to the overlay via getOverlay() 3475 * and add/remove objects to/from the overlay directly through the Overlay methods. 3476 */ 3477 ViewOverlay mOverlay; 3478 3479 /** 3480 * Consistency verifier for debugging purposes. 3481 * @hide 3482 */ 3483 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 3484 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 3485 new InputEventConsistencyVerifier(this, 0) : null; 3486 3487 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); 3488 3489 /** 3490 * Simple constructor to use when creating a view from code. 3491 * 3492 * @param context The Context the view is running in, through which it can 3493 * access the current theme, resources, etc. 3494 */ 3495 public View(Context context) { 3496 mContext = context; 3497 mResources = context != null ? context.getResources() : null; 3498 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 3499 // Set some flags defaults 3500 mPrivateFlags2 = 3501 (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) | 3502 (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) | 3503 (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) | 3504 (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) | 3505 (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) | 3506 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT); 3507 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 3508 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 3509 mUserPaddingStart = UNDEFINED_PADDING; 3510 mUserPaddingEnd = UNDEFINED_PADDING; 3511 3512 if (!sUseBrokenMakeMeasureSpec && context != null && 3513 context.getApplicationInfo().targetSdkVersion <= JELLY_BEAN_MR1) { 3514 // Older apps may need this compatibility hack for measurement. 3515 sUseBrokenMakeMeasureSpec = true; 3516 } 3517 } 3518 3519 /** 3520 * Constructor that is called when inflating a view from XML. This is called 3521 * when a view is being constructed from an XML file, supplying attributes 3522 * that were specified in the XML file. This version uses a default style of 3523 * 0, so the only attribute values applied are those in the Context's Theme 3524 * and the given AttributeSet. 3525 * 3526 * <p> 3527 * The method onFinishInflate() will be called after all children have been 3528 * added. 3529 * 3530 * @param context The Context the view is running in, through which it can 3531 * access the current theme, resources, etc. 3532 * @param attrs The attributes of the XML tag that is inflating the view. 3533 * @see #View(Context, AttributeSet, int) 3534 */ 3535 public View(Context context, AttributeSet attrs) { 3536 this(context, attrs, 0); 3537 } 3538 3539 /** 3540 * Perform inflation from XML and apply a class-specific base style from a 3541 * theme attribute. This constructor of View allows subclasses to use their 3542 * own base style when they are inflating. For example, a Button class's 3543 * constructor would call this version of the super class constructor and 3544 * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this 3545 * allows the theme's button style to modify all of the base view attributes 3546 * (in particular its background) as well as the Button class's attributes. 3547 * 3548 * @param context The Context the view is running in, through which it can 3549 * access the current theme, resources, etc. 3550 * @param attrs The attributes of the XML tag that is inflating the view. 3551 * @param defStyleAttr An attribute in the current theme that contains a 3552 * reference to a style resource that supplies default values for 3553 * the view. Can be 0 to not look for defaults. 3554 * @see #View(Context, AttributeSet) 3555 */ 3556 public View(Context context, AttributeSet attrs, int defStyleAttr) { 3557 this(context, attrs, defStyleAttr, 0); 3558 } 3559 3560 /** 3561 * Perform inflation from XML and apply a class-specific base style from a 3562 * theme attribute or style resource. This constructor of View allows 3563 * subclasses to use their own base style when they are inflating. 3564 * <p> 3565 * When determining the final value of a particular attribute, there are 3566 * four inputs that come into play: 3567 * <ol> 3568 * <li>Any attribute values in the given AttributeSet. 3569 * <li>The style resource specified in the AttributeSet (named "style"). 3570 * <li>The default style specified by <var>defStyleAttr</var>. 3571 * <li>The default style specified by <var>defStyleRes</var>. 3572 * <li>The base values in this theme. 3573 * </ol> 3574 * <p> 3575 * Each of these inputs is considered in-order, with the first listed taking 3576 * precedence over the following ones. In other words, if in the 3577 * AttributeSet you have supplied <code><Button * textColor="#ff000000"></code> 3578 * , then the button's text will <em>always</em> be black, regardless of 3579 * what is specified in any of the styles. 3580 * 3581 * @param context The Context the view is running in, through which it can 3582 * access the current theme, resources, etc. 3583 * @param attrs The attributes of the XML tag that is inflating the view. 3584 * @param defStyleAttr An attribute in the current theme that contains a 3585 * reference to a style resource that supplies default values for 3586 * the view. Can be 0 to not look for defaults. 3587 * @param defStyleRes A resource identifier of a style resource that 3588 * supplies default values for the view, used only if 3589 * defStyleAttr is 0 or can not be found in the theme. Can be 0 3590 * to not look for defaults. 3591 * @see #View(Context, AttributeSet, int) 3592 */ 3593 public View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 3594 this(context); 3595 3596 final TypedArray a = context.obtainStyledAttributes( 3597 attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes); 3598 3599 Drawable background = null; 3600 3601 int leftPadding = -1; 3602 int topPadding = -1; 3603 int rightPadding = -1; 3604 int bottomPadding = -1; 3605 int startPadding = UNDEFINED_PADDING; 3606 int endPadding = UNDEFINED_PADDING; 3607 3608 int padding = -1; 3609 3610 int viewFlagValues = 0; 3611 int viewFlagMasks = 0; 3612 3613 boolean setScrollContainer = false; 3614 3615 int x = 0; 3616 int y = 0; 3617 3618 float tx = 0; 3619 float ty = 0; 3620 float rotation = 0; 3621 float rotationX = 0; 3622 float rotationY = 0; 3623 float sx = 1f; 3624 float sy = 1f; 3625 boolean transformSet = false; 3626 3627 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 3628 int overScrollMode = mOverScrollMode; 3629 boolean initializeScrollbars = false; 3630 3631 boolean leftPaddingDefined = false; 3632 boolean rightPaddingDefined = false; 3633 boolean startPaddingDefined = false; 3634 boolean endPaddingDefined = false; 3635 3636 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3637 3638 final int N = a.getIndexCount(); 3639 for (int i = 0; i < N; i++) { 3640 int attr = a.getIndex(i); 3641 switch (attr) { 3642 case com.android.internal.R.styleable.View_background: 3643 background = a.getDrawable(attr); 3644 break; 3645 case com.android.internal.R.styleable.View_padding: 3646 padding = a.getDimensionPixelSize(attr, -1); 3647 mUserPaddingLeftInitial = padding; 3648 mUserPaddingRightInitial = padding; 3649 leftPaddingDefined = true; 3650 rightPaddingDefined = true; 3651 break; 3652 case com.android.internal.R.styleable.View_paddingLeft: 3653 leftPadding = a.getDimensionPixelSize(attr, -1); 3654 mUserPaddingLeftInitial = leftPadding; 3655 leftPaddingDefined = true; 3656 break; 3657 case com.android.internal.R.styleable.View_paddingTop: 3658 topPadding = a.getDimensionPixelSize(attr, -1); 3659 break; 3660 case com.android.internal.R.styleable.View_paddingRight: 3661 rightPadding = a.getDimensionPixelSize(attr, -1); 3662 mUserPaddingRightInitial = rightPadding; 3663 rightPaddingDefined = true; 3664 break; 3665 case com.android.internal.R.styleable.View_paddingBottom: 3666 bottomPadding = a.getDimensionPixelSize(attr, -1); 3667 break; 3668 case com.android.internal.R.styleable.View_paddingStart: 3669 startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3670 startPaddingDefined = (startPadding != UNDEFINED_PADDING); 3671 break; 3672 case com.android.internal.R.styleable.View_paddingEnd: 3673 endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3674 endPaddingDefined = (endPadding != UNDEFINED_PADDING); 3675 break; 3676 case com.android.internal.R.styleable.View_scrollX: 3677 x = a.getDimensionPixelOffset(attr, 0); 3678 break; 3679 case com.android.internal.R.styleable.View_scrollY: 3680 y = a.getDimensionPixelOffset(attr, 0); 3681 break; 3682 case com.android.internal.R.styleable.View_alpha: 3683 setAlpha(a.getFloat(attr, 1f)); 3684 break; 3685 case com.android.internal.R.styleable.View_transformPivotX: 3686 setPivotX(a.getDimensionPixelOffset(attr, 0)); 3687 break; 3688 case com.android.internal.R.styleable.View_transformPivotY: 3689 setPivotY(a.getDimensionPixelOffset(attr, 0)); 3690 break; 3691 case com.android.internal.R.styleable.View_translationX: 3692 tx = a.getDimensionPixelOffset(attr, 0); 3693 transformSet = true; 3694 break; 3695 case com.android.internal.R.styleable.View_translationY: 3696 ty = a.getDimensionPixelOffset(attr, 0); 3697 transformSet = true; 3698 break; 3699 case com.android.internal.R.styleable.View_rotation: 3700 rotation = a.getFloat(attr, 0); 3701 transformSet = true; 3702 break; 3703 case com.android.internal.R.styleable.View_rotationX: 3704 rotationX = a.getFloat(attr, 0); 3705 transformSet = true; 3706 break; 3707 case com.android.internal.R.styleable.View_rotationY: 3708 rotationY = a.getFloat(attr, 0); 3709 transformSet = true; 3710 break; 3711 case com.android.internal.R.styleable.View_scaleX: 3712 sx = a.getFloat(attr, 1f); 3713 transformSet = true; 3714 break; 3715 case com.android.internal.R.styleable.View_scaleY: 3716 sy = a.getFloat(attr, 1f); 3717 transformSet = true; 3718 break; 3719 case com.android.internal.R.styleable.View_id: 3720 mID = a.getResourceId(attr, NO_ID); 3721 break; 3722 case com.android.internal.R.styleable.View_tag: 3723 mTag = a.getText(attr); 3724 break; 3725 case com.android.internal.R.styleable.View_fitsSystemWindows: 3726 if (a.getBoolean(attr, false)) { 3727 viewFlagValues |= FITS_SYSTEM_WINDOWS; 3728 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 3729 } 3730 break; 3731 case com.android.internal.R.styleable.View_focusable: 3732 if (a.getBoolean(attr, false)) { 3733 viewFlagValues |= FOCUSABLE; 3734 viewFlagMasks |= FOCUSABLE_MASK; 3735 } 3736 break; 3737 case com.android.internal.R.styleable.View_focusableInTouchMode: 3738 if (a.getBoolean(attr, false)) { 3739 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 3740 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 3741 } 3742 break; 3743 case com.android.internal.R.styleable.View_clickable: 3744 if (a.getBoolean(attr, false)) { 3745 viewFlagValues |= CLICKABLE; 3746 viewFlagMasks |= CLICKABLE; 3747 } 3748 break; 3749 case com.android.internal.R.styleable.View_longClickable: 3750 if (a.getBoolean(attr, false)) { 3751 viewFlagValues |= LONG_CLICKABLE; 3752 viewFlagMasks |= LONG_CLICKABLE; 3753 } 3754 break; 3755 case com.android.internal.R.styleable.View_saveEnabled: 3756 if (!a.getBoolean(attr, true)) { 3757 viewFlagValues |= SAVE_DISABLED; 3758 viewFlagMasks |= SAVE_DISABLED_MASK; 3759 } 3760 break; 3761 case com.android.internal.R.styleable.View_duplicateParentState: 3762 if (a.getBoolean(attr, false)) { 3763 viewFlagValues |= DUPLICATE_PARENT_STATE; 3764 viewFlagMasks |= DUPLICATE_PARENT_STATE; 3765 } 3766 break; 3767 case com.android.internal.R.styleable.View_visibility: 3768 final int visibility = a.getInt(attr, 0); 3769 if (visibility != 0) { 3770 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 3771 viewFlagMasks |= VISIBILITY_MASK; 3772 } 3773 break; 3774 case com.android.internal.R.styleable.View_layoutDirection: 3775 // Clear any layout direction flags (included resolved bits) already set 3776 mPrivateFlags2 &= 3777 ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK); 3778 // Set the layout direction flags depending on the value of the attribute 3779 final int layoutDirection = a.getInt(attr, -1); 3780 final int value = (layoutDirection != -1) ? 3781 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 3782 mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT); 3783 break; 3784 case com.android.internal.R.styleable.View_drawingCacheQuality: 3785 final int cacheQuality = a.getInt(attr, 0); 3786 if (cacheQuality != 0) { 3787 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 3788 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 3789 } 3790 break; 3791 case com.android.internal.R.styleable.View_contentDescription: 3792 setContentDescription(a.getString(attr)); 3793 break; 3794 case com.android.internal.R.styleable.View_labelFor: 3795 setLabelFor(a.getResourceId(attr, NO_ID)); 3796 break; 3797 case com.android.internal.R.styleable.View_soundEffectsEnabled: 3798 if (!a.getBoolean(attr, true)) { 3799 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 3800 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 3801 } 3802 break; 3803 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 3804 if (!a.getBoolean(attr, true)) { 3805 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 3806 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 3807 } 3808 break; 3809 case R.styleable.View_scrollbars: 3810 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 3811 if (scrollbars != SCROLLBARS_NONE) { 3812 viewFlagValues |= scrollbars; 3813 viewFlagMasks |= SCROLLBARS_MASK; 3814 initializeScrollbars = true; 3815 } 3816 break; 3817 //noinspection deprecation 3818 case R.styleable.View_fadingEdge: 3819 if (targetSdkVersion >= ICE_CREAM_SANDWICH) { 3820 // Ignore the attribute starting with ICS 3821 break; 3822 } 3823 // With builds < ICS, fall through and apply fading edges 3824 case R.styleable.View_requiresFadingEdge: 3825 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 3826 if (fadingEdge != FADING_EDGE_NONE) { 3827 viewFlagValues |= fadingEdge; 3828 viewFlagMasks |= FADING_EDGE_MASK; 3829 initializeFadingEdge(a); 3830 } 3831 break; 3832 case R.styleable.View_scrollbarStyle: 3833 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 3834 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3835 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 3836 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 3837 } 3838 break; 3839 case R.styleable.View_isScrollContainer: 3840 setScrollContainer = true; 3841 if (a.getBoolean(attr, false)) { 3842 setScrollContainer(true); 3843 } 3844 break; 3845 case com.android.internal.R.styleable.View_keepScreenOn: 3846 if (a.getBoolean(attr, false)) { 3847 viewFlagValues |= KEEP_SCREEN_ON; 3848 viewFlagMasks |= KEEP_SCREEN_ON; 3849 } 3850 break; 3851 case R.styleable.View_filterTouchesWhenObscured: 3852 if (a.getBoolean(attr, false)) { 3853 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 3854 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 3855 } 3856 break; 3857 case R.styleable.View_nextFocusLeft: 3858 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 3859 break; 3860 case R.styleable.View_nextFocusRight: 3861 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 3862 break; 3863 case R.styleable.View_nextFocusUp: 3864 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 3865 break; 3866 case R.styleable.View_nextFocusDown: 3867 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 3868 break; 3869 case R.styleable.View_nextFocusForward: 3870 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 3871 break; 3872 case R.styleable.View_minWidth: 3873 mMinWidth = a.getDimensionPixelSize(attr, 0); 3874 break; 3875 case R.styleable.View_minHeight: 3876 mMinHeight = a.getDimensionPixelSize(attr, 0); 3877 break; 3878 case R.styleable.View_onClick: 3879 if (context.isRestricted()) { 3880 throw new IllegalStateException("The android:onClick attribute cannot " 3881 + "be used within a restricted context"); 3882 } 3883 3884 final String handlerName = a.getString(attr); 3885 if (handlerName != null) { 3886 setOnClickListener(new OnClickListener() { 3887 private Method mHandler; 3888 3889 public void onClick(View v) { 3890 if (mHandler == null) { 3891 try { 3892 mHandler = getContext().getClass().getMethod(handlerName, 3893 View.class); 3894 } catch (NoSuchMethodException e) { 3895 int id = getId(); 3896 String idText = id == NO_ID ? "" : " with id '" 3897 + getContext().getResources().getResourceEntryName( 3898 id) + "'"; 3899 throw new IllegalStateException("Could not find a method " + 3900 handlerName + "(View) in the activity " 3901 + getContext().getClass() + " for onClick handler" 3902 + " on view " + View.this.getClass() + idText, e); 3903 } 3904 } 3905 3906 try { 3907 mHandler.invoke(getContext(), View.this); 3908 } catch (IllegalAccessException e) { 3909 throw new IllegalStateException("Could not execute non " 3910 + "public method of the activity", e); 3911 } catch (InvocationTargetException e) { 3912 throw new IllegalStateException("Could not execute " 3913 + "method of the activity", e); 3914 } 3915 } 3916 }); 3917 } 3918 break; 3919 case R.styleable.View_overScrollMode: 3920 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 3921 break; 3922 case R.styleable.View_verticalScrollbarPosition: 3923 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 3924 break; 3925 case R.styleable.View_layerType: 3926 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 3927 break; 3928 case R.styleable.View_textDirection: 3929 // Clear any text direction flag already set 3930 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 3931 // Set the text direction flags depending on the value of the attribute 3932 final int textDirection = a.getInt(attr, -1); 3933 if (textDirection != -1) { 3934 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection]; 3935 } 3936 break; 3937 case R.styleable.View_textAlignment: 3938 // Clear any text alignment flag already set 3939 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 3940 // Set the text alignment flag depending on the value of the attribute 3941 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); 3942 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment]; 3943 break; 3944 case R.styleable.View_importantForAccessibility: 3945 setImportantForAccessibility(a.getInt(attr, 3946 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); 3947 break; 3948 case R.styleable.View_accessibilityLiveRegion: 3949 setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT)); 3950 break; 3951 } 3952 } 3953 3954 setOverScrollMode(overScrollMode); 3955 3956 // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet 3957 // the resolved layout direction). Those cached values will be used later during padding 3958 // resolution. 3959 mUserPaddingStart = startPadding; 3960 mUserPaddingEnd = endPadding; 3961 3962 if (background != null) { 3963 setBackground(background); 3964 } 3965 3966 if (padding >= 0) { 3967 leftPadding = padding; 3968 topPadding = padding; 3969 rightPadding = padding; 3970 bottomPadding = padding; 3971 mUserPaddingLeftInitial = padding; 3972 mUserPaddingRightInitial = padding; 3973 } 3974 3975 if (isRtlCompatibilityMode()) { 3976 // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case. 3977 // left / right padding are used if defined (meaning here nothing to do). If they are not 3978 // defined and start / end padding are defined (e.g. in Frameworks resources), then we use 3979 // start / end and resolve them as left / right (layout direction is not taken into account). 3980 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 3981 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 3982 // defined. 3983 if (!leftPaddingDefined && startPaddingDefined) { 3984 leftPadding = startPadding; 3985 } 3986 mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial; 3987 if (!rightPaddingDefined && endPaddingDefined) { 3988 rightPadding = endPadding; 3989 } 3990 mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial; 3991 } else { 3992 // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right 3993 // values defined. Otherwise, left /right values are used. 3994 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 3995 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 3996 // defined. 3997 final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined; 3998 3999 if (leftPaddingDefined && !hasRelativePadding) { 4000 mUserPaddingLeftInitial = leftPadding; 4001 } 4002 if (rightPaddingDefined && !hasRelativePadding) { 4003 mUserPaddingRightInitial = rightPadding; 4004 } 4005 } 4006 4007 internalSetPadding( 4008 mUserPaddingLeftInitial, 4009 topPadding >= 0 ? topPadding : mPaddingTop, 4010 mUserPaddingRightInitial, 4011 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 4012 4013 if (viewFlagMasks != 0) { 4014 setFlags(viewFlagValues, viewFlagMasks); 4015 } 4016 4017 if (initializeScrollbars) { 4018 initializeScrollbars(a); 4019 } 4020 4021 a.recycle(); 4022 4023 // Needs to be called after mViewFlags is set 4024 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 4025 recomputePadding(); 4026 } 4027 4028 if (x != 0 || y != 0) { 4029 scrollTo(x, y); 4030 } 4031 4032 if (transformSet) { 4033 setTranslationX(tx); 4034 setTranslationY(ty); 4035 setRotation(rotation); 4036 setRotationX(rotationX); 4037 setRotationY(rotationY); 4038 setScaleX(sx); 4039 setScaleY(sy); 4040 } 4041 4042 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 4043 setScrollContainer(true); 4044 } 4045 4046 computeOpaqueFlags(); 4047 } 4048 4049 /** 4050 * Non-public constructor for use in testing 4051 */ 4052 View() { 4053 mResources = null; 4054 } 4055 4056 public String toString() { 4057 StringBuilder out = new StringBuilder(128); 4058 out.append(getClass().getName()); 4059 out.append('{'); 4060 out.append(Integer.toHexString(System.identityHashCode(this))); 4061 out.append(' '); 4062 switch (mViewFlags&VISIBILITY_MASK) { 4063 case VISIBLE: out.append('V'); break; 4064 case INVISIBLE: out.append('I'); break; 4065 case GONE: out.append('G'); break; 4066 default: out.append('.'); break; 4067 } 4068 out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.'); 4069 out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.'); 4070 out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D'); 4071 out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.'); 4072 out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.'); 4073 out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.'); 4074 out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.'); 4075 out.append(' '); 4076 out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.'); 4077 out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.'); 4078 out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.'); 4079 if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) { 4080 out.append('p'); 4081 } else { 4082 out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.'); 4083 } 4084 out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.'); 4085 out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.'); 4086 out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.'); 4087 out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.'); 4088 out.append(' '); 4089 out.append(mLeft); 4090 out.append(','); 4091 out.append(mTop); 4092 out.append('-'); 4093 out.append(mRight); 4094 out.append(','); 4095 out.append(mBottom); 4096 final int id = getId(); 4097 if (id != NO_ID) { 4098 out.append(" #"); 4099 out.append(Integer.toHexString(id)); 4100 final Resources r = mResources; 4101 if (id != 0 && r != null) { 4102 try { 4103 String pkgname; 4104 switch (id&0xff000000) { 4105 case 0x7f000000: 4106 pkgname="app"; 4107 break; 4108 case 0x01000000: 4109 pkgname="android"; 4110 break; 4111 default: 4112 pkgname = r.getResourcePackageName(id); 4113 break; 4114 } 4115 String typename = r.getResourceTypeName(id); 4116 String entryname = r.getResourceEntryName(id); 4117 out.append(" "); 4118 out.append(pkgname); 4119 out.append(":"); 4120 out.append(typename); 4121 out.append("/"); 4122 out.append(entryname); 4123 } catch (Resources.NotFoundException e) { 4124 } 4125 } 4126 } 4127 out.append("}"); 4128 return out.toString(); 4129 } 4130 4131 /** 4132 * <p> 4133 * Initializes the fading edges from a given set of styled attributes. This 4134 * method should be called by subclasses that need fading edges and when an 4135 * instance of these subclasses is created programmatically rather than 4136 * being inflated from XML. This method is automatically called when the XML 4137 * is inflated. 4138 * </p> 4139 * 4140 * @param a the styled attributes set to initialize the fading edges from 4141 */ 4142 protected void initializeFadingEdge(TypedArray a) { 4143 initScrollCache(); 4144 4145 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 4146 R.styleable.View_fadingEdgeLength, 4147 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 4148 } 4149 4150 /** 4151 * Returns the size of the vertical faded edges used to indicate that more 4152 * content in this view is visible. 4153 * 4154 * @return The size in pixels of the vertical faded edge or 0 if vertical 4155 * faded edges are not enabled for this view. 4156 * @attr ref android.R.styleable#View_fadingEdgeLength 4157 */ 4158 public int getVerticalFadingEdgeLength() { 4159 if (isVerticalFadingEdgeEnabled()) { 4160 ScrollabilityCache cache = mScrollCache; 4161 if (cache != null) { 4162 return cache.fadingEdgeLength; 4163 } 4164 } 4165 return 0; 4166 } 4167 4168 /** 4169 * Set the size of the faded edge used to indicate that more content in this 4170 * view is available. Will not change whether the fading edge is enabled; use 4171 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 4172 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 4173 * for the vertical or horizontal fading edges. 4174 * 4175 * @param length The size in pixels of the faded edge used to indicate that more 4176 * content in this view is visible. 4177 */ 4178 public void setFadingEdgeLength(int length) { 4179 initScrollCache(); 4180 mScrollCache.fadingEdgeLength = length; 4181 } 4182 4183 /** 4184 * Returns the size of the horizontal faded edges used to indicate that more 4185 * content in this view is visible. 4186 * 4187 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 4188 * faded edges are not enabled for this view. 4189 * @attr ref android.R.styleable#View_fadingEdgeLength 4190 */ 4191 public int getHorizontalFadingEdgeLength() { 4192 if (isHorizontalFadingEdgeEnabled()) { 4193 ScrollabilityCache cache = mScrollCache; 4194 if (cache != null) { 4195 return cache.fadingEdgeLength; 4196 } 4197 } 4198 return 0; 4199 } 4200 4201 /** 4202 * Returns the width of the vertical scrollbar. 4203 * 4204 * @return The width in pixels of the vertical scrollbar or 0 if there 4205 * is no vertical scrollbar. 4206 */ 4207 public int getVerticalScrollbarWidth() { 4208 ScrollabilityCache cache = mScrollCache; 4209 if (cache != null) { 4210 ScrollBarDrawable scrollBar = cache.scrollBar; 4211 if (scrollBar != null) { 4212 int size = scrollBar.getSize(true); 4213 if (size <= 0) { 4214 size = cache.scrollBarSize; 4215 } 4216 return size; 4217 } 4218 return 0; 4219 } 4220 return 0; 4221 } 4222 4223 /** 4224 * Returns the height of the horizontal scrollbar. 4225 * 4226 * @return The height in pixels of the horizontal scrollbar or 0 if 4227 * there is no horizontal scrollbar. 4228 */ 4229 protected int getHorizontalScrollbarHeight() { 4230 ScrollabilityCache cache = mScrollCache; 4231 if (cache != null) { 4232 ScrollBarDrawable scrollBar = cache.scrollBar; 4233 if (scrollBar != null) { 4234 int size = scrollBar.getSize(false); 4235 if (size <= 0) { 4236 size = cache.scrollBarSize; 4237 } 4238 return size; 4239 } 4240 return 0; 4241 } 4242 return 0; 4243 } 4244 4245 /** 4246 * <p> 4247 * Initializes the scrollbars from a given set of styled attributes. This 4248 * method should be called by subclasses that need scrollbars and when an 4249 * instance of these subclasses is created programmatically rather than 4250 * being inflated from XML. This method is automatically called when the XML 4251 * is inflated. 4252 * </p> 4253 * 4254 * @param a the styled attributes set to initialize the scrollbars from 4255 */ 4256 protected void initializeScrollbars(TypedArray a) { 4257 initScrollCache(); 4258 4259 final ScrollabilityCache scrollabilityCache = mScrollCache; 4260 4261 if (scrollabilityCache.scrollBar == null) { 4262 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 4263 } 4264 4265 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 4266 4267 if (!fadeScrollbars) { 4268 scrollabilityCache.state = ScrollabilityCache.ON; 4269 } 4270 scrollabilityCache.fadeScrollBars = fadeScrollbars; 4271 4272 4273 scrollabilityCache.scrollBarFadeDuration = a.getInt( 4274 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 4275 .getScrollBarFadeDuration()); 4276 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 4277 R.styleable.View_scrollbarDefaultDelayBeforeFade, 4278 ViewConfiguration.getScrollDefaultDelay()); 4279 4280 4281 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 4282 com.android.internal.R.styleable.View_scrollbarSize, 4283 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 4284 4285 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 4286 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 4287 4288 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 4289 if (thumb != null) { 4290 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 4291 } 4292 4293 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 4294 false); 4295 if (alwaysDraw) { 4296 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 4297 } 4298 4299 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 4300 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 4301 4302 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 4303 if (thumb != null) { 4304 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 4305 } 4306 4307 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 4308 false); 4309 if (alwaysDraw) { 4310 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 4311 } 4312 4313 // Apply layout direction to the new Drawables if needed 4314 final int layoutDirection = getLayoutDirection(); 4315 if (track != null) { 4316 track.setLayoutDirection(layoutDirection); 4317 } 4318 if (thumb != null) { 4319 thumb.setLayoutDirection(layoutDirection); 4320 } 4321 4322 // Re-apply user/background padding so that scrollbar(s) get added 4323 resolvePadding(); 4324 } 4325 4326 /** 4327 * <p> 4328 * Initalizes the scrollability cache if necessary. 4329 * </p> 4330 */ 4331 private void initScrollCache() { 4332 if (mScrollCache == null) { 4333 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 4334 } 4335 } 4336 4337 private ScrollabilityCache getScrollCache() { 4338 initScrollCache(); 4339 return mScrollCache; 4340 } 4341 4342 /** 4343 * Set the position of the vertical scroll bar. Should be one of 4344 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 4345 * {@link #SCROLLBAR_POSITION_RIGHT}. 4346 * 4347 * @param position Where the vertical scroll bar should be positioned. 4348 */ 4349 public void setVerticalScrollbarPosition(int position) { 4350 if (mVerticalScrollbarPosition != position) { 4351 mVerticalScrollbarPosition = position; 4352 computeOpaqueFlags(); 4353 resolvePadding(); 4354 } 4355 } 4356 4357 /** 4358 * @return The position where the vertical scroll bar will show, if applicable. 4359 * @see #setVerticalScrollbarPosition(int) 4360 */ 4361 public int getVerticalScrollbarPosition() { 4362 return mVerticalScrollbarPosition; 4363 } 4364 4365 ListenerInfo getListenerInfo() { 4366 if (mListenerInfo != null) { 4367 return mListenerInfo; 4368 } 4369 mListenerInfo = new ListenerInfo(); 4370 return mListenerInfo; 4371 } 4372 4373 /** 4374 * Register a callback to be invoked when focus of this view changed. 4375 * 4376 * @param l The callback that will run. 4377 */ 4378 public void setOnFocusChangeListener(OnFocusChangeListener l) { 4379 getListenerInfo().mOnFocusChangeListener = l; 4380 } 4381 4382 /** 4383 * Add a listener that will be called when the bounds of the view change due to 4384 * layout processing. 4385 * 4386 * @param listener The listener that will be called when layout bounds change. 4387 */ 4388 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 4389 ListenerInfo li = getListenerInfo(); 4390 if (li.mOnLayoutChangeListeners == null) { 4391 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 4392 } 4393 if (!li.mOnLayoutChangeListeners.contains(listener)) { 4394 li.mOnLayoutChangeListeners.add(listener); 4395 } 4396 } 4397 4398 /** 4399 * Remove a listener for layout changes. 4400 * 4401 * @param listener The listener for layout bounds change. 4402 */ 4403 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 4404 ListenerInfo li = mListenerInfo; 4405 if (li == null || li.mOnLayoutChangeListeners == null) { 4406 return; 4407 } 4408 li.mOnLayoutChangeListeners.remove(listener); 4409 } 4410 4411 /** 4412 * Add a listener for attach state changes. 4413 * 4414 * This listener will be called whenever this view is attached or detached 4415 * from a window. Remove the listener using 4416 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 4417 * 4418 * @param listener Listener to attach 4419 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 4420 */ 4421 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4422 ListenerInfo li = getListenerInfo(); 4423 if (li.mOnAttachStateChangeListeners == null) { 4424 li.mOnAttachStateChangeListeners 4425 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 4426 } 4427 li.mOnAttachStateChangeListeners.add(listener); 4428 } 4429 4430 /** 4431 * Remove a listener for attach state changes. The listener will receive no further 4432 * notification of window attach/detach events. 4433 * 4434 * @param listener Listener to remove 4435 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 4436 */ 4437 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4438 ListenerInfo li = mListenerInfo; 4439 if (li == null || li.mOnAttachStateChangeListeners == null) { 4440 return; 4441 } 4442 li.mOnAttachStateChangeListeners.remove(listener); 4443 } 4444 4445 /** 4446 * Returns the focus-change callback registered for this view. 4447 * 4448 * @return The callback, or null if one is not registered. 4449 */ 4450 public OnFocusChangeListener getOnFocusChangeListener() { 4451 ListenerInfo li = mListenerInfo; 4452 return li != null ? li.mOnFocusChangeListener : null; 4453 } 4454 4455 /** 4456 * Register a callback to be invoked when this view is clicked. If this view is not 4457 * clickable, it becomes clickable. 4458 * 4459 * @param l The callback that will run 4460 * 4461 * @see #setClickable(boolean) 4462 */ 4463 public void setOnClickListener(OnClickListener l) { 4464 if (!isClickable()) { 4465 setClickable(true); 4466 } 4467 getListenerInfo().mOnClickListener = l; 4468 } 4469 4470 /** 4471 * Return whether this view has an attached OnClickListener. Returns 4472 * true if there is a listener, false if there is none. 4473 */ 4474 public boolean hasOnClickListeners() { 4475 ListenerInfo li = mListenerInfo; 4476 return (li != null && li.mOnClickListener != null); 4477 } 4478 4479 /** 4480 * Register a callback to be invoked when this view is clicked and held. If this view is not 4481 * long clickable, it becomes long clickable. 4482 * 4483 * @param l The callback that will run 4484 * 4485 * @see #setLongClickable(boolean) 4486 */ 4487 public void setOnLongClickListener(OnLongClickListener l) { 4488 if (!isLongClickable()) { 4489 setLongClickable(true); 4490 } 4491 getListenerInfo().mOnLongClickListener = l; 4492 } 4493 4494 /** 4495 * Register a callback to be invoked when the context menu for this view is 4496 * being built. If this view is not long clickable, it becomes long clickable. 4497 * 4498 * @param l The callback that will run 4499 * 4500 */ 4501 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 4502 if (!isLongClickable()) { 4503 setLongClickable(true); 4504 } 4505 getListenerInfo().mOnCreateContextMenuListener = l; 4506 } 4507 4508 /** 4509 * Call this view's OnClickListener, if it is defined. Performs all normal 4510 * actions associated with clicking: reporting accessibility event, playing 4511 * a sound, etc. 4512 * 4513 * @return True there was an assigned OnClickListener that was called, false 4514 * otherwise is returned. 4515 */ 4516 public boolean performClick() { 4517 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 4518 4519 ListenerInfo li = mListenerInfo; 4520 if (li != null && li.mOnClickListener != null) { 4521 playSoundEffect(SoundEffectConstants.CLICK); 4522 li.mOnClickListener.onClick(this); 4523 return true; 4524 } 4525 4526 return false; 4527 } 4528 4529 /** 4530 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 4531 * this only calls the listener, and does not do any associated clicking 4532 * actions like reporting an accessibility event. 4533 * 4534 * @return True there was an assigned OnClickListener that was called, false 4535 * otherwise is returned. 4536 */ 4537 public boolean callOnClick() { 4538 ListenerInfo li = mListenerInfo; 4539 if (li != null && li.mOnClickListener != null) { 4540 li.mOnClickListener.onClick(this); 4541 return true; 4542 } 4543 return false; 4544 } 4545 4546 /** 4547 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 4548 * OnLongClickListener did not consume the event. 4549 * 4550 * @return True if one of the above receivers consumed the event, false otherwise. 4551 */ 4552 public boolean performLongClick() { 4553 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 4554 4555 boolean handled = false; 4556 ListenerInfo li = mListenerInfo; 4557 if (li != null && li.mOnLongClickListener != null) { 4558 handled = li.mOnLongClickListener.onLongClick(View.this); 4559 } 4560 if (!handled) { 4561 handled = showContextMenu(); 4562 } 4563 if (handled) { 4564 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 4565 } 4566 return handled; 4567 } 4568 4569 /** 4570 * Performs button-related actions during a touch down event. 4571 * 4572 * @param event The event. 4573 * @return True if the down was consumed. 4574 * 4575 * @hide 4576 */ 4577 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 4578 if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 4579 if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) { 4580 return true; 4581 } 4582 } 4583 return false; 4584 } 4585 4586 /** 4587 * Bring up the context menu for this view. 4588 * 4589 * @return Whether a context menu was displayed. 4590 */ 4591 public boolean showContextMenu() { 4592 return getParent().showContextMenuForChild(this); 4593 } 4594 4595 /** 4596 * Bring up the context menu for this view, referring to the item under the specified point. 4597 * 4598 * @param x The referenced x coordinate. 4599 * @param y The referenced y coordinate. 4600 * @param metaState The keyboard modifiers that were pressed. 4601 * @return Whether a context menu was displayed. 4602 * 4603 * @hide 4604 */ 4605 public boolean showContextMenu(float x, float y, int metaState) { 4606 return showContextMenu(); 4607 } 4608 4609 /** 4610 * Start an action mode. 4611 * 4612 * @param callback Callback that will control the lifecycle of the action mode 4613 * @return The new action mode if it is started, null otherwise 4614 * 4615 * @see ActionMode 4616 */ 4617 public ActionMode startActionMode(ActionMode.Callback callback) { 4618 ViewParent parent = getParent(); 4619 if (parent == null) return null; 4620 return parent.startActionModeForChild(this, callback); 4621 } 4622 4623 /** 4624 * Register a callback to be invoked when a hardware key is pressed in this view. 4625 * Key presses in software input methods will generally not trigger the methods of 4626 * this listener. 4627 * @param l the key listener to attach to this view 4628 */ 4629 public void setOnKeyListener(OnKeyListener l) { 4630 getListenerInfo().mOnKeyListener = l; 4631 } 4632 4633 /** 4634 * Register a callback to be invoked when a touch event is sent to this view. 4635 * @param l the touch listener to attach to this view 4636 */ 4637 public void setOnTouchListener(OnTouchListener l) { 4638 getListenerInfo().mOnTouchListener = l; 4639 } 4640 4641 /** 4642 * Register a callback to be invoked when a generic motion event is sent to this view. 4643 * @param l the generic motion listener to attach to this view 4644 */ 4645 public void setOnGenericMotionListener(OnGenericMotionListener l) { 4646 getListenerInfo().mOnGenericMotionListener = l; 4647 } 4648 4649 /** 4650 * Register a callback to be invoked when a hover event is sent to this view. 4651 * @param l the hover listener to attach to this view 4652 */ 4653 public void setOnHoverListener(OnHoverListener l) { 4654 getListenerInfo().mOnHoverListener = l; 4655 } 4656 4657 /** 4658 * Register a drag event listener callback object for this View. The parameter is 4659 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 4660 * View, the system calls the 4661 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 4662 * @param l An implementation of {@link android.view.View.OnDragListener}. 4663 */ 4664 public void setOnDragListener(OnDragListener l) { 4665 getListenerInfo().mOnDragListener = l; 4666 } 4667 4668 /** 4669 * Give this view focus. This will cause 4670 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 4671 * 4672 * Note: this does not check whether this {@link View} should get focus, it just 4673 * gives it focus no matter what. It should only be called internally by framework 4674 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 4675 * 4676 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 4677 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 4678 * focus moved when requestFocus() is called. It may not always 4679 * apply, in which case use the default View.FOCUS_DOWN. 4680 * @param previouslyFocusedRect The rectangle of the view that had focus 4681 * prior in this View's coordinate system. 4682 */ 4683 void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) { 4684 if (DBG) { 4685 System.out.println(this + " requestFocus()"); 4686 } 4687 4688 if ((mPrivateFlags & PFLAG_FOCUSED) == 0) { 4689 mPrivateFlags |= PFLAG_FOCUSED; 4690 4691 View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null; 4692 4693 if (mParent != null) { 4694 mParent.requestChildFocus(this, this); 4695 } 4696 4697 if (mAttachInfo != null) { 4698 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this); 4699 } 4700 4701 onFocusChanged(true, direction, previouslyFocusedRect); 4702 refreshDrawableState(); 4703 } 4704 } 4705 4706 /** 4707 * Request that a rectangle of this view be visible on the screen, 4708 * scrolling if necessary just enough. 4709 * 4710 * <p>A View should call this if it maintains some notion of which part 4711 * of its content is interesting. For example, a text editing view 4712 * should call this when its cursor moves. 4713 * 4714 * @param rectangle The rectangle. 4715 * @return Whether any parent scrolled. 4716 */ 4717 public boolean requestRectangleOnScreen(Rect rectangle) { 4718 return requestRectangleOnScreen(rectangle, false); 4719 } 4720 4721 /** 4722 * Request that a rectangle of this view be visible on the screen, 4723 * scrolling if necessary just enough. 4724 * 4725 * <p>A View should call this if it maintains some notion of which part 4726 * of its content is interesting. For example, a text editing view 4727 * should call this when its cursor moves. 4728 * 4729 * <p>When <code>immediate</code> is set to true, scrolling will not be 4730 * animated. 4731 * 4732 * @param rectangle The rectangle. 4733 * @param immediate True to forbid animated scrolling, false otherwise 4734 * @return Whether any parent scrolled. 4735 */ 4736 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 4737 if (mParent == null) { 4738 return false; 4739 } 4740 4741 View child = this; 4742 4743 RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF(); 4744 position.set(rectangle); 4745 4746 ViewParent parent = mParent; 4747 boolean scrolled = false; 4748 while (parent != null) { 4749 rectangle.set((int) position.left, (int) position.top, 4750 (int) position.right, (int) position.bottom); 4751 4752 scrolled |= parent.requestChildRectangleOnScreen(child, 4753 rectangle, immediate); 4754 4755 if (!child.hasIdentityMatrix()) { 4756 child.getMatrix().mapRect(position); 4757 } 4758 4759 position.offset(child.mLeft, child.mTop); 4760 4761 if (!(parent instanceof View)) { 4762 break; 4763 } 4764 4765 View parentView = (View) parent; 4766 4767 position.offset(-parentView.getScrollX(), -parentView.getScrollY()); 4768 4769 child = parentView; 4770 parent = child.getParent(); 4771 } 4772 4773 return scrolled; 4774 } 4775 4776 /** 4777 * Called when this view wants to give up focus. If focus is cleared 4778 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 4779 * <p> 4780 * <strong>Note:</strong> When a View clears focus the framework is trying 4781 * to give focus to the first focusable View from the top. Hence, if this 4782 * View is the first from the top that can take focus, then all callbacks 4783 * related to clearing focus will be invoked after wich the framework will 4784 * give focus to this view. 4785 * </p> 4786 */ 4787 public void clearFocus() { 4788 if (DBG) { 4789 System.out.println(this + " clearFocus()"); 4790 } 4791 4792 clearFocusInternal(true, true); 4793 } 4794 4795 /** 4796 * Clears focus from the view, optionally propagating the change up through 4797 * the parent hierarchy and requesting that the root view place new focus. 4798 * 4799 * @param propagate whether to propagate the change up through the parent 4800 * hierarchy 4801 * @param refocus when propagate is true, specifies whether to request the 4802 * root view place new focus 4803 */ 4804 void clearFocusInternal(boolean propagate, boolean refocus) { 4805 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 4806 mPrivateFlags &= ~PFLAG_FOCUSED; 4807 4808 if (propagate && mParent != null) { 4809 mParent.clearChildFocus(this); 4810 } 4811 4812 onFocusChanged(false, 0, null); 4813 4814 refreshDrawableState(); 4815 4816 if (propagate && (!refocus || !rootViewRequestFocus())) { 4817 notifyGlobalFocusCleared(this); 4818 } 4819 } 4820 } 4821 4822 void notifyGlobalFocusCleared(View oldFocus) { 4823 if (oldFocus != null && mAttachInfo != null) { 4824 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null); 4825 } 4826 } 4827 4828 boolean rootViewRequestFocus() { 4829 final View root = getRootView(); 4830 return root != null && root.requestFocus(); 4831 } 4832 4833 /** 4834 * Called internally by the view system when a new view is getting focus. 4835 * This is what clears the old focus. 4836 * <p> 4837 * <b>NOTE:</b> The parent view's focused child must be updated manually 4838 * after calling this method. Otherwise, the view hierarchy may be left in 4839 * an inconstent state. 4840 */ 4841 void unFocus() { 4842 if (DBG) { 4843 System.out.println(this + " unFocus()"); 4844 } 4845 4846 clearFocusInternal(false, false); 4847 } 4848 4849 /** 4850 * Returns true if this view has focus iteself, or is the ancestor of the 4851 * view that has focus. 4852 * 4853 * @return True if this view has or contains focus, false otherwise. 4854 */ 4855 @ViewDebug.ExportedProperty(category = "focus") 4856 public boolean hasFocus() { 4857 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 4858 } 4859 4860 /** 4861 * Returns true if this view is focusable or if it contains a reachable View 4862 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 4863 * is a View whose parents do not block descendants focus. 4864 * 4865 * Only {@link #VISIBLE} views are considered focusable. 4866 * 4867 * @return True if the view is focusable or if the view contains a focusable 4868 * View, false otherwise. 4869 * 4870 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 4871 */ 4872 public boolean hasFocusable() { 4873 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 4874 } 4875 4876 /** 4877 * Called by the view system when the focus state of this view changes. 4878 * When the focus change event is caused by directional navigation, direction 4879 * and previouslyFocusedRect provide insight into where the focus is coming from. 4880 * When overriding, be sure to call up through to the super class so that 4881 * the standard focus handling will occur. 4882 * 4883 * @param gainFocus True if the View has focus; false otherwise. 4884 * @param direction The direction focus has moved when requestFocus() 4885 * is called to give this view focus. Values are 4886 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 4887 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 4888 * It may not always apply, in which case use the default. 4889 * @param previouslyFocusedRect The rectangle, in this view's coordinate 4890 * system, of the previously focused view. If applicable, this will be 4891 * passed in as finer grained information about where the focus is coming 4892 * from (in addition to direction). Will be <code>null</code> otherwise. 4893 */ 4894 protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction, 4895 @Nullable Rect previouslyFocusedRect) { 4896 if (gainFocus) { 4897 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 4898 } else { 4899 notifyViewAccessibilityStateChangedIfNeeded( 4900 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 4901 } 4902 4903 InputMethodManager imm = InputMethodManager.peekInstance(); 4904 if (!gainFocus) { 4905 if (isPressed()) { 4906 setPressed(false); 4907 } 4908 if (imm != null && mAttachInfo != null 4909 && mAttachInfo.mHasWindowFocus) { 4910 imm.focusOut(this); 4911 } 4912 onFocusLost(); 4913 } else if (imm != null && mAttachInfo != null 4914 && mAttachInfo.mHasWindowFocus) { 4915 imm.focusIn(this); 4916 } 4917 4918 invalidate(true); 4919 ListenerInfo li = mListenerInfo; 4920 if (li != null && li.mOnFocusChangeListener != null) { 4921 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 4922 } 4923 4924 if (mAttachInfo != null) { 4925 mAttachInfo.mKeyDispatchState.reset(this); 4926 } 4927 } 4928 4929 /** 4930 * Sends an accessibility event of the given type. If accessibility is 4931 * not enabled this method has no effect. The default implementation calls 4932 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 4933 * to populate information about the event source (this View), then calls 4934 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 4935 * populate the text content of the event source including its descendants, 4936 * and last calls 4937 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 4938 * on its parent to resuest sending of the event to interested parties. 4939 * <p> 4940 * If an {@link AccessibilityDelegate} has been specified via calling 4941 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4942 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 4943 * responsible for handling this call. 4944 * </p> 4945 * 4946 * @param eventType The type of the event to send, as defined by several types from 4947 * {@link android.view.accessibility.AccessibilityEvent}, such as 4948 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 4949 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 4950 * 4951 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 4952 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4953 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 4954 * @see AccessibilityDelegate 4955 */ 4956 public void sendAccessibilityEvent(int eventType) { 4957 // Excluded views do not send accessibility events. 4958 if (!includeForAccessibility()) { 4959 return; 4960 } 4961 if (mAccessibilityDelegate != null) { 4962 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 4963 } else { 4964 sendAccessibilityEventInternal(eventType); 4965 } 4966 } 4967 4968 /** 4969 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 4970 * {@link AccessibilityEvent} to make an announcement which is related to some 4971 * sort of a context change for which none of the events representing UI transitions 4972 * is a good fit. For example, announcing a new page in a book. If accessibility 4973 * is not enabled this method does nothing. 4974 * 4975 * @param text The announcement text. 4976 */ 4977 public void announceForAccessibility(CharSequence text) { 4978 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) { 4979 AccessibilityEvent event = AccessibilityEvent.obtain( 4980 AccessibilityEvent.TYPE_ANNOUNCEMENT); 4981 onInitializeAccessibilityEvent(event); 4982 event.getText().add(text); 4983 event.setContentDescription(null); 4984 mParent.requestSendAccessibilityEvent(this, event); 4985 } 4986 } 4987 4988 /** 4989 * @see #sendAccessibilityEvent(int) 4990 * 4991 * Note: Called from the default {@link AccessibilityDelegate}. 4992 */ 4993 void sendAccessibilityEventInternal(int eventType) { 4994 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 4995 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 4996 } 4997 } 4998 4999 /** 5000 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 5001 * takes as an argument an empty {@link AccessibilityEvent} and does not 5002 * perform a check whether accessibility is enabled. 5003 * <p> 5004 * If an {@link AccessibilityDelegate} has been specified via calling 5005 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5006 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 5007 * is responsible for handling this call. 5008 * </p> 5009 * 5010 * @param event The event to send. 5011 * 5012 * @see #sendAccessibilityEvent(int) 5013 */ 5014 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 5015 if (mAccessibilityDelegate != null) { 5016 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 5017 } else { 5018 sendAccessibilityEventUncheckedInternal(event); 5019 } 5020 } 5021 5022 /** 5023 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 5024 * 5025 * Note: Called from the default {@link AccessibilityDelegate}. 5026 */ 5027 void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 5028 if (!isShown()) { 5029 return; 5030 } 5031 onInitializeAccessibilityEvent(event); 5032 // Only a subset of accessibility events populates text content. 5033 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 5034 dispatchPopulateAccessibilityEvent(event); 5035 } 5036 // In the beginning we called #isShown(), so we know that getParent() is not null. 5037 getParent().requestSendAccessibilityEvent(this, event); 5038 } 5039 5040 /** 5041 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 5042 * to its children for adding their text content to the event. Note that the 5043 * event text is populated in a separate dispatch path since we add to the 5044 * event not only the text of the source but also the text of all its descendants. 5045 * A typical implementation will call 5046 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 5047 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5048 * on each child. Override this method if custom population of the event text 5049 * content is required. 5050 * <p> 5051 * If an {@link AccessibilityDelegate} has been specified via calling 5052 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5053 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 5054 * is responsible for handling this call. 5055 * </p> 5056 * <p> 5057 * <em>Note:</em> Accessibility events of certain types are not dispatched for 5058 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 5059 * </p> 5060 * 5061 * @param event The event. 5062 * 5063 * @return True if the event population was completed. 5064 */ 5065 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 5066 if (mAccessibilityDelegate != null) { 5067 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 5068 } else { 5069 return dispatchPopulateAccessibilityEventInternal(event); 5070 } 5071 } 5072 5073 /** 5074 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5075 * 5076 * Note: Called from the default {@link AccessibilityDelegate}. 5077 */ 5078 boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5079 onPopulateAccessibilityEvent(event); 5080 return false; 5081 } 5082 5083 /** 5084 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5085 * giving a chance to this View to populate the accessibility event with its 5086 * text content. While this method is free to modify event 5087 * attributes other than text content, doing so should normally be performed in 5088 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 5089 * <p> 5090 * Example: Adding formatted date string to an accessibility event in addition 5091 * to the text added by the super implementation: 5092 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5093 * super.onPopulateAccessibilityEvent(event); 5094 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 5095 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 5096 * mCurrentDate.getTimeInMillis(), flags); 5097 * event.getText().add(selectedDateUtterance); 5098 * }</pre> 5099 * <p> 5100 * If an {@link AccessibilityDelegate} has been specified via calling 5101 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5102 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 5103 * is responsible for handling this call. 5104 * </p> 5105 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5106 * information to the event, in case the default implementation has basic information to add. 5107 * </p> 5108 * 5109 * @param event The accessibility event which to populate. 5110 * 5111 * @see #sendAccessibilityEvent(int) 5112 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5113 */ 5114 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5115 if (mAccessibilityDelegate != null) { 5116 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 5117 } else { 5118 onPopulateAccessibilityEventInternal(event); 5119 } 5120 } 5121 5122 /** 5123 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 5124 * 5125 * Note: Called from the default {@link AccessibilityDelegate}. 5126 */ 5127 void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5128 } 5129 5130 /** 5131 * Initializes an {@link AccessibilityEvent} with information about 5132 * this View which is the event source. In other words, the source of 5133 * an accessibility event is the view whose state change triggered firing 5134 * the event. 5135 * <p> 5136 * Example: Setting the password property of an event in addition 5137 * to properties set by the super implementation: 5138 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5139 * super.onInitializeAccessibilityEvent(event); 5140 * event.setPassword(true); 5141 * }</pre> 5142 * <p> 5143 * If an {@link AccessibilityDelegate} has been specified via calling 5144 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5145 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 5146 * is responsible for handling this call. 5147 * </p> 5148 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5149 * information to the event, in case the default implementation has basic information to add. 5150 * </p> 5151 * @param event The event to initialize. 5152 * 5153 * @see #sendAccessibilityEvent(int) 5154 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5155 */ 5156 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5157 if (mAccessibilityDelegate != null) { 5158 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 5159 } else { 5160 onInitializeAccessibilityEventInternal(event); 5161 } 5162 } 5163 5164 /** 5165 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5166 * 5167 * Note: Called from the default {@link AccessibilityDelegate}. 5168 */ 5169 void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 5170 event.setSource(this); 5171 event.setClassName(View.class.getName()); 5172 event.setPackageName(getContext().getPackageName()); 5173 event.setEnabled(isEnabled()); 5174 event.setContentDescription(mContentDescription); 5175 5176 switch (event.getEventType()) { 5177 case AccessibilityEvent.TYPE_VIEW_FOCUSED: { 5178 ArrayList<View> focusablesTempList = (mAttachInfo != null) 5179 ? mAttachInfo.mTempArrayList : new ArrayList<View>(); 5180 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL); 5181 event.setItemCount(focusablesTempList.size()); 5182 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 5183 if (mAttachInfo != null) { 5184 focusablesTempList.clear(); 5185 } 5186 } break; 5187 case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: { 5188 CharSequence text = getIterableTextForAccessibility(); 5189 if (text != null && text.length() > 0) { 5190 event.setFromIndex(getAccessibilitySelectionStart()); 5191 event.setToIndex(getAccessibilitySelectionEnd()); 5192 event.setItemCount(text.length()); 5193 } 5194 } break; 5195 } 5196 } 5197 5198 /** 5199 * Returns an {@link AccessibilityNodeInfo} representing this view from the 5200 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 5201 * This method is responsible for obtaining an accessibility node info from a 5202 * pool of reusable instances and calling 5203 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 5204 * initialize the former. 5205 * <p> 5206 * Note: The client is responsible for recycling the obtained instance by calling 5207 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 5208 * </p> 5209 * 5210 * @return A populated {@link AccessibilityNodeInfo}. 5211 * 5212 * @see AccessibilityNodeInfo 5213 */ 5214 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 5215 if (mAccessibilityDelegate != null) { 5216 return mAccessibilityDelegate.createAccessibilityNodeInfo(this); 5217 } else { 5218 return createAccessibilityNodeInfoInternal(); 5219 } 5220 } 5221 5222 /** 5223 * @see #createAccessibilityNodeInfo() 5224 */ 5225 AccessibilityNodeInfo createAccessibilityNodeInfoInternal() { 5226 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 5227 if (provider != null) { 5228 return provider.createAccessibilityNodeInfo(View.NO_ID); 5229 } else { 5230 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 5231 onInitializeAccessibilityNodeInfo(info); 5232 return info; 5233 } 5234 } 5235 5236 /** 5237 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 5238 * The base implementation sets: 5239 * <ul> 5240 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 5241 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 5242 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 5243 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 5244 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 5245 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 5246 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 5247 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 5248 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 5249 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 5250 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 5251 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 5252 * </ul> 5253 * <p> 5254 * Subclasses should override this method, call the super implementation, 5255 * and set additional attributes. 5256 * </p> 5257 * <p> 5258 * If an {@link AccessibilityDelegate} has been specified via calling 5259 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5260 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 5261 * is responsible for handling this call. 5262 * </p> 5263 * 5264 * @param info The instance to initialize. 5265 */ 5266 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 5267 if (mAccessibilityDelegate != null) { 5268 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 5269 } else { 5270 onInitializeAccessibilityNodeInfoInternal(info); 5271 } 5272 } 5273 5274 /** 5275 * Gets the location of this view in screen coordintates. 5276 * 5277 * @param outRect The output location 5278 */ 5279 void getBoundsOnScreen(Rect outRect) { 5280 if (mAttachInfo == null) { 5281 return; 5282 } 5283 5284 RectF position = mAttachInfo.mTmpTransformRect; 5285 position.set(0, 0, mRight - mLeft, mBottom - mTop); 5286 5287 if (!hasIdentityMatrix()) { 5288 getMatrix().mapRect(position); 5289 } 5290 5291 position.offset(mLeft, mTop); 5292 5293 ViewParent parent = mParent; 5294 while (parent instanceof View) { 5295 View parentView = (View) parent; 5296 5297 position.offset(-parentView.mScrollX, -parentView.mScrollY); 5298 5299 if (!parentView.hasIdentityMatrix()) { 5300 parentView.getMatrix().mapRect(position); 5301 } 5302 5303 position.offset(parentView.mLeft, parentView.mTop); 5304 5305 parent = parentView.mParent; 5306 } 5307 5308 if (parent instanceof ViewRootImpl) { 5309 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 5310 position.offset(0, -viewRootImpl.mCurScrollY); 5311 } 5312 5313 position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 5314 5315 outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f), 5316 (int) (position.right + 0.5f), (int) (position.bottom + 0.5f)); 5317 } 5318 5319 /** 5320 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 5321 * 5322 * Note: Called from the default {@link AccessibilityDelegate}. 5323 */ 5324 void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 5325 Rect bounds = mAttachInfo.mTmpInvalRect; 5326 5327 getDrawingRect(bounds); 5328 info.setBoundsInParent(bounds); 5329 5330 getBoundsOnScreen(bounds); 5331 info.setBoundsInScreen(bounds); 5332 5333 ViewParent parent = getParentForAccessibility(); 5334 if (parent instanceof View) { 5335 info.setParent((View) parent); 5336 } 5337 5338 if (mID != View.NO_ID) { 5339 View rootView = getRootView(); 5340 if (rootView == null) { 5341 rootView = this; 5342 } 5343 View label = rootView.findLabelForView(this, mID); 5344 if (label != null) { 5345 info.setLabeledBy(label); 5346 } 5347 5348 if ((mAttachInfo.mAccessibilityFetchFlags 5349 & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0 5350 && Resources.resourceHasPackage(mID)) { 5351 try { 5352 String viewId = getResources().getResourceName(mID); 5353 info.setViewIdResourceName(viewId); 5354 } catch (Resources.NotFoundException nfe) { 5355 /* ignore */ 5356 } 5357 } 5358 } 5359 5360 if (mLabelForId != View.NO_ID) { 5361 View rootView = getRootView(); 5362 if (rootView == null) { 5363 rootView = this; 5364 } 5365 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId); 5366 if (labeled != null) { 5367 info.setLabelFor(labeled); 5368 } 5369 } 5370 5371 info.setVisibleToUser(isVisibleToUser()); 5372 5373 info.setPackageName(mContext.getPackageName()); 5374 info.setClassName(View.class.getName()); 5375 info.setContentDescription(getContentDescription()); 5376 5377 info.setEnabled(isEnabled()); 5378 info.setClickable(isClickable()); 5379 info.setFocusable(isFocusable()); 5380 info.setFocused(isFocused()); 5381 info.setAccessibilityFocused(isAccessibilityFocused()); 5382 info.setSelected(isSelected()); 5383 info.setLongClickable(isLongClickable()); 5384 5385 // TODO: These make sense only if we are in an AdapterView but all 5386 // views can be selected. Maybe from accessibility perspective 5387 // we should report as selectable view in an AdapterView. 5388 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 5389 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 5390 5391 if (isFocusable()) { 5392 if (isFocused()) { 5393 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 5394 } else { 5395 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 5396 } 5397 } 5398 5399 if (!isAccessibilityFocused()) { 5400 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 5401 } else { 5402 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 5403 } 5404 5405 if (isClickable() && isEnabled()) { 5406 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 5407 } 5408 5409 if (isLongClickable() && isEnabled()) { 5410 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 5411 } 5412 5413 CharSequence text = getIterableTextForAccessibility(); 5414 if (text != null && text.length() > 0) { 5415 info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd()); 5416 5417 info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); 5418 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 5419 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 5420 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 5421 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 5422 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 5423 } 5424 } 5425 5426 private View findLabelForView(View view, int labeledId) { 5427 if (mMatchLabelForPredicate == null) { 5428 mMatchLabelForPredicate = new MatchLabelForPredicate(); 5429 } 5430 mMatchLabelForPredicate.mLabeledId = labeledId; 5431 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 5432 } 5433 5434 /** 5435 * Computes whether this view is visible to the user. Such a view is 5436 * attached, visible, all its predecessors are visible, it is not clipped 5437 * entirely by its predecessors, and has an alpha greater than zero. 5438 * 5439 * @return Whether the view is visible on the screen. 5440 * 5441 * @hide 5442 */ 5443 protected boolean isVisibleToUser() { 5444 return isVisibleToUser(null); 5445 } 5446 5447 /** 5448 * Computes whether the given portion of this view is visible to the user. 5449 * Such a view is attached, visible, all its predecessors are visible, 5450 * has an alpha greater than zero, and the specified portion is not 5451 * clipped entirely by its predecessors. 5452 * 5453 * @param boundInView the portion of the view to test; coordinates should be relative; may be 5454 * <code>null</code>, and the entire view will be tested in this case. 5455 * When <code>true</code> is returned by the function, the actual visible 5456 * region will be stored in this parameter; that is, if boundInView is fully 5457 * contained within the view, no modification will be made, otherwise regions 5458 * outside of the visible area of the view will be clipped. 5459 * 5460 * @return Whether the specified portion of the view is visible on the screen. 5461 * 5462 * @hide 5463 */ 5464 protected boolean isVisibleToUser(Rect boundInView) { 5465 if (mAttachInfo != null) { 5466 // Attached to invisible window means this view is not visible. 5467 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 5468 return false; 5469 } 5470 // An invisible predecessor or one with alpha zero means 5471 // that this view is not visible to the user. 5472 Object current = this; 5473 while (current instanceof View) { 5474 View view = (View) current; 5475 // We have attach info so this view is attached and there is no 5476 // need to check whether we reach to ViewRootImpl on the way up. 5477 if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 || 5478 view.getVisibility() != VISIBLE) { 5479 return false; 5480 } 5481 current = view.mParent; 5482 } 5483 // Check if the view is entirely covered by its predecessors. 5484 Rect visibleRect = mAttachInfo.mTmpInvalRect; 5485 Point offset = mAttachInfo.mPoint; 5486 if (!getGlobalVisibleRect(visibleRect, offset)) { 5487 return false; 5488 } 5489 // Check if the visible portion intersects the rectangle of interest. 5490 if (boundInView != null) { 5491 visibleRect.offset(-offset.x, -offset.y); 5492 return boundInView.intersect(visibleRect); 5493 } 5494 return true; 5495 } 5496 return false; 5497 } 5498 5499 /** 5500 * Returns the delegate for implementing accessibility support via 5501 * composition. For more details see {@link AccessibilityDelegate}. 5502 * 5503 * @return The delegate, or null if none set. 5504 * 5505 * @hide 5506 */ 5507 public AccessibilityDelegate getAccessibilityDelegate() { 5508 return mAccessibilityDelegate; 5509 } 5510 5511 /** 5512 * Sets a delegate for implementing accessibility support via composition as 5513 * opposed to inheritance. The delegate's primary use is for implementing 5514 * backwards compatible widgets. For more details see {@link AccessibilityDelegate}. 5515 * 5516 * @param delegate The delegate instance. 5517 * 5518 * @see AccessibilityDelegate 5519 */ 5520 public void setAccessibilityDelegate(AccessibilityDelegate delegate) { 5521 mAccessibilityDelegate = delegate; 5522 } 5523 5524 /** 5525 * Gets the provider for managing a virtual view hierarchy rooted at this View 5526 * and reported to {@link android.accessibilityservice.AccessibilityService}s 5527 * that explore the window content. 5528 * <p> 5529 * If this method returns an instance, this instance is responsible for managing 5530 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 5531 * View including the one representing the View itself. Similarly the returned 5532 * instance is responsible for performing accessibility actions on any virtual 5533 * view or the root view itself. 5534 * </p> 5535 * <p> 5536 * If an {@link AccessibilityDelegate} has been specified via calling 5537 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5538 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 5539 * is responsible for handling this call. 5540 * </p> 5541 * 5542 * @return The provider. 5543 * 5544 * @see AccessibilityNodeProvider 5545 */ 5546 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 5547 if (mAccessibilityDelegate != null) { 5548 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 5549 } else { 5550 return null; 5551 } 5552 } 5553 5554 /** 5555 * Gets the unique identifier of this view on the screen for accessibility purposes. 5556 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 5557 * 5558 * @return The view accessibility id. 5559 * 5560 * @hide 5561 */ 5562 public int getAccessibilityViewId() { 5563 if (mAccessibilityViewId == NO_ID) { 5564 mAccessibilityViewId = sNextAccessibilityViewId++; 5565 } 5566 return mAccessibilityViewId; 5567 } 5568 5569 /** 5570 * Gets the unique identifier of the window in which this View reseides. 5571 * 5572 * @return The window accessibility id. 5573 * 5574 * @hide 5575 */ 5576 public int getAccessibilityWindowId() { 5577 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID; 5578 } 5579 5580 /** 5581 * Gets the {@link View} description. It briefly describes the view and is 5582 * primarily used for accessibility support. Set this property to enable 5583 * better accessibility support for your application. This is especially 5584 * true for views that do not have textual representation (For example, 5585 * ImageButton). 5586 * 5587 * @return The content description. 5588 * 5589 * @attr ref android.R.styleable#View_contentDescription 5590 */ 5591 @ViewDebug.ExportedProperty(category = "accessibility") 5592 public CharSequence getContentDescription() { 5593 return mContentDescription; 5594 } 5595 5596 /** 5597 * Sets the {@link View} description. It briefly describes the view and is 5598 * primarily used for accessibility support. Set this property to enable 5599 * better accessibility support for your application. This is especially 5600 * true for views that do not have textual representation (For example, 5601 * ImageButton). 5602 * 5603 * @param contentDescription The content description. 5604 * 5605 * @attr ref android.R.styleable#View_contentDescription 5606 */ 5607 @RemotableViewMethod 5608 public void setContentDescription(CharSequence contentDescription) { 5609 if (mContentDescription == null) { 5610 if (contentDescription == null) { 5611 return; 5612 } 5613 } else if (mContentDescription.equals(contentDescription)) { 5614 return; 5615 } 5616 mContentDescription = contentDescription; 5617 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 5618 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 5619 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 5620 notifySubtreeAccessibilityStateChangedIfNeeded(); 5621 } else { 5622 notifyViewAccessibilityStateChangedIfNeeded( 5623 AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION); 5624 } 5625 } 5626 5627 /** 5628 * Gets the id of a view for which this view serves as a label for 5629 * accessibility purposes. 5630 * 5631 * @return The labeled view id. 5632 */ 5633 @ViewDebug.ExportedProperty(category = "accessibility") 5634 public int getLabelFor() { 5635 return mLabelForId; 5636 } 5637 5638 /** 5639 * Sets the id of a view for which this view serves as a label for 5640 * accessibility purposes. 5641 * 5642 * @param id The labeled view id. 5643 */ 5644 @RemotableViewMethod 5645 public void setLabelFor(int id) { 5646 mLabelForId = id; 5647 if (mLabelForId != View.NO_ID 5648 && mID == View.NO_ID) { 5649 mID = generateViewId(); 5650 } 5651 } 5652 5653 /** 5654 * Invoked whenever this view loses focus, either by losing window focus or by losing 5655 * focus within its window. This method can be used to clear any state tied to the 5656 * focus. For instance, if a button is held pressed with the trackball and the window 5657 * loses focus, this method can be used to cancel the press. 5658 * 5659 * Subclasses of View overriding this method should always call super.onFocusLost(). 5660 * 5661 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 5662 * @see #onWindowFocusChanged(boolean) 5663 * 5664 * @hide pending API council approval 5665 */ 5666 protected void onFocusLost() { 5667 resetPressedState(); 5668 } 5669 5670 private void resetPressedState() { 5671 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 5672 return; 5673 } 5674 5675 if (isPressed()) { 5676 setPressed(false); 5677 5678 if (!mHasPerformedLongPress) { 5679 removeLongPressCallback(); 5680 } 5681 } 5682 } 5683 5684 /** 5685 * Returns true if this view has focus 5686 * 5687 * @return True if this view has focus, false otherwise. 5688 */ 5689 @ViewDebug.ExportedProperty(category = "focus") 5690 public boolean isFocused() { 5691 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 5692 } 5693 5694 /** 5695 * Find the view in the hierarchy rooted at this view that currently has 5696 * focus. 5697 * 5698 * @return The view that currently has focus, or null if no focused view can 5699 * be found. 5700 */ 5701 public View findFocus() { 5702 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 5703 } 5704 5705 /** 5706 * Indicates whether this view is one of the set of scrollable containers in 5707 * its window. 5708 * 5709 * @return whether this view is one of the set of scrollable containers in 5710 * its window 5711 * 5712 * @attr ref android.R.styleable#View_isScrollContainer 5713 */ 5714 public boolean isScrollContainer() { 5715 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 5716 } 5717 5718 /** 5719 * Change whether this view is one of the set of scrollable containers in 5720 * its window. This will be used to determine whether the window can 5721 * resize or must pan when a soft input area is open -- scrollable 5722 * containers allow the window to use resize mode since the container 5723 * will appropriately shrink. 5724 * 5725 * @attr ref android.R.styleable#View_isScrollContainer 5726 */ 5727 public void setScrollContainer(boolean isScrollContainer) { 5728 if (isScrollContainer) { 5729 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 5730 mAttachInfo.mScrollContainers.add(this); 5731 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 5732 } 5733 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 5734 } else { 5735 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 5736 mAttachInfo.mScrollContainers.remove(this); 5737 } 5738 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 5739 } 5740 } 5741 5742 /** 5743 * Returns the quality of the drawing cache. 5744 * 5745 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5746 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5747 * 5748 * @see #setDrawingCacheQuality(int) 5749 * @see #setDrawingCacheEnabled(boolean) 5750 * @see #isDrawingCacheEnabled() 5751 * 5752 * @attr ref android.R.styleable#View_drawingCacheQuality 5753 */ 5754 @DrawingCacheQuality 5755 public int getDrawingCacheQuality() { 5756 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 5757 } 5758 5759 /** 5760 * Set the drawing cache quality of this view. This value is used only when the 5761 * drawing cache is enabled 5762 * 5763 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5764 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5765 * 5766 * @see #getDrawingCacheQuality() 5767 * @see #setDrawingCacheEnabled(boolean) 5768 * @see #isDrawingCacheEnabled() 5769 * 5770 * @attr ref android.R.styleable#View_drawingCacheQuality 5771 */ 5772 public void setDrawingCacheQuality(@DrawingCacheQuality int quality) { 5773 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 5774 } 5775 5776 /** 5777 * Returns whether the screen should remain on, corresponding to the current 5778 * value of {@link #KEEP_SCREEN_ON}. 5779 * 5780 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 5781 * 5782 * @see #setKeepScreenOn(boolean) 5783 * 5784 * @attr ref android.R.styleable#View_keepScreenOn 5785 */ 5786 public boolean getKeepScreenOn() { 5787 return (mViewFlags & KEEP_SCREEN_ON) != 0; 5788 } 5789 5790 /** 5791 * Controls whether the screen should remain on, modifying the 5792 * value of {@link #KEEP_SCREEN_ON}. 5793 * 5794 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 5795 * 5796 * @see #getKeepScreenOn() 5797 * 5798 * @attr ref android.R.styleable#View_keepScreenOn 5799 */ 5800 public void setKeepScreenOn(boolean keepScreenOn) { 5801 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 5802 } 5803 5804 /** 5805 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5806 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5807 * 5808 * @attr ref android.R.styleable#View_nextFocusLeft 5809 */ 5810 public int getNextFocusLeftId() { 5811 return mNextFocusLeftId; 5812 } 5813 5814 /** 5815 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5816 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 5817 * decide automatically. 5818 * 5819 * @attr ref android.R.styleable#View_nextFocusLeft 5820 */ 5821 public void setNextFocusLeftId(int nextFocusLeftId) { 5822 mNextFocusLeftId = nextFocusLeftId; 5823 } 5824 5825 /** 5826 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5827 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5828 * 5829 * @attr ref android.R.styleable#View_nextFocusRight 5830 */ 5831 public int getNextFocusRightId() { 5832 return mNextFocusRightId; 5833 } 5834 5835 /** 5836 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5837 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 5838 * decide automatically. 5839 * 5840 * @attr ref android.R.styleable#View_nextFocusRight 5841 */ 5842 public void setNextFocusRightId(int nextFocusRightId) { 5843 mNextFocusRightId = nextFocusRightId; 5844 } 5845 5846 /** 5847 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 5848 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5849 * 5850 * @attr ref android.R.styleable#View_nextFocusUp 5851 */ 5852 public int getNextFocusUpId() { 5853 return mNextFocusUpId; 5854 } 5855 5856 /** 5857 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 5858 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 5859 * decide automatically. 5860 * 5861 * @attr ref android.R.styleable#View_nextFocusUp 5862 */ 5863 public void setNextFocusUpId(int nextFocusUpId) { 5864 mNextFocusUpId = nextFocusUpId; 5865 } 5866 5867 /** 5868 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 5869 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5870 * 5871 * @attr ref android.R.styleable#View_nextFocusDown 5872 */ 5873 public int getNextFocusDownId() { 5874 return mNextFocusDownId; 5875 } 5876 5877 /** 5878 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 5879 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 5880 * decide automatically. 5881 * 5882 * @attr ref android.R.styleable#View_nextFocusDown 5883 */ 5884 public void setNextFocusDownId(int nextFocusDownId) { 5885 mNextFocusDownId = nextFocusDownId; 5886 } 5887 5888 /** 5889 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 5890 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5891 * 5892 * @attr ref android.R.styleable#View_nextFocusForward 5893 */ 5894 public int getNextFocusForwardId() { 5895 return mNextFocusForwardId; 5896 } 5897 5898 /** 5899 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 5900 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 5901 * decide automatically. 5902 * 5903 * @attr ref android.R.styleable#View_nextFocusForward 5904 */ 5905 public void setNextFocusForwardId(int nextFocusForwardId) { 5906 mNextFocusForwardId = nextFocusForwardId; 5907 } 5908 5909 /** 5910 * Returns the visibility of this view and all of its ancestors 5911 * 5912 * @return True if this view and all of its ancestors are {@link #VISIBLE} 5913 */ 5914 public boolean isShown() { 5915 View current = this; 5916 //noinspection ConstantConditions 5917 do { 5918 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 5919 return false; 5920 } 5921 ViewParent parent = current.mParent; 5922 if (parent == null) { 5923 return false; // We are not attached to the view root 5924 } 5925 if (!(parent instanceof View)) { 5926 return true; 5927 } 5928 current = (View) parent; 5929 } while (current != null); 5930 5931 return false; 5932 } 5933 5934 /** 5935 * Called by the view hierarchy when the content insets for a window have 5936 * changed, to allow it to adjust its content to fit within those windows. 5937 * The content insets tell you the space that the status bar, input method, 5938 * and other system windows infringe on the application's window. 5939 * 5940 * <p>You do not normally need to deal with this function, since the default 5941 * window decoration given to applications takes care of applying it to the 5942 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 5943 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 5944 * and your content can be placed under those system elements. You can then 5945 * use this method within your view hierarchy if you have parts of your UI 5946 * which you would like to ensure are not being covered. 5947 * 5948 * <p>The default implementation of this method simply applies the content 5949 * insets to the view's padding, consuming that content (modifying the 5950 * insets to be 0), and returning true. This behavior is off by default, but can 5951 * be enabled through {@link #setFitsSystemWindows(boolean)}. 5952 * 5953 * <p>This function's traversal down the hierarchy is depth-first. The same content 5954 * insets object is propagated down the hierarchy, so any changes made to it will 5955 * be seen by all following views (including potentially ones above in 5956 * the hierarchy since this is a depth-first traversal). The first view 5957 * that returns true will abort the entire traversal. 5958 * 5959 * <p>The default implementation works well for a situation where it is 5960 * used with a container that covers the entire window, allowing it to 5961 * apply the appropriate insets to its content on all edges. If you need 5962 * a more complicated layout (such as two different views fitting system 5963 * windows, one on the top of the window, and one on the bottom), 5964 * you can override the method and handle the insets however you would like. 5965 * Note that the insets provided by the framework are always relative to the 5966 * far edges of the window, not accounting for the location of the called view 5967 * within that window. (In fact when this method is called you do not yet know 5968 * where the layout will place the view, as it is done before layout happens.) 5969 * 5970 * <p>Note: unlike many View methods, there is no dispatch phase to this 5971 * call. If you are overriding it in a ViewGroup and want to allow the 5972 * call to continue to your children, you must be sure to call the super 5973 * implementation. 5974 * 5975 * <p>Here is a sample layout that makes use of fitting system windows 5976 * to have controls for a video view placed inside of the window decorations 5977 * that it hides and shows. This can be used with code like the second 5978 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 5979 * 5980 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 5981 * 5982 * @param insets Current content insets of the window. Prior to 5983 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 5984 * the insets or else you and Android will be unhappy. 5985 * 5986 * @return {@code true} if this view applied the insets and it should not 5987 * continue propagating further down the hierarchy, {@code false} otherwise. 5988 * @see #getFitsSystemWindows() 5989 * @see #setFitsSystemWindows(boolean) 5990 * @see #setSystemUiVisibility(int) 5991 */ 5992 protected boolean fitSystemWindows(Rect insets) { 5993 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 5994 mUserPaddingStart = UNDEFINED_PADDING; 5995 mUserPaddingEnd = UNDEFINED_PADDING; 5996 Rect localInsets = sThreadLocal.get(); 5997 if (localInsets == null) { 5998 localInsets = new Rect(); 5999 sThreadLocal.set(localInsets); 6000 } 6001 boolean res = computeFitSystemWindows(insets, localInsets); 6002 internalSetPadding(localInsets.left, localInsets.top, 6003 localInsets.right, localInsets.bottom); 6004 return res; 6005 } 6006 return false; 6007 } 6008 6009 /** 6010 * @hide Compute the insets that should be consumed by this view and the ones 6011 * that should propagate to those under it. 6012 */ 6013 protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) { 6014 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 6015 || mAttachInfo == null 6016 || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0 6017 && !mAttachInfo.mOverscanRequested)) { 6018 outLocalInsets.set(inoutInsets); 6019 inoutInsets.set(0, 0, 0, 0); 6020 return true; 6021 } else { 6022 // The application wants to take care of fitting system window for 6023 // the content... however we still need to take care of any overscan here. 6024 final Rect overscan = mAttachInfo.mOverscanInsets; 6025 outLocalInsets.set(overscan); 6026 inoutInsets.left -= overscan.left; 6027 inoutInsets.top -= overscan.top; 6028 inoutInsets.right -= overscan.right; 6029 inoutInsets.bottom -= overscan.bottom; 6030 return false; 6031 } 6032 } 6033 6034 /** 6035 * Sets whether or not this view should account for system screen decorations 6036 * such as the status bar and inset its content; that is, controlling whether 6037 * the default implementation of {@link #fitSystemWindows(Rect)} will be 6038 * executed. See that method for more details. 6039 * 6040 * <p>Note that if you are providing your own implementation of 6041 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 6042 * flag to true -- your implementation will be overriding the default 6043 * implementation that checks this flag. 6044 * 6045 * @param fitSystemWindows If true, then the default implementation of 6046 * {@link #fitSystemWindows(Rect)} will be executed. 6047 * 6048 * @attr ref android.R.styleable#View_fitsSystemWindows 6049 * @see #getFitsSystemWindows() 6050 * @see #fitSystemWindows(Rect) 6051 * @see #setSystemUiVisibility(int) 6052 */ 6053 public void setFitsSystemWindows(boolean fitSystemWindows) { 6054 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 6055 } 6056 6057 /** 6058 * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method 6059 * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)} 6060 * will be executed. 6061 * 6062 * @return {@code true} if the default implementation of 6063 * {@link #fitSystemWindows(Rect)} will be executed. 6064 * 6065 * @attr ref android.R.styleable#View_fitsSystemWindows 6066 * @see #setFitsSystemWindows(boolean) 6067 * @see #fitSystemWindows(Rect) 6068 * @see #setSystemUiVisibility(int) 6069 */ 6070 public boolean getFitsSystemWindows() { 6071 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 6072 } 6073 6074 /** @hide */ 6075 public boolean fitsSystemWindows() { 6076 return getFitsSystemWindows(); 6077 } 6078 6079 /** 6080 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 6081 */ 6082 public void requestFitSystemWindows() { 6083 if (mParent != null) { 6084 mParent.requestFitSystemWindows(); 6085 } 6086 } 6087 6088 /** 6089 * For use by PhoneWindow to make its own system window fitting optional. 6090 * @hide 6091 */ 6092 public void makeOptionalFitsSystemWindows() { 6093 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 6094 } 6095 6096 /** 6097 * Returns the visibility status for this view. 6098 * 6099 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6100 * @attr ref android.R.styleable#View_visibility 6101 */ 6102 @ViewDebug.ExportedProperty(mapping = { 6103 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 6104 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 6105 @ViewDebug.IntToString(from = GONE, to = "GONE") 6106 }) 6107 @Visibility 6108 public int getVisibility() { 6109 return mViewFlags & VISIBILITY_MASK; 6110 } 6111 6112 /** 6113 * Set the enabled state of this view. 6114 * 6115 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6116 * @attr ref android.R.styleable#View_visibility 6117 */ 6118 @RemotableViewMethod 6119 public void setVisibility(@Visibility int visibility) { 6120 setFlags(visibility, VISIBILITY_MASK); 6121 if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false); 6122 } 6123 6124 /** 6125 * Returns the enabled status for this view. The interpretation of the 6126 * enabled state varies by subclass. 6127 * 6128 * @return True if this view is enabled, false otherwise. 6129 */ 6130 @ViewDebug.ExportedProperty 6131 public boolean isEnabled() { 6132 return (mViewFlags & ENABLED_MASK) == ENABLED; 6133 } 6134 6135 /** 6136 * Set the enabled state of this view. The interpretation of the enabled 6137 * state varies by subclass. 6138 * 6139 * @param enabled True if this view is enabled, false otherwise. 6140 */ 6141 @RemotableViewMethod 6142 public void setEnabled(boolean enabled) { 6143 if (enabled == isEnabled()) return; 6144 6145 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 6146 6147 /* 6148 * The View most likely has to change its appearance, so refresh 6149 * the drawable state. 6150 */ 6151 refreshDrawableState(); 6152 6153 // Invalidate too, since the default behavior for views is to be 6154 // be drawn at 50% alpha rather than to change the drawable. 6155 invalidate(true); 6156 6157 if (!enabled) { 6158 cancelPendingInputEvents(); 6159 } 6160 } 6161 6162 /** 6163 * Set whether this view can receive the focus. 6164 * 6165 * Setting this to false will also ensure that this view is not focusable 6166 * in touch mode. 6167 * 6168 * @param focusable If true, this view can receive the focus. 6169 * 6170 * @see #setFocusableInTouchMode(boolean) 6171 * @attr ref android.R.styleable#View_focusable 6172 */ 6173 public void setFocusable(boolean focusable) { 6174 if (!focusable) { 6175 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 6176 } 6177 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 6178 } 6179 6180 /** 6181 * Set whether this view can receive focus while in touch mode. 6182 * 6183 * Setting this to true will also ensure that this view is focusable. 6184 * 6185 * @param focusableInTouchMode If true, this view can receive the focus while 6186 * in touch mode. 6187 * 6188 * @see #setFocusable(boolean) 6189 * @attr ref android.R.styleable#View_focusableInTouchMode 6190 */ 6191 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 6192 // Focusable in touch mode should always be set before the focusable flag 6193 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 6194 // which, in touch mode, will not successfully request focus on this view 6195 // because the focusable in touch mode flag is not set 6196 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 6197 if (focusableInTouchMode) { 6198 setFlags(FOCUSABLE, FOCUSABLE_MASK); 6199 } 6200 } 6201 6202 /** 6203 * Set whether this view should have sound effects enabled for events such as 6204 * clicking and touching. 6205 * 6206 * <p>You may wish to disable sound effects for a view if you already play sounds, 6207 * for instance, a dial key that plays dtmf tones. 6208 * 6209 * @param soundEffectsEnabled whether sound effects are enabled for this view. 6210 * @see #isSoundEffectsEnabled() 6211 * @see #playSoundEffect(int) 6212 * @attr ref android.R.styleable#View_soundEffectsEnabled 6213 */ 6214 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 6215 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 6216 } 6217 6218 /** 6219 * @return whether this view should have sound effects enabled for events such as 6220 * clicking and touching. 6221 * 6222 * @see #setSoundEffectsEnabled(boolean) 6223 * @see #playSoundEffect(int) 6224 * @attr ref android.R.styleable#View_soundEffectsEnabled 6225 */ 6226 @ViewDebug.ExportedProperty 6227 public boolean isSoundEffectsEnabled() { 6228 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 6229 } 6230 6231 /** 6232 * Set whether this view should have haptic feedback for events such as 6233 * long presses. 6234 * 6235 * <p>You may wish to disable haptic feedback if your view already controls 6236 * its own haptic feedback. 6237 * 6238 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 6239 * @see #isHapticFeedbackEnabled() 6240 * @see #performHapticFeedback(int) 6241 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6242 */ 6243 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 6244 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 6245 } 6246 6247 /** 6248 * @return whether this view should have haptic feedback enabled for events 6249 * long presses. 6250 * 6251 * @see #setHapticFeedbackEnabled(boolean) 6252 * @see #performHapticFeedback(int) 6253 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6254 */ 6255 @ViewDebug.ExportedProperty 6256 public boolean isHapticFeedbackEnabled() { 6257 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 6258 } 6259 6260 /** 6261 * Returns the layout direction for this view. 6262 * 6263 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 6264 * {@link #LAYOUT_DIRECTION_RTL}, 6265 * {@link #LAYOUT_DIRECTION_INHERIT} or 6266 * {@link #LAYOUT_DIRECTION_LOCALE}. 6267 * 6268 * @attr ref android.R.styleable#View_layoutDirection 6269 * 6270 * @hide 6271 */ 6272 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6273 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 6274 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 6275 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 6276 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 6277 }) 6278 @LayoutDir 6279 public int getRawLayoutDirection() { 6280 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 6281 } 6282 6283 /** 6284 * Set the layout direction for this view. This will propagate a reset of layout direction 6285 * resolution to the view's children and resolve layout direction for this view. 6286 * 6287 * @param layoutDirection the layout direction to set. Should be one of: 6288 * 6289 * {@link #LAYOUT_DIRECTION_LTR}, 6290 * {@link #LAYOUT_DIRECTION_RTL}, 6291 * {@link #LAYOUT_DIRECTION_INHERIT}, 6292 * {@link #LAYOUT_DIRECTION_LOCALE}. 6293 * 6294 * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution 6295 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 6296 * will return the default {@link #LAYOUT_DIRECTION_LTR}. 6297 * 6298 * @attr ref android.R.styleable#View_layoutDirection 6299 */ 6300 @RemotableViewMethod 6301 public void setLayoutDirection(@LayoutDir int layoutDirection) { 6302 if (getRawLayoutDirection() != layoutDirection) { 6303 // Reset the current layout direction and the resolved one 6304 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 6305 resetRtlProperties(); 6306 // Set the new layout direction (filtered) 6307 mPrivateFlags2 |= 6308 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 6309 // We need to resolve all RTL properties as they all depend on layout direction 6310 resolveRtlPropertiesIfNeeded(); 6311 requestLayout(); 6312 invalidate(true); 6313 } 6314 } 6315 6316 /** 6317 * Returns the resolved layout direction for this view. 6318 * 6319 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 6320 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 6321 * 6322 * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version 6323 * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}. 6324 * 6325 * @attr ref android.R.styleable#View_layoutDirection 6326 */ 6327 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6328 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 6329 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 6330 }) 6331 @ResolvedLayoutDir 6332 public int getLayoutDirection() { 6333 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 6334 if (targetSdkVersion < JELLY_BEAN_MR1) { 6335 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 6336 return LAYOUT_DIRECTION_RESOLVED_DEFAULT; 6337 } 6338 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == 6339 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 6340 } 6341 6342 /** 6343 * Indicates whether or not this view's layout is right-to-left. This is resolved from 6344 * layout attribute and/or the inherited value from the parent 6345 * 6346 * @return true if the layout is right-to-left. 6347 * 6348 * @hide 6349 */ 6350 @ViewDebug.ExportedProperty(category = "layout") 6351 public boolean isLayoutRtl() { 6352 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 6353 } 6354 6355 /** 6356 * Indicates whether the view is currently tracking transient state that the 6357 * app should not need to concern itself with saving and restoring, but that 6358 * the framework should take special note to preserve when possible. 6359 * 6360 * <p>A view with transient state cannot be trivially rebound from an external 6361 * data source, such as an adapter binding item views in a list. This may be 6362 * because the view is performing an animation, tracking user selection 6363 * of content, or similar.</p> 6364 * 6365 * @return true if the view has transient state 6366 */ 6367 @ViewDebug.ExportedProperty(category = "layout") 6368 public boolean hasTransientState() { 6369 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 6370 } 6371 6372 /** 6373 * Set whether this view is currently tracking transient state that the 6374 * framework should attempt to preserve when possible. This flag is reference counted, 6375 * so every call to setHasTransientState(true) should be paired with a later call 6376 * to setHasTransientState(false). 6377 * 6378 * <p>A view with transient state cannot be trivially rebound from an external 6379 * data source, such as an adapter binding item views in a list. This may be 6380 * because the view is performing an animation, tracking user selection 6381 * of content, or similar.</p> 6382 * 6383 * @param hasTransientState true if this view has transient state 6384 */ 6385 public void setHasTransientState(boolean hasTransientState) { 6386 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 6387 mTransientStateCount - 1; 6388 if (mTransientStateCount < 0) { 6389 mTransientStateCount = 0; 6390 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 6391 "unmatched pair of setHasTransientState calls"); 6392 } else if ((hasTransientState && mTransientStateCount == 1) || 6393 (!hasTransientState && mTransientStateCount == 0)) { 6394 // update flag if we've just incremented up from 0 or decremented down to 0 6395 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 6396 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 6397 if (mParent != null) { 6398 try { 6399 mParent.childHasTransientStateChanged(this, hasTransientState); 6400 } catch (AbstractMethodError e) { 6401 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 6402 " does not fully implement ViewParent", e); 6403 } 6404 } 6405 } 6406 } 6407 6408 /** 6409 * Returns true if this view is currently attached to a window. 6410 */ 6411 public boolean isAttachedToWindow() { 6412 return mAttachInfo != null; 6413 } 6414 6415 /** 6416 * Returns true if this view has been through at least one layout since it 6417 * was last attached to or detached from a window. 6418 */ 6419 public boolean isLaidOut() { 6420 return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT; 6421 } 6422 6423 /** 6424 * If this view doesn't do any drawing on its own, set this flag to 6425 * allow further optimizations. By default, this flag is not set on 6426 * View, but could be set on some View subclasses such as ViewGroup. 6427 * 6428 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 6429 * you should clear this flag. 6430 * 6431 * @param willNotDraw whether or not this View draw on its own 6432 */ 6433 public void setWillNotDraw(boolean willNotDraw) { 6434 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 6435 } 6436 6437 /** 6438 * Returns whether or not this View draws on its own. 6439 * 6440 * @return true if this view has nothing to draw, false otherwise 6441 */ 6442 @ViewDebug.ExportedProperty(category = "drawing") 6443 public boolean willNotDraw() { 6444 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 6445 } 6446 6447 /** 6448 * When a View's drawing cache is enabled, drawing is redirected to an 6449 * offscreen bitmap. Some views, like an ImageView, must be able to 6450 * bypass this mechanism if they already draw a single bitmap, to avoid 6451 * unnecessary usage of the memory. 6452 * 6453 * @param willNotCacheDrawing true if this view does not cache its 6454 * drawing, false otherwise 6455 */ 6456 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 6457 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 6458 } 6459 6460 /** 6461 * Returns whether or not this View can cache its drawing or not. 6462 * 6463 * @return true if this view does not cache its drawing, false otherwise 6464 */ 6465 @ViewDebug.ExportedProperty(category = "drawing") 6466 public boolean willNotCacheDrawing() { 6467 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 6468 } 6469 6470 /** 6471 * Indicates whether this view reacts to click events or not. 6472 * 6473 * @return true if the view is clickable, false otherwise 6474 * 6475 * @see #setClickable(boolean) 6476 * @attr ref android.R.styleable#View_clickable 6477 */ 6478 @ViewDebug.ExportedProperty 6479 public boolean isClickable() { 6480 return (mViewFlags & CLICKABLE) == CLICKABLE; 6481 } 6482 6483 /** 6484 * Enables or disables click events for this view. When a view 6485 * is clickable it will change its state to "pressed" on every click. 6486 * Subclasses should set the view clickable to visually react to 6487 * user's clicks. 6488 * 6489 * @param clickable true to make the view clickable, false otherwise 6490 * 6491 * @see #isClickable() 6492 * @attr ref android.R.styleable#View_clickable 6493 */ 6494 public void setClickable(boolean clickable) { 6495 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 6496 } 6497 6498 /** 6499 * Indicates whether this view reacts to long click events or not. 6500 * 6501 * @return true if the view is long clickable, false otherwise 6502 * 6503 * @see #setLongClickable(boolean) 6504 * @attr ref android.R.styleable#View_longClickable 6505 */ 6506 public boolean isLongClickable() { 6507 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 6508 } 6509 6510 /** 6511 * Enables or disables long click events for this view. When a view is long 6512 * clickable it reacts to the user holding down the button for a longer 6513 * duration than a tap. This event can either launch the listener or a 6514 * context menu. 6515 * 6516 * @param longClickable true to make the view long clickable, false otherwise 6517 * @see #isLongClickable() 6518 * @attr ref android.R.styleable#View_longClickable 6519 */ 6520 public void setLongClickable(boolean longClickable) { 6521 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 6522 } 6523 6524 /** 6525 * Sets the pressed state for this view. 6526 * 6527 * @see #isClickable() 6528 * @see #setClickable(boolean) 6529 * 6530 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 6531 * the View's internal state from a previously set "pressed" state. 6532 */ 6533 public void setPressed(boolean pressed) { 6534 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 6535 6536 if (pressed) { 6537 mPrivateFlags |= PFLAG_PRESSED; 6538 } else { 6539 mPrivateFlags &= ~PFLAG_PRESSED; 6540 } 6541 6542 if (needsRefresh) { 6543 refreshDrawableState(); 6544 } 6545 dispatchSetPressed(pressed); 6546 } 6547 6548 /** 6549 * Dispatch setPressed to all of this View's children. 6550 * 6551 * @see #setPressed(boolean) 6552 * 6553 * @param pressed The new pressed state 6554 */ 6555 protected void dispatchSetPressed(boolean pressed) { 6556 } 6557 6558 /** 6559 * Indicates whether the view is currently in pressed state. Unless 6560 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 6561 * the pressed state. 6562 * 6563 * @see #setPressed(boolean) 6564 * @see #isClickable() 6565 * @see #setClickable(boolean) 6566 * 6567 * @return true if the view is currently pressed, false otherwise 6568 */ 6569 public boolean isPressed() { 6570 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 6571 } 6572 6573 /** 6574 * Indicates whether this view will save its state (that is, 6575 * whether its {@link #onSaveInstanceState} method will be called). 6576 * 6577 * @return Returns true if the view state saving is enabled, else false. 6578 * 6579 * @see #setSaveEnabled(boolean) 6580 * @attr ref android.R.styleable#View_saveEnabled 6581 */ 6582 public boolean isSaveEnabled() { 6583 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 6584 } 6585 6586 /** 6587 * Controls whether the saving of this view's state is 6588 * enabled (that is, whether its {@link #onSaveInstanceState} method 6589 * will be called). Note that even if freezing is enabled, the 6590 * view still must have an id assigned to it (via {@link #setId(int)}) 6591 * for its state to be saved. This flag can only disable the 6592 * saving of this view; any child views may still have their state saved. 6593 * 6594 * @param enabled Set to false to <em>disable</em> state saving, or true 6595 * (the default) to allow it. 6596 * 6597 * @see #isSaveEnabled() 6598 * @see #setId(int) 6599 * @see #onSaveInstanceState() 6600 * @attr ref android.R.styleable#View_saveEnabled 6601 */ 6602 public void setSaveEnabled(boolean enabled) { 6603 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 6604 } 6605 6606 /** 6607 * Gets whether the framework should discard touches when the view's 6608 * window is obscured by another visible window. 6609 * Refer to the {@link View} security documentation for more details. 6610 * 6611 * @return True if touch filtering is enabled. 6612 * 6613 * @see #setFilterTouchesWhenObscured(boolean) 6614 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6615 */ 6616 @ViewDebug.ExportedProperty 6617 public boolean getFilterTouchesWhenObscured() { 6618 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 6619 } 6620 6621 /** 6622 * Sets whether the framework should discard touches when the view's 6623 * window is obscured by another visible window. 6624 * Refer to the {@link View} security documentation for more details. 6625 * 6626 * @param enabled True if touch filtering should be enabled. 6627 * 6628 * @see #getFilterTouchesWhenObscured 6629 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6630 */ 6631 public void setFilterTouchesWhenObscured(boolean enabled) { 6632 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED, 6633 FILTER_TOUCHES_WHEN_OBSCURED); 6634 } 6635 6636 /** 6637 * Indicates whether the entire hierarchy under this view will save its 6638 * state when a state saving traversal occurs from its parent. The default 6639 * is true; if false, these views will not be saved unless 6640 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6641 * 6642 * @return Returns true if the view state saving from parent is enabled, else false. 6643 * 6644 * @see #setSaveFromParentEnabled(boolean) 6645 */ 6646 public boolean isSaveFromParentEnabled() { 6647 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 6648 } 6649 6650 /** 6651 * Controls whether the entire hierarchy under this view will save its 6652 * state when a state saving traversal occurs from its parent. The default 6653 * is true; if false, these views will not be saved unless 6654 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6655 * 6656 * @param enabled Set to false to <em>disable</em> state saving, or true 6657 * (the default) to allow it. 6658 * 6659 * @see #isSaveFromParentEnabled() 6660 * @see #setId(int) 6661 * @see #onSaveInstanceState() 6662 */ 6663 public void setSaveFromParentEnabled(boolean enabled) { 6664 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 6665 } 6666 6667 6668 /** 6669 * Returns whether this View is able to take focus. 6670 * 6671 * @return True if this view can take focus, or false otherwise. 6672 * @attr ref android.R.styleable#View_focusable 6673 */ 6674 @ViewDebug.ExportedProperty(category = "focus") 6675 public final boolean isFocusable() { 6676 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 6677 } 6678 6679 /** 6680 * When a view is focusable, it may not want to take focus when in touch mode. 6681 * For example, a button would like focus when the user is navigating via a D-pad 6682 * so that the user can click on it, but once the user starts touching the screen, 6683 * the button shouldn't take focus 6684 * @return Whether the view is focusable in touch mode. 6685 * @attr ref android.R.styleable#View_focusableInTouchMode 6686 */ 6687 @ViewDebug.ExportedProperty 6688 public final boolean isFocusableInTouchMode() { 6689 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 6690 } 6691 6692 /** 6693 * Find the nearest view in the specified direction that can take focus. 6694 * This does not actually give focus to that view. 6695 * 6696 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 6697 * 6698 * @return The nearest focusable in the specified direction, or null if none 6699 * can be found. 6700 */ 6701 public View focusSearch(@FocusRealDirection int direction) { 6702 if (mParent != null) { 6703 return mParent.focusSearch(this, direction); 6704 } else { 6705 return null; 6706 } 6707 } 6708 6709 /** 6710 * This method is the last chance for the focused view and its ancestors to 6711 * respond to an arrow key. This is called when the focused view did not 6712 * consume the key internally, nor could the view system find a new view in 6713 * the requested direction to give focus to. 6714 * 6715 * @param focused The currently focused view. 6716 * @param direction The direction focus wants to move. One of FOCUS_UP, 6717 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 6718 * @return True if the this view consumed this unhandled move. 6719 */ 6720 public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) { 6721 return false; 6722 } 6723 6724 /** 6725 * If a user manually specified the next view id for a particular direction, 6726 * use the root to look up the view. 6727 * @param root The root view of the hierarchy containing this view. 6728 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 6729 * or FOCUS_BACKWARD. 6730 * @return The user specified next view, or null if there is none. 6731 */ 6732 View findUserSetNextFocus(View root, @FocusDirection int direction) { 6733 switch (direction) { 6734 case FOCUS_LEFT: 6735 if (mNextFocusLeftId == View.NO_ID) return null; 6736 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 6737 case FOCUS_RIGHT: 6738 if (mNextFocusRightId == View.NO_ID) return null; 6739 return findViewInsideOutShouldExist(root, mNextFocusRightId); 6740 case FOCUS_UP: 6741 if (mNextFocusUpId == View.NO_ID) return null; 6742 return findViewInsideOutShouldExist(root, mNextFocusUpId); 6743 case FOCUS_DOWN: 6744 if (mNextFocusDownId == View.NO_ID) return null; 6745 return findViewInsideOutShouldExist(root, mNextFocusDownId); 6746 case FOCUS_FORWARD: 6747 if (mNextFocusForwardId == View.NO_ID) return null; 6748 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 6749 case FOCUS_BACKWARD: { 6750 if (mID == View.NO_ID) return null; 6751 final int id = mID; 6752 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 6753 @Override 6754 public boolean apply(View t) { 6755 return t.mNextFocusForwardId == id; 6756 } 6757 }); 6758 } 6759 } 6760 return null; 6761 } 6762 6763 private View findViewInsideOutShouldExist(View root, int id) { 6764 if (mMatchIdPredicate == null) { 6765 mMatchIdPredicate = new MatchIdPredicate(); 6766 } 6767 mMatchIdPredicate.mId = id; 6768 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 6769 if (result == null) { 6770 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 6771 } 6772 return result; 6773 } 6774 6775 /** 6776 * Find and return all focusable views that are descendants of this view, 6777 * possibly including this view if it is focusable itself. 6778 * 6779 * @param direction The direction of the focus 6780 * @return A list of focusable views 6781 */ 6782 public ArrayList<View> getFocusables(@FocusDirection int direction) { 6783 ArrayList<View> result = new ArrayList<View>(24); 6784 addFocusables(result, direction); 6785 return result; 6786 } 6787 6788 /** 6789 * Add any focusable views that are descendants of this view (possibly 6790 * including this view if it is focusable itself) to views. If we are in touch mode, 6791 * only add views that are also focusable in touch mode. 6792 * 6793 * @param views Focusable views found so far 6794 * @param direction The direction of the focus 6795 */ 6796 public void addFocusables(ArrayList<View> views, @FocusDirection int direction) { 6797 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 6798 } 6799 6800 /** 6801 * Adds any focusable views that are descendants of this view (possibly 6802 * including this view if it is focusable itself) to views. This method 6803 * adds all focusable views regardless if we are in touch mode or 6804 * only views focusable in touch mode if we are in touch mode or 6805 * only views that can take accessibility focus if accessibility is enabeld 6806 * depending on the focusable mode paramater. 6807 * 6808 * @param views Focusable views found so far or null if all we are interested is 6809 * the number of focusables. 6810 * @param direction The direction of the focus. 6811 * @param focusableMode The type of focusables to be added. 6812 * 6813 * @see #FOCUSABLES_ALL 6814 * @see #FOCUSABLES_TOUCH_MODE 6815 */ 6816 public void addFocusables(ArrayList<View> views, @FocusDirection int direction, 6817 @FocusableMode int focusableMode) { 6818 if (views == null) { 6819 return; 6820 } 6821 if (!isFocusable()) { 6822 return; 6823 } 6824 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 6825 && isInTouchMode() && !isFocusableInTouchMode()) { 6826 return; 6827 } 6828 views.add(this); 6829 } 6830 6831 /** 6832 * Finds the Views that contain given text. The containment is case insensitive. 6833 * The search is performed by either the text that the View renders or the content 6834 * description that describes the view for accessibility purposes and the view does 6835 * not render or both. Clients can specify how the search is to be performed via 6836 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 6837 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 6838 * 6839 * @param outViews The output list of matching Views. 6840 * @param searched The text to match against. 6841 * 6842 * @see #FIND_VIEWS_WITH_TEXT 6843 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 6844 * @see #setContentDescription(CharSequence) 6845 */ 6846 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, 6847 @FindViewFlags int flags) { 6848 if (getAccessibilityNodeProvider() != null) { 6849 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 6850 outViews.add(this); 6851 } 6852 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 6853 && (searched != null && searched.length() > 0) 6854 && (mContentDescription != null && mContentDescription.length() > 0)) { 6855 String searchedLowerCase = searched.toString().toLowerCase(); 6856 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 6857 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 6858 outViews.add(this); 6859 } 6860 } 6861 } 6862 6863 /** 6864 * Find and return all touchable views that are descendants of this view, 6865 * possibly including this view if it is touchable itself. 6866 * 6867 * @return A list of touchable views 6868 */ 6869 public ArrayList<View> getTouchables() { 6870 ArrayList<View> result = new ArrayList<View>(); 6871 addTouchables(result); 6872 return result; 6873 } 6874 6875 /** 6876 * Add any touchable views that are descendants of this view (possibly 6877 * including this view if it is touchable itself) to views. 6878 * 6879 * @param views Touchable views found so far 6880 */ 6881 public void addTouchables(ArrayList<View> views) { 6882 final int viewFlags = mViewFlags; 6883 6884 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 6885 && (viewFlags & ENABLED_MASK) == ENABLED) { 6886 views.add(this); 6887 } 6888 } 6889 6890 /** 6891 * Returns whether this View is accessibility focused. 6892 * 6893 * @return True if this View is accessibility focused. 6894 * @hide 6895 */ 6896 public boolean isAccessibilityFocused() { 6897 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 6898 } 6899 6900 /** 6901 * Call this to try to give accessibility focus to this view. 6902 * 6903 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 6904 * returns false or the view is no visible or the view already has accessibility 6905 * focus. 6906 * 6907 * See also {@link #focusSearch(int)}, which is what you call to say that you 6908 * have focus, and you want your parent to look for the next one. 6909 * 6910 * @return Whether this view actually took accessibility focus. 6911 * 6912 * @hide 6913 */ 6914 public boolean requestAccessibilityFocus() { 6915 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 6916 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 6917 return false; 6918 } 6919 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 6920 return false; 6921 } 6922 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 6923 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 6924 ViewRootImpl viewRootImpl = getViewRootImpl(); 6925 if (viewRootImpl != null) { 6926 viewRootImpl.setAccessibilityFocus(this, null); 6927 } 6928 invalidate(); 6929 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 6930 return true; 6931 } 6932 return false; 6933 } 6934 6935 /** 6936 * Call this to try to clear accessibility focus of this view. 6937 * 6938 * See also {@link #focusSearch(int)}, which is what you call to say that you 6939 * have focus, and you want your parent to look for the next one. 6940 * 6941 * @hide 6942 */ 6943 public void clearAccessibilityFocus() { 6944 clearAccessibilityFocusNoCallbacks(); 6945 // Clear the global reference of accessibility focus if this 6946 // view or any of its descendants had accessibility focus. 6947 ViewRootImpl viewRootImpl = getViewRootImpl(); 6948 if (viewRootImpl != null) { 6949 View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 6950 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 6951 viewRootImpl.setAccessibilityFocus(null, null); 6952 } 6953 } 6954 } 6955 6956 private void sendAccessibilityHoverEvent(int eventType) { 6957 // Since we are not delivering to a client accessibility events from not 6958 // important views (unless the clinet request that) we need to fire the 6959 // event from the deepest view exposed to the client. As a consequence if 6960 // the user crosses a not exposed view the client will see enter and exit 6961 // of the exposed predecessor followed by and enter and exit of that same 6962 // predecessor when entering and exiting the not exposed descendant. This 6963 // is fine since the client has a clear idea which view is hovered at the 6964 // price of a couple more events being sent. This is a simple and 6965 // working solution. 6966 View source = this; 6967 while (true) { 6968 if (source.includeForAccessibility()) { 6969 source.sendAccessibilityEvent(eventType); 6970 return; 6971 } 6972 ViewParent parent = source.getParent(); 6973 if (parent instanceof View) { 6974 source = (View) parent; 6975 } else { 6976 return; 6977 } 6978 } 6979 } 6980 6981 /** 6982 * Clears accessibility focus without calling any callback methods 6983 * normally invoked in {@link #clearAccessibilityFocus()}. This method 6984 * is used for clearing accessibility focus when giving this focus to 6985 * another view. 6986 */ 6987 void clearAccessibilityFocusNoCallbacks() { 6988 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 6989 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 6990 invalidate(); 6991 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 6992 } 6993 } 6994 6995 /** 6996 * Call this to try to give focus to a specific view or to one of its 6997 * descendants. 6998 * 6999 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7000 * false), or if it is focusable and it is not focusable in touch mode 7001 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7002 * 7003 * See also {@link #focusSearch(int)}, which is what you call to say that you 7004 * have focus, and you want your parent to look for the next one. 7005 * 7006 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 7007 * {@link #FOCUS_DOWN} and <code>null</code>. 7008 * 7009 * @return Whether this view or one of its descendants actually took focus. 7010 */ 7011 public final boolean requestFocus() { 7012 return requestFocus(View.FOCUS_DOWN); 7013 } 7014 7015 /** 7016 * Call this to try to give focus to a specific view or to one of its 7017 * descendants and give it a hint about what direction focus is heading. 7018 * 7019 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7020 * false), or if it is focusable and it is not focusable in touch mode 7021 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7022 * 7023 * See also {@link #focusSearch(int)}, which is what you call to say that you 7024 * have focus, and you want your parent to look for the next one. 7025 * 7026 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 7027 * <code>null</code> set for the previously focused rectangle. 7028 * 7029 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7030 * @return Whether this view or one of its descendants actually took focus. 7031 */ 7032 public final boolean requestFocus(int direction) { 7033 return requestFocus(direction, null); 7034 } 7035 7036 /** 7037 * Call this to try to give focus to a specific view or to one of its descendants 7038 * and give it hints about the direction and a specific rectangle that the focus 7039 * is coming from. The rectangle can help give larger views a finer grained hint 7040 * about where focus is coming from, and therefore, where to show selection, or 7041 * forward focus change internally. 7042 * 7043 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7044 * false), or if it is focusable and it is not focusable in touch mode 7045 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7046 * 7047 * A View will not take focus if it is not visible. 7048 * 7049 * A View will not take focus if one of its parents has 7050 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 7051 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 7052 * 7053 * See also {@link #focusSearch(int)}, which is what you call to say that you 7054 * have focus, and you want your parent to look for the next one. 7055 * 7056 * You may wish to override this method if your custom {@link View} has an internal 7057 * {@link View} that it wishes to forward the request to. 7058 * 7059 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7060 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 7061 * to give a finer grained hint about where focus is coming from. May be null 7062 * if there is no hint. 7063 * @return Whether this view or one of its descendants actually took focus. 7064 */ 7065 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 7066 return requestFocusNoSearch(direction, previouslyFocusedRect); 7067 } 7068 7069 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 7070 // need to be focusable 7071 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 7072 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7073 return false; 7074 } 7075 7076 // need to be focusable in touch mode if in touch mode 7077 if (isInTouchMode() && 7078 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 7079 return false; 7080 } 7081 7082 // need to not have any parents blocking us 7083 if (hasAncestorThatBlocksDescendantFocus()) { 7084 return false; 7085 } 7086 7087 handleFocusGainInternal(direction, previouslyFocusedRect); 7088 return true; 7089 } 7090 7091 /** 7092 * Call this to try to give focus to a specific view or to one of its descendants. This is a 7093 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 7094 * touch mode to request focus when they are touched. 7095 * 7096 * @return Whether this view or one of its descendants actually took focus. 7097 * 7098 * @see #isInTouchMode() 7099 * 7100 */ 7101 public final boolean requestFocusFromTouch() { 7102 // Leave touch mode if we need to 7103 if (isInTouchMode()) { 7104 ViewRootImpl viewRoot = getViewRootImpl(); 7105 if (viewRoot != null) { 7106 viewRoot.ensureTouchMode(false); 7107 } 7108 } 7109 return requestFocus(View.FOCUS_DOWN); 7110 } 7111 7112 /** 7113 * @return Whether any ancestor of this view blocks descendant focus. 7114 */ 7115 private boolean hasAncestorThatBlocksDescendantFocus() { 7116 ViewParent ancestor = mParent; 7117 while (ancestor instanceof ViewGroup) { 7118 final ViewGroup vgAncestor = (ViewGroup) ancestor; 7119 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) { 7120 return true; 7121 } else { 7122 ancestor = vgAncestor.getParent(); 7123 } 7124 } 7125 return false; 7126 } 7127 7128 /** 7129 * Gets the mode for determining whether this View is important for accessibility 7130 * which is if it fires accessibility events and if it is reported to 7131 * accessibility services that query the screen. 7132 * 7133 * @return The mode for determining whether a View is important for accessibility. 7134 * 7135 * @attr ref android.R.styleable#View_importantForAccessibility 7136 * 7137 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7138 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7139 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7140 */ 7141 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 7142 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 7143 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 7144 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no") 7145 }) 7146 public int getImportantForAccessibility() { 7147 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7148 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7149 } 7150 7151 /** 7152 * Sets the live region mode for this view. This indicates to accessibility 7153 * services whether they should automatically notify the user about changes 7154 * to the view's content description or text, or to the content descriptions 7155 * or text of the view's children (where applicable). 7156 * <p> 7157 * For example, in a login screen with a TextView that displays an "incorrect 7158 * password" notification, that view should be marked as a live region with 7159 * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7160 * <p> 7161 * To disable change notifications for this view, use 7162 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region 7163 * mode for most views. 7164 * <p> 7165 * To indicate that the user should be notified of changes, use 7166 * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7167 * <p> 7168 * If the view's changes should interrupt ongoing speech and notify the user 7169 * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}. 7170 * 7171 * @param mode The live region mode for this view, one of: 7172 * <ul> 7173 * <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE} 7174 * <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE} 7175 * <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE} 7176 * </ul> 7177 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7178 */ 7179 public void setAccessibilityLiveRegion(int mode) { 7180 if (mode != getAccessibilityLiveRegion()) { 7181 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7182 mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT) 7183 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7184 notifyViewAccessibilityStateChangedIfNeeded( 7185 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7186 } 7187 } 7188 7189 /** 7190 * Gets the live region mode for this View. 7191 * 7192 * @return The live region mode for the view. 7193 * 7194 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7195 * 7196 * @see #setAccessibilityLiveRegion(int) 7197 */ 7198 public int getAccessibilityLiveRegion() { 7199 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK) 7200 >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 7201 } 7202 7203 /** 7204 * Sets how to determine whether this view is important for accessibility 7205 * which is if it fires accessibility events and if it is reported to 7206 * accessibility services that query the screen. 7207 * 7208 * @param mode How to determine whether this view is important for accessibility. 7209 * 7210 * @attr ref android.R.styleable#View_importantForAccessibility 7211 * 7212 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7213 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7214 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7215 */ 7216 public void setImportantForAccessibility(int mode) { 7217 final boolean oldIncludeForAccessibility = includeForAccessibility(); 7218 if (mode != getImportantForAccessibility()) { 7219 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7220 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 7221 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7222 if (oldIncludeForAccessibility != includeForAccessibility()) { 7223 notifySubtreeAccessibilityStateChangedIfNeeded(); 7224 } else { 7225 notifyViewAccessibilityStateChangedIfNeeded( 7226 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7227 } 7228 } 7229 } 7230 7231 /** 7232 * Gets whether this view should be exposed for accessibility. 7233 * 7234 * @return Whether the view is exposed for accessibility. 7235 * 7236 * @hide 7237 */ 7238 public boolean isImportantForAccessibility() { 7239 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7240 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7241 switch (mode) { 7242 case IMPORTANT_FOR_ACCESSIBILITY_YES: 7243 return true; 7244 case IMPORTANT_FOR_ACCESSIBILITY_NO: 7245 return false; 7246 case IMPORTANT_FOR_ACCESSIBILITY_AUTO: 7247 return isActionableForAccessibility() || hasListenersForAccessibility() 7248 || getAccessibilityNodeProvider() != null 7249 || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE; 7250 default: 7251 throw new IllegalArgumentException("Unknown important for accessibility mode: " 7252 + mode); 7253 } 7254 } 7255 7256 /** 7257 * Gets the parent for accessibility purposes. Note that the parent for 7258 * accessibility is not necessary the immediate parent. It is the first 7259 * predecessor that is important for accessibility. 7260 * 7261 * @return The parent for accessibility purposes. 7262 */ 7263 public ViewParent getParentForAccessibility() { 7264 if (mParent instanceof View) { 7265 View parentView = (View) mParent; 7266 if (parentView.includeForAccessibility()) { 7267 return mParent; 7268 } else { 7269 return mParent.getParentForAccessibility(); 7270 } 7271 } 7272 return null; 7273 } 7274 7275 /** 7276 * Adds the children of a given View for accessibility. Since some Views are 7277 * not important for accessibility the children for accessibility are not 7278 * necessarily direct children of the view, rather they are the first level of 7279 * descendants important for accessibility. 7280 * 7281 * @param children The list of children for accessibility. 7282 */ 7283 public void addChildrenForAccessibility(ArrayList<View> children) { 7284 if (includeForAccessibility()) { 7285 children.add(this); 7286 } 7287 } 7288 7289 /** 7290 * Whether to regard this view for accessibility. A view is regarded for 7291 * accessibility if it is important for accessibility or the querying 7292 * accessibility service has explicitly requested that view not 7293 * important for accessibility are regarded. 7294 * 7295 * @return Whether to regard the view for accessibility. 7296 * 7297 * @hide 7298 */ 7299 public boolean includeForAccessibility() { 7300 //noinspection SimplifiableIfStatement 7301 if (mAttachInfo != null) { 7302 return (mAttachInfo.mAccessibilityFetchFlags 7303 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0 7304 || isImportantForAccessibility(); 7305 } 7306 return false; 7307 } 7308 7309 /** 7310 * Returns whether the View is considered actionable from 7311 * accessibility perspective. Such view are important for 7312 * accessibility. 7313 * 7314 * @return True if the view is actionable for accessibility. 7315 * 7316 * @hide 7317 */ 7318 public boolean isActionableForAccessibility() { 7319 return (isClickable() || isLongClickable() || isFocusable()); 7320 } 7321 7322 /** 7323 * Returns whether the View has registered callbacks which makes it 7324 * important for accessibility. 7325 * 7326 * @return True if the view is actionable for accessibility. 7327 */ 7328 private boolean hasListenersForAccessibility() { 7329 ListenerInfo info = getListenerInfo(); 7330 return mTouchDelegate != null || info.mOnKeyListener != null 7331 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 7332 || info.mOnHoverListener != null || info.mOnDragListener != null; 7333 } 7334 7335 /** 7336 * Notifies that the accessibility state of this view changed. The change 7337 * is local to this view and does not represent structural changes such 7338 * as children and parent. For example, the view became focusable. The 7339 * notification is at at most once every 7340 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7341 * to avoid unnecessary load to the system. Also once a view has a pending 7342 * notification this method is a NOP until the notification has been sent. 7343 * 7344 * @hide 7345 */ 7346 public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) { 7347 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7348 return; 7349 } 7350 if (mSendViewStateChangedAccessibilityEvent == null) { 7351 mSendViewStateChangedAccessibilityEvent = 7352 new SendViewStateChangedAccessibilityEvent(); 7353 } 7354 mSendViewStateChangedAccessibilityEvent.runOrPost(changeType); 7355 } 7356 7357 /** 7358 * Notifies that the accessibility state of this view changed. The change 7359 * is *not* local to this view and does represent structural changes such 7360 * as children and parent. For example, the view size changed. The 7361 * notification is at at most once every 7362 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7363 * to avoid unnecessary load to the system. Also once a view has a pending 7364 * notifucation this method is a NOP until the notification has been sent. 7365 * 7366 * @hide 7367 */ 7368 public void notifySubtreeAccessibilityStateChangedIfNeeded() { 7369 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7370 return; 7371 } 7372 if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) { 7373 mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 7374 if (mParent != null) { 7375 try { 7376 mParent.notifySubtreeAccessibilityStateChanged( 7377 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE); 7378 } catch (AbstractMethodError e) { 7379 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 7380 " does not fully implement ViewParent", e); 7381 } 7382 } 7383 } 7384 } 7385 7386 /** 7387 * Reset the flag indicating the accessibility state of the subtree rooted 7388 * at this view changed. 7389 */ 7390 void resetSubtreeAccessibilityStateChanged() { 7391 mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 7392 } 7393 7394 /** 7395 * Performs the specified accessibility action on the view. For 7396 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 7397 * <p> 7398 * If an {@link AccessibilityDelegate} has been specified via calling 7399 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 7400 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 7401 * is responsible for handling this call. 7402 * </p> 7403 * 7404 * @param action The action to perform. 7405 * @param arguments Optional action arguments. 7406 * @return Whether the action was performed. 7407 */ 7408 public boolean performAccessibilityAction(int action, Bundle arguments) { 7409 if (mAccessibilityDelegate != null) { 7410 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 7411 } else { 7412 return performAccessibilityActionInternal(action, arguments); 7413 } 7414 } 7415 7416 /** 7417 * @see #performAccessibilityAction(int, Bundle) 7418 * 7419 * Note: Called from the default {@link AccessibilityDelegate}. 7420 */ 7421 boolean performAccessibilityActionInternal(int action, Bundle arguments) { 7422 switch (action) { 7423 case AccessibilityNodeInfo.ACTION_CLICK: { 7424 if (isClickable()) { 7425 performClick(); 7426 return true; 7427 } 7428 } break; 7429 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 7430 if (isLongClickable()) { 7431 performLongClick(); 7432 return true; 7433 } 7434 } break; 7435 case AccessibilityNodeInfo.ACTION_FOCUS: { 7436 if (!hasFocus()) { 7437 // Get out of touch mode since accessibility 7438 // wants to move focus around. 7439 getViewRootImpl().ensureTouchMode(false); 7440 return requestFocus(); 7441 } 7442 } break; 7443 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 7444 if (hasFocus()) { 7445 clearFocus(); 7446 return !isFocused(); 7447 } 7448 } break; 7449 case AccessibilityNodeInfo.ACTION_SELECT: { 7450 if (!isSelected()) { 7451 setSelected(true); 7452 return isSelected(); 7453 } 7454 } break; 7455 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 7456 if (isSelected()) { 7457 setSelected(false); 7458 return !isSelected(); 7459 } 7460 } break; 7461 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 7462 if (!isAccessibilityFocused()) { 7463 return requestAccessibilityFocus(); 7464 } 7465 } break; 7466 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 7467 if (isAccessibilityFocused()) { 7468 clearAccessibilityFocus(); 7469 return true; 7470 } 7471 } break; 7472 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 7473 if (arguments != null) { 7474 final int granularity = arguments.getInt( 7475 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 7476 final boolean extendSelection = arguments.getBoolean( 7477 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 7478 return traverseAtGranularity(granularity, true, extendSelection); 7479 } 7480 } break; 7481 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 7482 if (arguments != null) { 7483 final int granularity = arguments.getInt( 7484 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 7485 final boolean extendSelection = arguments.getBoolean( 7486 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 7487 return traverseAtGranularity(granularity, false, extendSelection); 7488 } 7489 } break; 7490 case AccessibilityNodeInfo.ACTION_SET_SELECTION: { 7491 CharSequence text = getIterableTextForAccessibility(); 7492 if (text == null) { 7493 return false; 7494 } 7495 final int start = (arguments != null) ? arguments.getInt( 7496 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1; 7497 final int end = (arguments != null) ? arguments.getInt( 7498 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1; 7499 // Only cursor position can be specified (selection length == 0) 7500 if ((getAccessibilitySelectionStart() != start 7501 || getAccessibilitySelectionEnd() != end) 7502 && (start == end)) { 7503 setAccessibilitySelection(start, end); 7504 notifyViewAccessibilityStateChangedIfNeeded( 7505 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7506 return true; 7507 } 7508 } break; 7509 } 7510 return false; 7511 } 7512 7513 private boolean traverseAtGranularity(int granularity, boolean forward, 7514 boolean extendSelection) { 7515 CharSequence text = getIterableTextForAccessibility(); 7516 if (text == null || text.length() == 0) { 7517 return false; 7518 } 7519 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 7520 if (iterator == null) { 7521 return false; 7522 } 7523 int current = getAccessibilitySelectionEnd(); 7524 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 7525 current = forward ? 0 : text.length(); 7526 } 7527 final int[] range = forward ? iterator.following(current) : iterator.preceding(current); 7528 if (range == null) { 7529 return false; 7530 } 7531 final int segmentStart = range[0]; 7532 final int segmentEnd = range[1]; 7533 int selectionStart; 7534 int selectionEnd; 7535 if (extendSelection && isAccessibilitySelectionExtendable()) { 7536 selectionStart = getAccessibilitySelectionStart(); 7537 if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 7538 selectionStart = forward ? segmentStart : segmentEnd; 7539 } 7540 selectionEnd = forward ? segmentEnd : segmentStart; 7541 } else { 7542 selectionStart = selectionEnd= forward ? segmentEnd : segmentStart; 7543 } 7544 setAccessibilitySelection(selectionStart, selectionEnd); 7545 final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY 7546 : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY; 7547 sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd); 7548 return true; 7549 } 7550 7551 /** 7552 * Gets the text reported for accessibility purposes. 7553 * 7554 * @return The accessibility text. 7555 * 7556 * @hide 7557 */ 7558 public CharSequence getIterableTextForAccessibility() { 7559 return getContentDescription(); 7560 } 7561 7562 /** 7563 * Gets whether accessibility selection can be extended. 7564 * 7565 * @return If selection is extensible. 7566 * 7567 * @hide 7568 */ 7569 public boolean isAccessibilitySelectionExtendable() { 7570 return false; 7571 } 7572 7573 /** 7574 * @hide 7575 */ 7576 public int getAccessibilitySelectionStart() { 7577 return mAccessibilityCursorPosition; 7578 } 7579 7580 /** 7581 * @hide 7582 */ 7583 public int getAccessibilitySelectionEnd() { 7584 return getAccessibilitySelectionStart(); 7585 } 7586 7587 /** 7588 * @hide 7589 */ 7590 public void setAccessibilitySelection(int start, int end) { 7591 if (start == end && end == mAccessibilityCursorPosition) { 7592 return; 7593 } 7594 if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) { 7595 mAccessibilityCursorPosition = start; 7596 } else { 7597 mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 7598 } 7599 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 7600 } 7601 7602 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 7603 int fromIndex, int toIndex) { 7604 if (mParent == null) { 7605 return; 7606 } 7607 AccessibilityEvent event = AccessibilityEvent.obtain( 7608 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 7609 onInitializeAccessibilityEvent(event); 7610 onPopulateAccessibilityEvent(event); 7611 event.setFromIndex(fromIndex); 7612 event.setToIndex(toIndex); 7613 event.setAction(action); 7614 event.setMovementGranularity(granularity); 7615 mParent.requestSendAccessibilityEvent(this, event); 7616 } 7617 7618 /** 7619 * @hide 7620 */ 7621 public TextSegmentIterator getIteratorForGranularity(int granularity) { 7622 switch (granularity) { 7623 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 7624 CharSequence text = getIterableTextForAccessibility(); 7625 if (text != null && text.length() > 0) { 7626 CharacterTextSegmentIterator iterator = 7627 CharacterTextSegmentIterator.getInstance( 7628 mContext.getResources().getConfiguration().locale); 7629 iterator.initialize(text.toString()); 7630 return iterator; 7631 } 7632 } break; 7633 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 7634 CharSequence text = getIterableTextForAccessibility(); 7635 if (text != null && text.length() > 0) { 7636 WordTextSegmentIterator iterator = 7637 WordTextSegmentIterator.getInstance( 7638 mContext.getResources().getConfiguration().locale); 7639 iterator.initialize(text.toString()); 7640 return iterator; 7641 } 7642 } break; 7643 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 7644 CharSequence text = getIterableTextForAccessibility(); 7645 if (text != null && text.length() > 0) { 7646 ParagraphTextSegmentIterator iterator = 7647 ParagraphTextSegmentIterator.getInstance(); 7648 iterator.initialize(text.toString()); 7649 return iterator; 7650 } 7651 } break; 7652 } 7653 return null; 7654 } 7655 7656 /** 7657 * @hide 7658 */ 7659 public void dispatchStartTemporaryDetach() { 7660 clearDisplayList(); 7661 7662 onStartTemporaryDetach(); 7663 } 7664 7665 /** 7666 * This is called when a container is going to temporarily detach a child, with 7667 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 7668 * It will either be followed by {@link #onFinishTemporaryDetach()} or 7669 * {@link #onDetachedFromWindow()} when the container is done. 7670 */ 7671 public void onStartTemporaryDetach() { 7672 removeUnsetPressCallback(); 7673 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 7674 } 7675 7676 /** 7677 * @hide 7678 */ 7679 public void dispatchFinishTemporaryDetach() { 7680 onFinishTemporaryDetach(); 7681 } 7682 7683 /** 7684 * Called after {@link #onStartTemporaryDetach} when the container is done 7685 * changing the view. 7686 */ 7687 public void onFinishTemporaryDetach() { 7688 } 7689 7690 /** 7691 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 7692 * for this view's window. Returns null if the view is not currently attached 7693 * to the window. Normally you will not need to use this directly, but 7694 * just use the standard high-level event callbacks like 7695 * {@link #onKeyDown(int, KeyEvent)}. 7696 */ 7697 public KeyEvent.DispatcherState getKeyDispatcherState() { 7698 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 7699 } 7700 7701 /** 7702 * Dispatch a key event before it is processed by any input method 7703 * associated with the view hierarchy. This can be used to intercept 7704 * key events in special situations before the IME consumes them; a 7705 * typical example would be handling the BACK key to update the application's 7706 * UI instead of allowing the IME to see it and close itself. 7707 * 7708 * @param event The key event to be dispatched. 7709 * @return True if the event was handled, false otherwise. 7710 */ 7711 public boolean dispatchKeyEventPreIme(KeyEvent event) { 7712 return onKeyPreIme(event.getKeyCode(), event); 7713 } 7714 7715 /** 7716 * Dispatch a key event to the next view on the focus path. This path runs 7717 * from the top of the view tree down to the currently focused view. If this 7718 * view has focus, it will dispatch to itself. Otherwise it will dispatch 7719 * the next node down the focus path. This method also fires any key 7720 * listeners. 7721 * 7722 * @param event The key event to be dispatched. 7723 * @return True if the event was handled, false otherwise. 7724 */ 7725 public boolean dispatchKeyEvent(KeyEvent event) { 7726 if (mInputEventConsistencyVerifier != null) { 7727 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 7728 } 7729 7730 // Give any attached key listener a first crack at the event. 7731 //noinspection SimplifiableIfStatement 7732 ListenerInfo li = mListenerInfo; 7733 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 7734 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 7735 return true; 7736 } 7737 7738 if (event.dispatch(this, mAttachInfo != null 7739 ? mAttachInfo.mKeyDispatchState : null, this)) { 7740 return true; 7741 } 7742 7743 if (mInputEventConsistencyVerifier != null) { 7744 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7745 } 7746 return false; 7747 } 7748 7749 /** 7750 * Dispatches a key shortcut event. 7751 * 7752 * @param event The key event to be dispatched. 7753 * @return True if the event was handled by the view, false otherwise. 7754 */ 7755 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 7756 return onKeyShortcut(event.getKeyCode(), event); 7757 } 7758 7759 /** 7760 * Pass the touch screen motion event down to the target view, or this 7761 * view if it is the target. 7762 * 7763 * @param event The motion event to be dispatched. 7764 * @return True if the event was handled by the view, false otherwise. 7765 */ 7766 public boolean dispatchTouchEvent(MotionEvent event) { 7767 if (mInputEventConsistencyVerifier != null) { 7768 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 7769 } 7770 7771 if (onFilterTouchEventForSecurity(event)) { 7772 //noinspection SimplifiableIfStatement 7773 ListenerInfo li = mListenerInfo; 7774 if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 7775 && li.mOnTouchListener.onTouch(this, event)) { 7776 return true; 7777 } 7778 7779 if (onTouchEvent(event)) { 7780 return true; 7781 } 7782 } 7783 7784 if (mInputEventConsistencyVerifier != null) { 7785 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7786 } 7787 return false; 7788 } 7789 7790 /** 7791 * Filter the touch event to apply security policies. 7792 * 7793 * @param event The motion event to be filtered. 7794 * @return True if the event should be dispatched, false if the event should be dropped. 7795 * 7796 * @see #getFilterTouchesWhenObscured 7797 */ 7798 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 7799 //noinspection RedundantIfStatement 7800 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 7801 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 7802 // Window is obscured, drop this touch. 7803 return false; 7804 } 7805 return true; 7806 } 7807 7808 /** 7809 * Pass a trackball motion event down to the focused view. 7810 * 7811 * @param event The motion event to be dispatched. 7812 * @return True if the event was handled by the view, false otherwise. 7813 */ 7814 public boolean dispatchTrackballEvent(MotionEvent event) { 7815 if (mInputEventConsistencyVerifier != null) { 7816 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 7817 } 7818 7819 return onTrackballEvent(event); 7820 } 7821 7822 /** 7823 * Dispatch a generic motion event. 7824 * <p> 7825 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 7826 * are delivered to the view under the pointer. All other generic motion events are 7827 * delivered to the focused view. Hover events are handled specially and are delivered 7828 * to {@link #onHoverEvent(MotionEvent)}. 7829 * </p> 7830 * 7831 * @param event The motion event to be dispatched. 7832 * @return True if the event was handled by the view, false otherwise. 7833 */ 7834 public boolean dispatchGenericMotionEvent(MotionEvent event) { 7835 if (mInputEventConsistencyVerifier != null) { 7836 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 7837 } 7838 7839 final int source = event.getSource(); 7840 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 7841 final int action = event.getAction(); 7842 if (action == MotionEvent.ACTION_HOVER_ENTER 7843 || action == MotionEvent.ACTION_HOVER_MOVE 7844 || action == MotionEvent.ACTION_HOVER_EXIT) { 7845 if (dispatchHoverEvent(event)) { 7846 return true; 7847 } 7848 } else if (dispatchGenericPointerEvent(event)) { 7849 return true; 7850 } 7851 } else if (dispatchGenericFocusedEvent(event)) { 7852 return true; 7853 } 7854 7855 if (dispatchGenericMotionEventInternal(event)) { 7856 return true; 7857 } 7858 7859 if (mInputEventConsistencyVerifier != null) { 7860 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7861 } 7862 return false; 7863 } 7864 7865 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 7866 //noinspection SimplifiableIfStatement 7867 ListenerInfo li = mListenerInfo; 7868 if (li != null && li.mOnGenericMotionListener != null 7869 && (mViewFlags & ENABLED_MASK) == ENABLED 7870 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 7871 return true; 7872 } 7873 7874 if (onGenericMotionEvent(event)) { 7875 return true; 7876 } 7877 7878 if (mInputEventConsistencyVerifier != null) { 7879 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7880 } 7881 return false; 7882 } 7883 7884 /** 7885 * Dispatch a hover event. 7886 * <p> 7887 * Do not call this method directly. 7888 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 7889 * </p> 7890 * 7891 * @param event The motion event to be dispatched. 7892 * @return True if the event was handled by the view, false otherwise. 7893 */ 7894 protected boolean dispatchHoverEvent(MotionEvent event) { 7895 ListenerInfo li = mListenerInfo; 7896 //noinspection SimplifiableIfStatement 7897 if (li != null && li.mOnHoverListener != null 7898 && (mViewFlags & ENABLED_MASK) == ENABLED 7899 && li.mOnHoverListener.onHover(this, event)) { 7900 return true; 7901 } 7902 7903 return onHoverEvent(event); 7904 } 7905 7906 /** 7907 * Returns true if the view has a child to which it has recently sent 7908 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 7909 * it does not have a hovered child, then it must be the innermost hovered view. 7910 * @hide 7911 */ 7912 protected boolean hasHoveredChild() { 7913 return false; 7914 } 7915 7916 /** 7917 * Dispatch a generic motion event to the view under the first pointer. 7918 * <p> 7919 * Do not call this method directly. 7920 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 7921 * </p> 7922 * 7923 * @param event The motion event to be dispatched. 7924 * @return True if the event was handled by the view, false otherwise. 7925 */ 7926 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 7927 return false; 7928 } 7929 7930 /** 7931 * Dispatch a generic motion event to the currently focused view. 7932 * <p> 7933 * Do not call this method directly. 7934 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 7935 * </p> 7936 * 7937 * @param event The motion event to be dispatched. 7938 * @return True if the event was handled by the view, false otherwise. 7939 */ 7940 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 7941 return false; 7942 } 7943 7944 /** 7945 * Dispatch a pointer event. 7946 * <p> 7947 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 7948 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 7949 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 7950 * and should not be expected to handle other pointing device features. 7951 * </p> 7952 * 7953 * @param event The motion event to be dispatched. 7954 * @return True if the event was handled by the view, false otherwise. 7955 * @hide 7956 */ 7957 public final boolean dispatchPointerEvent(MotionEvent event) { 7958 if (event.isTouchEvent()) { 7959 return dispatchTouchEvent(event); 7960 } else { 7961 return dispatchGenericMotionEvent(event); 7962 } 7963 } 7964 7965 /** 7966 * Called when the window containing this view gains or loses window focus. 7967 * ViewGroups should override to route to their children. 7968 * 7969 * @param hasFocus True if the window containing this view now has focus, 7970 * false otherwise. 7971 */ 7972 public void dispatchWindowFocusChanged(boolean hasFocus) { 7973 onWindowFocusChanged(hasFocus); 7974 } 7975 7976 /** 7977 * Called when the window containing this view gains or loses focus. Note 7978 * that this is separate from view focus: to receive key events, both 7979 * your view and its window must have focus. If a window is displayed 7980 * on top of yours that takes input focus, then your own window will lose 7981 * focus but the view focus will remain unchanged. 7982 * 7983 * @param hasWindowFocus True if the window containing this view now has 7984 * focus, false otherwise. 7985 */ 7986 public void onWindowFocusChanged(boolean hasWindowFocus) { 7987 InputMethodManager imm = InputMethodManager.peekInstance(); 7988 if (!hasWindowFocus) { 7989 if (isPressed()) { 7990 setPressed(false); 7991 } 7992 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 7993 imm.focusOut(this); 7994 } 7995 removeLongPressCallback(); 7996 removeTapCallback(); 7997 onFocusLost(); 7998 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 7999 imm.focusIn(this); 8000 } 8001 refreshDrawableState(); 8002 } 8003 8004 /** 8005 * Returns true if this view is in a window that currently has window focus. 8006 * Note that this is not the same as the view itself having focus. 8007 * 8008 * @return True if this view is in a window that currently has window focus. 8009 */ 8010 public boolean hasWindowFocus() { 8011 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 8012 } 8013 8014 /** 8015 * Dispatch a view visibility change down the view hierarchy. 8016 * ViewGroups should override to route to their children. 8017 * @param changedView The view whose visibility changed. Could be 'this' or 8018 * an ancestor view. 8019 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 8020 * {@link #INVISIBLE} or {@link #GONE}. 8021 */ 8022 protected void dispatchVisibilityChanged(@NonNull View changedView, 8023 @Visibility int visibility) { 8024 onVisibilityChanged(changedView, visibility); 8025 } 8026 8027 /** 8028 * Called when the visibility of the view or an ancestor of the view is changed. 8029 * @param changedView The view whose visibility changed. Could be 'this' or 8030 * an ancestor view. 8031 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 8032 * {@link #INVISIBLE} or {@link #GONE}. 8033 */ 8034 protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) { 8035 if (visibility == VISIBLE) { 8036 if (mAttachInfo != null) { 8037 initialAwakenScrollBars(); 8038 } else { 8039 mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 8040 } 8041 } 8042 } 8043 8044 /** 8045 * Dispatch a hint about whether this view is displayed. For instance, when 8046 * a View moves out of the screen, it might receives a display hint indicating 8047 * the view is not displayed. Applications should not <em>rely</em> on this hint 8048 * as there is no guarantee that they will receive one. 8049 * 8050 * @param hint A hint about whether or not this view is displayed: 8051 * {@link #VISIBLE} or {@link #INVISIBLE}. 8052 */ 8053 public void dispatchDisplayHint(@Visibility int hint) { 8054 onDisplayHint(hint); 8055 } 8056 8057 /** 8058 * Gives this view a hint about whether is displayed or not. For instance, when 8059 * a View moves out of the screen, it might receives a display hint indicating 8060 * the view is not displayed. Applications should not <em>rely</em> on this hint 8061 * as there is no guarantee that they will receive one. 8062 * 8063 * @param hint A hint about whether or not this view is displayed: 8064 * {@link #VISIBLE} or {@link #INVISIBLE}. 8065 */ 8066 protected void onDisplayHint(@Visibility int hint) { 8067 } 8068 8069 /** 8070 * Dispatch a window visibility change down the view hierarchy. 8071 * ViewGroups should override to route to their children. 8072 * 8073 * @param visibility The new visibility of the window. 8074 * 8075 * @see #onWindowVisibilityChanged(int) 8076 */ 8077 public void dispatchWindowVisibilityChanged(@Visibility int visibility) { 8078 onWindowVisibilityChanged(visibility); 8079 } 8080 8081 /** 8082 * Called when the window containing has change its visibility 8083 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 8084 * that this tells you whether or not your window is being made visible 8085 * to the window manager; this does <em>not</em> tell you whether or not 8086 * your window is obscured by other windows on the screen, even if it 8087 * is itself visible. 8088 * 8089 * @param visibility The new visibility of the window. 8090 */ 8091 protected void onWindowVisibilityChanged(@Visibility int visibility) { 8092 if (visibility == VISIBLE) { 8093 initialAwakenScrollBars(); 8094 } 8095 } 8096 8097 /** 8098 * Returns the current visibility of the window this view is attached to 8099 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 8100 * 8101 * @return Returns the current visibility of the view's window. 8102 */ 8103 @Visibility 8104 public int getWindowVisibility() { 8105 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 8106 } 8107 8108 /** 8109 * Retrieve the overall visible display size in which the window this view is 8110 * attached to has been positioned in. This takes into account screen 8111 * decorations above the window, for both cases where the window itself 8112 * is being position inside of them or the window is being placed under 8113 * then and covered insets are used for the window to position its content 8114 * inside. In effect, this tells you the available area where content can 8115 * be placed and remain visible to users. 8116 * 8117 * <p>This function requires an IPC back to the window manager to retrieve 8118 * the requested information, so should not be used in performance critical 8119 * code like drawing. 8120 * 8121 * @param outRect Filled in with the visible display frame. If the view 8122 * is not attached to a window, this is simply the raw display size. 8123 */ 8124 public void getWindowVisibleDisplayFrame(Rect outRect) { 8125 if (mAttachInfo != null) { 8126 try { 8127 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 8128 } catch (RemoteException e) { 8129 return; 8130 } 8131 // XXX This is really broken, and probably all needs to be done 8132 // in the window manager, and we need to know more about whether 8133 // we want the area behind or in front of the IME. 8134 final Rect insets = mAttachInfo.mVisibleInsets; 8135 outRect.left += insets.left; 8136 outRect.top += insets.top; 8137 outRect.right -= insets.right; 8138 outRect.bottom -= insets.bottom; 8139 return; 8140 } 8141 // The view is not attached to a display so we don't have a context. 8142 // Make a best guess about the display size. 8143 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 8144 d.getRectSize(outRect); 8145 } 8146 8147 /** 8148 * Dispatch a notification about a resource configuration change down 8149 * the view hierarchy. 8150 * ViewGroups should override to route to their children. 8151 * 8152 * @param newConfig The new resource configuration. 8153 * 8154 * @see #onConfigurationChanged(android.content.res.Configuration) 8155 */ 8156 public void dispatchConfigurationChanged(Configuration newConfig) { 8157 onConfigurationChanged(newConfig); 8158 } 8159 8160 /** 8161 * Called when the current configuration of the resources being used 8162 * by the application have changed. You can use this to decide when 8163 * to reload resources that can changed based on orientation and other 8164 * configuration characterstics. You only need to use this if you are 8165 * not relying on the normal {@link android.app.Activity} mechanism of 8166 * recreating the activity instance upon a configuration change. 8167 * 8168 * @param newConfig The new resource configuration. 8169 */ 8170 protected void onConfigurationChanged(Configuration newConfig) { 8171 } 8172 8173 /** 8174 * Private function to aggregate all per-view attributes in to the view 8175 * root. 8176 */ 8177 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8178 performCollectViewAttributes(attachInfo, visibility); 8179 } 8180 8181 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8182 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 8183 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 8184 attachInfo.mKeepScreenOn = true; 8185 } 8186 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 8187 ListenerInfo li = mListenerInfo; 8188 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 8189 attachInfo.mHasSystemUiListeners = true; 8190 } 8191 } 8192 } 8193 8194 void needGlobalAttributesUpdate(boolean force) { 8195 final AttachInfo ai = mAttachInfo; 8196 if (ai != null && !ai.mRecomputeGlobalAttributes) { 8197 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 8198 || ai.mHasSystemUiListeners) { 8199 ai.mRecomputeGlobalAttributes = true; 8200 } 8201 } 8202 } 8203 8204 /** 8205 * Returns whether the device is currently in touch mode. Touch mode is entered 8206 * once the user begins interacting with the device by touch, and affects various 8207 * things like whether focus is always visible to the user. 8208 * 8209 * @return Whether the device is in touch mode. 8210 */ 8211 @ViewDebug.ExportedProperty 8212 public boolean isInTouchMode() { 8213 if (mAttachInfo != null) { 8214 return mAttachInfo.mInTouchMode; 8215 } else { 8216 return ViewRootImpl.isInTouchMode(); 8217 } 8218 } 8219 8220 /** 8221 * Returns the context the view is running in, through which it can 8222 * access the current theme, resources, etc. 8223 * 8224 * @return The view's Context. 8225 */ 8226 @ViewDebug.CapturedViewProperty 8227 public final Context getContext() { 8228 return mContext; 8229 } 8230 8231 /** 8232 * Handle a key event before it is processed by any input method 8233 * associated with the view hierarchy. This can be used to intercept 8234 * key events in special situations before the IME consumes them; a 8235 * typical example would be handling the BACK key to update the application's 8236 * UI instead of allowing the IME to see it and close itself. 8237 * 8238 * @param keyCode The value in event.getKeyCode(). 8239 * @param event Description of the key event. 8240 * @return If you handled the event, return true. If you want to allow the 8241 * event to be handled by the next receiver, return false. 8242 */ 8243 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 8244 return false; 8245 } 8246 8247 /** 8248 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 8249 * KeyEvent.Callback.onKeyDown()}: perform press of the view 8250 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 8251 * is released, if the view is enabled and clickable. 8252 * 8253 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8254 * although some may elect to do so in some situations. Do not rely on this to 8255 * catch software key presses. 8256 * 8257 * @param keyCode A key code that represents the button pressed, from 8258 * {@link android.view.KeyEvent}. 8259 * @param event The KeyEvent object that defines the button action. 8260 */ 8261 public boolean onKeyDown(int keyCode, KeyEvent event) { 8262 boolean result = false; 8263 8264 if (KeyEvent.isConfirmKey(keyCode)) { 8265 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8266 return true; 8267 } 8268 // Long clickable items don't necessarily have to be clickable 8269 if (((mViewFlags & CLICKABLE) == CLICKABLE || 8270 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 8271 (event.getRepeatCount() == 0)) { 8272 setPressed(true); 8273 checkForLongClick(0); 8274 return true; 8275 } 8276 } 8277 return result; 8278 } 8279 8280 /** 8281 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 8282 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 8283 * the event). 8284 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8285 * although some may elect to do so in some situations. Do not rely on this to 8286 * catch software key presses. 8287 */ 8288 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 8289 return false; 8290 } 8291 8292 /** 8293 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 8294 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 8295 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 8296 * {@link KeyEvent#KEYCODE_ENTER} is released. 8297 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8298 * although some may elect to do so in some situations. Do not rely on this to 8299 * catch software key presses. 8300 * 8301 * @param keyCode A key code that represents the button pressed, from 8302 * {@link android.view.KeyEvent}. 8303 * @param event The KeyEvent object that defines the button action. 8304 */ 8305 public boolean onKeyUp(int keyCode, KeyEvent event) { 8306 if (KeyEvent.isConfirmKey(keyCode)) { 8307 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8308 return true; 8309 } 8310 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 8311 setPressed(false); 8312 8313 if (!mHasPerformedLongPress) { 8314 // This is a tap, so remove the longpress check 8315 removeLongPressCallback(); 8316 return performClick(); 8317 } 8318 } 8319 } 8320 return false; 8321 } 8322 8323 /** 8324 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 8325 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 8326 * the event). 8327 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8328 * although some may elect to do so in some situations. Do not rely on this to 8329 * catch software key presses. 8330 * 8331 * @param keyCode A key code that represents the button pressed, from 8332 * {@link android.view.KeyEvent}. 8333 * @param repeatCount The number of times the action was made. 8334 * @param event The KeyEvent object that defines the button action. 8335 */ 8336 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 8337 return false; 8338 } 8339 8340 /** 8341 * Called on the focused view when a key shortcut event is not handled. 8342 * Override this method to implement local key shortcuts for the View. 8343 * Key shortcuts can also be implemented by setting the 8344 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 8345 * 8346 * @param keyCode The value in event.getKeyCode(). 8347 * @param event Description of the key event. 8348 * @return If you handled the event, return true. If you want to allow the 8349 * event to be handled by the next receiver, return false. 8350 */ 8351 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 8352 return false; 8353 } 8354 8355 /** 8356 * Check whether the called view is a text editor, in which case it 8357 * would make sense to automatically display a soft input window for 8358 * it. Subclasses should override this if they implement 8359 * {@link #onCreateInputConnection(EditorInfo)} to return true if 8360 * a call on that method would return a non-null InputConnection, and 8361 * they are really a first-class editor that the user would normally 8362 * start typing on when the go into a window containing your view. 8363 * 8364 * <p>The default implementation always returns false. This does 8365 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 8366 * will not be called or the user can not otherwise perform edits on your 8367 * view; it is just a hint to the system that this is not the primary 8368 * purpose of this view. 8369 * 8370 * @return Returns true if this view is a text editor, else false. 8371 */ 8372 public boolean onCheckIsTextEditor() { 8373 return false; 8374 } 8375 8376 /** 8377 * Create a new InputConnection for an InputMethod to interact 8378 * with the view. The default implementation returns null, since it doesn't 8379 * support input methods. You can override this to implement such support. 8380 * This is only needed for views that take focus and text input. 8381 * 8382 * <p>When implementing this, you probably also want to implement 8383 * {@link #onCheckIsTextEditor()} to indicate you will return a 8384 * non-null InputConnection. 8385 * 8386 * @param outAttrs Fill in with attribute information about the connection. 8387 */ 8388 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 8389 return null; 8390 } 8391 8392 /** 8393 * Called by the {@link android.view.inputmethod.InputMethodManager} 8394 * when a view who is not the current 8395 * input connection target is trying to make a call on the manager. The 8396 * default implementation returns false; you can override this to return 8397 * true for certain views if you are performing InputConnection proxying 8398 * to them. 8399 * @param view The View that is making the InputMethodManager call. 8400 * @return Return true to allow the call, false to reject. 8401 */ 8402 public boolean checkInputConnectionProxy(View view) { 8403 return false; 8404 } 8405 8406 /** 8407 * Show the context menu for this view. It is not safe to hold on to the 8408 * menu after returning from this method. 8409 * 8410 * You should normally not overload this method. Overload 8411 * {@link #onCreateContextMenu(ContextMenu)} or define an 8412 * {@link OnCreateContextMenuListener} to add items to the context menu. 8413 * 8414 * @param menu The context menu to populate 8415 */ 8416 public void createContextMenu(ContextMenu menu) { 8417 ContextMenuInfo menuInfo = getContextMenuInfo(); 8418 8419 // Sets the current menu info so all items added to menu will have 8420 // my extra info set. 8421 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 8422 8423 onCreateContextMenu(menu); 8424 ListenerInfo li = mListenerInfo; 8425 if (li != null && li.mOnCreateContextMenuListener != null) { 8426 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 8427 } 8428 8429 // Clear the extra information so subsequent items that aren't mine don't 8430 // have my extra info. 8431 ((MenuBuilder)menu).setCurrentMenuInfo(null); 8432 8433 if (mParent != null) { 8434 mParent.createContextMenu(menu); 8435 } 8436 } 8437 8438 /** 8439 * Views should implement this if they have extra information to associate 8440 * with the context menu. The return result is supplied as a parameter to 8441 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 8442 * callback. 8443 * 8444 * @return Extra information about the item for which the context menu 8445 * should be shown. This information will vary across different 8446 * subclasses of View. 8447 */ 8448 protected ContextMenuInfo getContextMenuInfo() { 8449 return null; 8450 } 8451 8452 /** 8453 * Views should implement this if the view itself is going to add items to 8454 * the context menu. 8455 * 8456 * @param menu the context menu to populate 8457 */ 8458 protected void onCreateContextMenu(ContextMenu menu) { 8459 } 8460 8461 /** 8462 * Implement this method to handle trackball motion events. The 8463 * <em>relative</em> movement of the trackball since the last event 8464 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 8465 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 8466 * that a movement of 1 corresponds to the user pressing one DPAD key (so 8467 * they will often be fractional values, representing the more fine-grained 8468 * movement information available from a trackball). 8469 * 8470 * @param event The motion event. 8471 * @return True if the event was handled, false otherwise. 8472 */ 8473 public boolean onTrackballEvent(MotionEvent event) { 8474 return false; 8475 } 8476 8477 /** 8478 * Implement this method to handle generic motion events. 8479 * <p> 8480 * Generic motion events describe joystick movements, mouse hovers, track pad 8481 * touches, scroll wheel movements and other input events. The 8482 * {@link MotionEvent#getSource() source} of the motion event specifies 8483 * the class of input that was received. Implementations of this method 8484 * must examine the bits in the source before processing the event. 8485 * The following code example shows how this is done. 8486 * </p><p> 8487 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 8488 * are delivered to the view under the pointer. All other generic motion events are 8489 * delivered to the focused view. 8490 * </p> 8491 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 8492 * if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) { 8493 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 8494 * // process the joystick movement... 8495 * return true; 8496 * } 8497 * } 8498 * if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { 8499 * switch (event.getAction()) { 8500 * case MotionEvent.ACTION_HOVER_MOVE: 8501 * // process the mouse hover movement... 8502 * return true; 8503 * case MotionEvent.ACTION_SCROLL: 8504 * // process the scroll wheel movement... 8505 * return true; 8506 * } 8507 * } 8508 * return super.onGenericMotionEvent(event); 8509 * }</pre> 8510 * 8511 * @param event The generic motion event being processed. 8512 * @return True if the event was handled, false otherwise. 8513 */ 8514 public boolean onGenericMotionEvent(MotionEvent event) { 8515 return false; 8516 } 8517 8518 /** 8519 * Implement this method to handle hover events. 8520 * <p> 8521 * This method is called whenever a pointer is hovering into, over, or out of the 8522 * bounds of a view and the view is not currently being touched. 8523 * Hover events are represented as pointer events with action 8524 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 8525 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 8526 * </p> 8527 * <ul> 8528 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 8529 * when the pointer enters the bounds of the view.</li> 8530 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 8531 * when the pointer has already entered the bounds of the view and has moved.</li> 8532 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 8533 * when the pointer has exited the bounds of the view or when the pointer is 8534 * about to go down due to a button click, tap, or similar user action that 8535 * causes the view to be touched.</li> 8536 * </ul> 8537 * <p> 8538 * The view should implement this method to return true to indicate that it is 8539 * handling the hover event, such as by changing its drawable state. 8540 * </p><p> 8541 * The default implementation calls {@link #setHovered} to update the hovered state 8542 * of the view when a hover enter or hover exit event is received, if the view 8543 * is enabled and is clickable. The default implementation also sends hover 8544 * accessibility events. 8545 * </p> 8546 * 8547 * @param event The motion event that describes the hover. 8548 * @return True if the view handled the hover event. 8549 * 8550 * @see #isHovered 8551 * @see #setHovered 8552 * @see #onHoverChanged 8553 */ 8554 public boolean onHoverEvent(MotionEvent event) { 8555 // The root view may receive hover (or touch) events that are outside the bounds of 8556 // the window. This code ensures that we only send accessibility events for 8557 // hovers that are actually within the bounds of the root view. 8558 final int action = event.getActionMasked(); 8559 if (!mSendingHoverAccessibilityEvents) { 8560 if ((action == MotionEvent.ACTION_HOVER_ENTER 8561 || action == MotionEvent.ACTION_HOVER_MOVE) 8562 && !hasHoveredChild() 8563 && pointInView(event.getX(), event.getY())) { 8564 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 8565 mSendingHoverAccessibilityEvents = true; 8566 } 8567 } else { 8568 if (action == MotionEvent.ACTION_HOVER_EXIT 8569 || (action == MotionEvent.ACTION_MOVE 8570 && !pointInView(event.getX(), event.getY()))) { 8571 mSendingHoverAccessibilityEvents = false; 8572 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 8573 // If the window does not have input focus we take away accessibility 8574 // focus as soon as the user stop hovering over the view. 8575 if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) { 8576 getViewRootImpl().setAccessibilityFocus(null, null); 8577 } 8578 } 8579 } 8580 8581 if (isHoverable()) { 8582 switch (action) { 8583 case MotionEvent.ACTION_HOVER_ENTER: 8584 setHovered(true); 8585 break; 8586 case MotionEvent.ACTION_HOVER_EXIT: 8587 setHovered(false); 8588 break; 8589 } 8590 8591 // Dispatch the event to onGenericMotionEvent before returning true. 8592 // This is to provide compatibility with existing applications that 8593 // handled HOVER_MOVE events in onGenericMotionEvent and that would 8594 // break because of the new default handling for hoverable views 8595 // in onHoverEvent. 8596 // Note that onGenericMotionEvent will be called by default when 8597 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 8598 dispatchGenericMotionEventInternal(event); 8599 // The event was already handled by calling setHovered(), so always 8600 // return true. 8601 return true; 8602 } 8603 8604 return false; 8605 } 8606 8607 /** 8608 * Returns true if the view should handle {@link #onHoverEvent} 8609 * by calling {@link #setHovered} to change its hovered state. 8610 * 8611 * @return True if the view is hoverable. 8612 */ 8613 private boolean isHoverable() { 8614 final int viewFlags = mViewFlags; 8615 if ((viewFlags & ENABLED_MASK) == DISABLED) { 8616 return false; 8617 } 8618 8619 return (viewFlags & CLICKABLE) == CLICKABLE 8620 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 8621 } 8622 8623 /** 8624 * Returns true if the view is currently hovered. 8625 * 8626 * @return True if the view is currently hovered. 8627 * 8628 * @see #setHovered 8629 * @see #onHoverChanged 8630 */ 8631 @ViewDebug.ExportedProperty 8632 public boolean isHovered() { 8633 return (mPrivateFlags & PFLAG_HOVERED) != 0; 8634 } 8635 8636 /** 8637 * Sets whether the view is currently hovered. 8638 * <p> 8639 * Calling this method also changes the drawable state of the view. This 8640 * enables the view to react to hover by using different drawable resources 8641 * to change its appearance. 8642 * </p><p> 8643 * The {@link #onHoverChanged} method is called when the hovered state changes. 8644 * </p> 8645 * 8646 * @param hovered True if the view is hovered. 8647 * 8648 * @see #isHovered 8649 * @see #onHoverChanged 8650 */ 8651 public void setHovered(boolean hovered) { 8652 if (hovered) { 8653 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 8654 mPrivateFlags |= PFLAG_HOVERED; 8655 refreshDrawableState(); 8656 onHoverChanged(true); 8657 } 8658 } else { 8659 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 8660 mPrivateFlags &= ~PFLAG_HOVERED; 8661 refreshDrawableState(); 8662 onHoverChanged(false); 8663 } 8664 } 8665 } 8666 8667 /** 8668 * Implement this method to handle hover state changes. 8669 * <p> 8670 * This method is called whenever the hover state changes as a result of a 8671 * call to {@link #setHovered}. 8672 * </p> 8673 * 8674 * @param hovered The current hover state, as returned by {@link #isHovered}. 8675 * 8676 * @see #isHovered 8677 * @see #setHovered 8678 */ 8679 public void onHoverChanged(boolean hovered) { 8680 } 8681 8682 /** 8683 * Implement this method to handle touch screen motion events. 8684 * <p> 8685 * If this method is used to detect click actions, it is recommended that 8686 * the actions be performed by implementing and calling 8687 * {@link #performClick()}. This will ensure consistent system behavior, 8688 * including: 8689 * <ul> 8690 * <li>obeying click sound preferences 8691 * <li>dispatching OnClickListener calls 8692 * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when 8693 * accessibility features are enabled 8694 * </ul> 8695 * 8696 * @param event The motion event. 8697 * @return True if the event was handled, false otherwise. 8698 */ 8699 public boolean onTouchEvent(MotionEvent event) { 8700 final int viewFlags = mViewFlags; 8701 8702 if ((viewFlags & ENABLED_MASK) == DISABLED) { 8703 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 8704 setPressed(false); 8705 } 8706 // A disabled view that is clickable still consumes the touch 8707 // events, it just doesn't respond to them. 8708 return (((viewFlags & CLICKABLE) == CLICKABLE || 8709 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 8710 } 8711 8712 if (mTouchDelegate != null) { 8713 if (mTouchDelegate.onTouchEvent(event)) { 8714 return true; 8715 } 8716 } 8717 8718 if (((viewFlags & CLICKABLE) == CLICKABLE || 8719 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 8720 switch (event.getAction()) { 8721 case MotionEvent.ACTION_UP: 8722 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 8723 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 8724 // take focus if we don't have it already and we should in 8725 // touch mode. 8726 boolean focusTaken = false; 8727 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 8728 focusTaken = requestFocus(); 8729 } 8730 8731 if (prepressed) { 8732 // The button is being released before we actually 8733 // showed it as pressed. Make it show the pressed 8734 // state now (before scheduling the click) to ensure 8735 // the user sees it. 8736 setPressed(true); 8737 } 8738 8739 if (!mHasPerformedLongPress) { 8740 // This is a tap, so remove the longpress check 8741 removeLongPressCallback(); 8742 8743 // Only perform take click actions if we were in the pressed state 8744 if (!focusTaken) { 8745 // Use a Runnable and post this rather than calling 8746 // performClick directly. This lets other visual state 8747 // of the view update before click actions start. 8748 if (mPerformClick == null) { 8749 mPerformClick = new PerformClick(); 8750 } 8751 if (!post(mPerformClick)) { 8752 performClick(); 8753 } 8754 } 8755 } 8756 8757 if (mUnsetPressedState == null) { 8758 mUnsetPressedState = new UnsetPressedState(); 8759 } 8760 8761 if (prepressed) { 8762 postDelayed(mUnsetPressedState, 8763 ViewConfiguration.getPressedStateDuration()); 8764 } else if (!post(mUnsetPressedState)) { 8765 // If the post failed, unpress right now 8766 mUnsetPressedState.run(); 8767 } 8768 removeTapCallback(); 8769 } 8770 break; 8771 8772 case MotionEvent.ACTION_DOWN: 8773 mHasPerformedLongPress = false; 8774 8775 if (performButtonActionOnTouchDown(event)) { 8776 break; 8777 } 8778 8779 // Walk up the hierarchy to determine if we're inside a scrolling container. 8780 boolean isInScrollingContainer = isInScrollingContainer(); 8781 8782 // For views inside a scrolling container, delay the pressed feedback for 8783 // a short period in case this is a scroll. 8784 if (isInScrollingContainer) { 8785 mPrivateFlags |= PFLAG_PREPRESSED; 8786 if (mPendingCheckForTap == null) { 8787 mPendingCheckForTap = new CheckForTap(); 8788 } 8789 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 8790 } else { 8791 // Not inside a scrolling container, so show the feedback right away 8792 setPressed(true); 8793 checkForLongClick(0); 8794 } 8795 break; 8796 8797 case MotionEvent.ACTION_CANCEL: 8798 setPressed(false); 8799 removeTapCallback(); 8800 removeLongPressCallback(); 8801 break; 8802 8803 case MotionEvent.ACTION_MOVE: 8804 final int x = (int) event.getX(); 8805 final int y = (int) event.getY(); 8806 8807 // Be lenient about moving outside of buttons 8808 if (!pointInView(x, y, mTouchSlop)) { 8809 // Outside button 8810 removeTapCallback(); 8811 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 8812 // Remove any future long press/tap checks 8813 removeLongPressCallback(); 8814 8815 setPressed(false); 8816 } 8817 } 8818 break; 8819 } 8820 return true; 8821 } 8822 8823 return false; 8824 } 8825 8826 /** 8827 * @hide 8828 */ 8829 public boolean isInScrollingContainer() { 8830 ViewParent p = getParent(); 8831 while (p != null && p instanceof ViewGroup) { 8832 if (((ViewGroup) p).shouldDelayChildPressedState()) { 8833 return true; 8834 } 8835 p = p.getParent(); 8836 } 8837 return false; 8838 } 8839 8840 /** 8841 * Remove the longpress detection timer. 8842 */ 8843 private void removeLongPressCallback() { 8844 if (mPendingCheckForLongPress != null) { 8845 removeCallbacks(mPendingCheckForLongPress); 8846 } 8847 } 8848 8849 /** 8850 * Remove the pending click action 8851 */ 8852 private void removePerformClickCallback() { 8853 if (mPerformClick != null) { 8854 removeCallbacks(mPerformClick); 8855 } 8856 } 8857 8858 /** 8859 * Remove the prepress detection timer. 8860 */ 8861 private void removeUnsetPressCallback() { 8862 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 8863 setPressed(false); 8864 removeCallbacks(mUnsetPressedState); 8865 } 8866 } 8867 8868 /** 8869 * Remove the tap detection timer. 8870 */ 8871 private void removeTapCallback() { 8872 if (mPendingCheckForTap != null) { 8873 mPrivateFlags &= ~PFLAG_PREPRESSED; 8874 removeCallbacks(mPendingCheckForTap); 8875 } 8876 } 8877 8878 /** 8879 * Cancels a pending long press. Your subclass can use this if you 8880 * want the context menu to come up if the user presses and holds 8881 * at the same place, but you don't want it to come up if they press 8882 * and then move around enough to cause scrolling. 8883 */ 8884 public void cancelLongPress() { 8885 removeLongPressCallback(); 8886 8887 /* 8888 * The prepressed state handled by the tap callback is a display 8889 * construct, but the tap callback will post a long press callback 8890 * less its own timeout. Remove it here. 8891 */ 8892 removeTapCallback(); 8893 } 8894 8895 /** 8896 * Remove the pending callback for sending a 8897 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 8898 */ 8899 private void removeSendViewScrolledAccessibilityEventCallback() { 8900 if (mSendViewScrolledAccessibilityEvent != null) { 8901 removeCallbacks(mSendViewScrolledAccessibilityEvent); 8902 mSendViewScrolledAccessibilityEvent.mIsPending = false; 8903 } 8904 } 8905 8906 /** 8907 * Sets the TouchDelegate for this View. 8908 */ 8909 public void setTouchDelegate(TouchDelegate delegate) { 8910 mTouchDelegate = delegate; 8911 } 8912 8913 /** 8914 * Gets the TouchDelegate for this View. 8915 */ 8916 public TouchDelegate getTouchDelegate() { 8917 return mTouchDelegate; 8918 } 8919 8920 /** 8921 * Set flags controlling behavior of this view. 8922 * 8923 * @param flags Constant indicating the value which should be set 8924 * @param mask Constant indicating the bit range that should be changed 8925 */ 8926 void setFlags(int flags, int mask) { 8927 final boolean accessibilityEnabled = 8928 AccessibilityManager.getInstance(mContext).isEnabled(); 8929 final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility(); 8930 8931 int old = mViewFlags; 8932 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 8933 8934 int changed = mViewFlags ^ old; 8935 if (changed == 0) { 8936 return; 8937 } 8938 int privateFlags = mPrivateFlags; 8939 8940 /* Check if the FOCUSABLE bit has changed */ 8941 if (((changed & FOCUSABLE_MASK) != 0) && 8942 ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) { 8943 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 8944 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 8945 /* Give up focus if we are no longer focusable */ 8946 clearFocus(); 8947 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 8948 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 8949 /* 8950 * Tell the view system that we are now available to take focus 8951 * if no one else already has it. 8952 */ 8953 if (mParent != null) mParent.focusableViewAvailable(this); 8954 } 8955 } 8956 8957 final int newVisibility = flags & VISIBILITY_MASK; 8958 if (newVisibility == VISIBLE) { 8959 if ((changed & VISIBILITY_MASK) != 0) { 8960 /* 8961 * If this view is becoming visible, invalidate it in case it changed while 8962 * it was not visible. Marking it drawn ensures that the invalidation will 8963 * go through. 8964 */ 8965 mPrivateFlags |= PFLAG_DRAWN; 8966 invalidate(true); 8967 8968 needGlobalAttributesUpdate(true); 8969 8970 // a view becoming visible is worth notifying the parent 8971 // about in case nothing has focus. even if this specific view 8972 // isn't focusable, it may contain something that is, so let 8973 // the root view try to give this focus if nothing else does. 8974 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 8975 mParent.focusableViewAvailable(this); 8976 } 8977 } 8978 } 8979 8980 /* Check if the GONE bit has changed */ 8981 if ((changed & GONE) != 0) { 8982 needGlobalAttributesUpdate(false); 8983 requestLayout(); 8984 8985 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 8986 if (hasFocus()) clearFocus(); 8987 clearAccessibilityFocus(); 8988 destroyDrawingCache(); 8989 if (mParent instanceof View) { 8990 // GONE views noop invalidation, so invalidate the parent 8991 ((View) mParent).invalidate(true); 8992 } 8993 // Mark the view drawn to ensure that it gets invalidated properly the next 8994 // time it is visible and gets invalidated 8995 mPrivateFlags |= PFLAG_DRAWN; 8996 } 8997 if (mAttachInfo != null) { 8998 mAttachInfo.mViewVisibilityChanged = true; 8999 } 9000 } 9001 9002 /* Check if the VISIBLE bit has changed */ 9003 if ((changed & INVISIBLE) != 0) { 9004 needGlobalAttributesUpdate(false); 9005 /* 9006 * If this view is becoming invisible, set the DRAWN flag so that 9007 * the next invalidate() will not be skipped. 9008 */ 9009 mPrivateFlags |= PFLAG_DRAWN; 9010 9011 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) { 9012 // root view becoming invisible shouldn't clear focus and accessibility focus 9013 if (getRootView() != this) { 9014 clearFocus(); 9015 clearAccessibilityFocus(); 9016 } 9017 } 9018 if (mAttachInfo != null) { 9019 mAttachInfo.mViewVisibilityChanged = true; 9020 } 9021 } 9022 9023 if ((changed & VISIBILITY_MASK) != 0) { 9024 // If the view is invisible, cleanup its display list to free up resources 9025 if (newVisibility != VISIBLE) { 9026 cleanupDraw(); 9027 } 9028 9029 if (mParent instanceof ViewGroup) { 9030 ((ViewGroup) mParent).onChildVisibilityChanged(this, 9031 (changed & VISIBILITY_MASK), newVisibility); 9032 ((View) mParent).invalidate(true); 9033 } else if (mParent != null) { 9034 mParent.invalidateChild(this, null); 9035 } 9036 dispatchVisibilityChanged(this, newVisibility); 9037 } 9038 9039 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 9040 destroyDrawingCache(); 9041 } 9042 9043 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 9044 destroyDrawingCache(); 9045 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9046 invalidateParentCaches(); 9047 } 9048 9049 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 9050 destroyDrawingCache(); 9051 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9052 } 9053 9054 if ((changed & DRAW_MASK) != 0) { 9055 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 9056 if (mBackground != null) { 9057 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9058 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 9059 } else { 9060 mPrivateFlags |= PFLAG_SKIP_DRAW; 9061 } 9062 } else { 9063 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9064 } 9065 requestLayout(); 9066 invalidate(true); 9067 } 9068 9069 if ((changed & KEEP_SCREEN_ON) != 0) { 9070 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 9071 mParent.recomputeViewAttributes(this); 9072 } 9073 } 9074 9075 if (accessibilityEnabled) { 9076 if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0 9077 || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) { 9078 if (oldIncludeForAccessibility != includeForAccessibility()) { 9079 notifySubtreeAccessibilityStateChangedIfNeeded(); 9080 } else { 9081 notifyViewAccessibilityStateChangedIfNeeded( 9082 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9083 } 9084 } else if ((changed & ENABLED_MASK) != 0) { 9085 notifyViewAccessibilityStateChangedIfNeeded( 9086 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9087 } 9088 } 9089 } 9090 9091 /** 9092 * Change the view's z order in the tree, so it's on top of other sibling 9093 * views. This ordering change may affect layout, if the parent container 9094 * uses an order-dependent layout scheme (e.g., LinearLayout). Prior 9095 * to {@link android.os.Build.VERSION_CODES#KITKAT} this 9096 * method should be followed by calls to {@link #requestLayout()} and 9097 * {@link View#invalidate()} on the view's parent to force the parent to redraw 9098 * with the new child ordering. 9099 * 9100 * @see ViewGroup#bringChildToFront(View) 9101 */ 9102 public void bringToFront() { 9103 if (mParent != null) { 9104 mParent.bringChildToFront(this); 9105 } 9106 } 9107 9108 /** 9109 * This is called in response to an internal scroll in this view (i.e., the 9110 * view scrolled its own contents). This is typically as a result of 9111 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 9112 * called. 9113 * 9114 * @param l Current horizontal scroll origin. 9115 * @param t Current vertical scroll origin. 9116 * @param oldl Previous horizontal scroll origin. 9117 * @param oldt Previous vertical scroll origin. 9118 */ 9119 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 9120 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 9121 postSendViewScrolledAccessibilityEventCallback(); 9122 } 9123 9124 mBackgroundSizeChanged = true; 9125 9126 final AttachInfo ai = mAttachInfo; 9127 if (ai != null) { 9128 ai.mViewScrollChanged = true; 9129 } 9130 } 9131 9132 /** 9133 * Interface definition for a callback to be invoked when the layout bounds of a view 9134 * changes due to layout processing. 9135 */ 9136 public interface OnLayoutChangeListener { 9137 /** 9138 * Called when the focus state of a view has changed. 9139 * 9140 * @param v The view whose state has changed. 9141 * @param left The new value of the view's left property. 9142 * @param top The new value of the view's top property. 9143 * @param right The new value of the view's right property. 9144 * @param bottom The new value of the view's bottom property. 9145 * @param oldLeft The previous value of the view's left property. 9146 * @param oldTop The previous value of the view's top property. 9147 * @param oldRight The previous value of the view's right property. 9148 * @param oldBottom The previous value of the view's bottom property. 9149 */ 9150 void onLayoutChange(View v, int left, int top, int right, int bottom, 9151 int oldLeft, int oldTop, int oldRight, int oldBottom); 9152 } 9153 9154 /** 9155 * This is called during layout when the size of this view has changed. If 9156 * you were just added to the view hierarchy, you're called with the old 9157 * values of 0. 9158 * 9159 * @param w Current width of this view. 9160 * @param h Current height of this view. 9161 * @param oldw Old width of this view. 9162 * @param oldh Old height of this view. 9163 */ 9164 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 9165 } 9166 9167 /** 9168 * Called by draw to draw the child views. This may be overridden 9169 * by derived classes to gain control just before its children are drawn 9170 * (but after its own view has been drawn). 9171 * @param canvas the canvas on which to draw the view 9172 */ 9173 protected void dispatchDraw(Canvas canvas) { 9174 9175 } 9176 9177 /** 9178 * Gets the parent of this view. Note that the parent is a 9179 * ViewParent and not necessarily a View. 9180 * 9181 * @return Parent of this view. 9182 */ 9183 public final ViewParent getParent() { 9184 return mParent; 9185 } 9186 9187 /** 9188 * Set the horizontal scrolled position of your view. This will cause a call to 9189 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9190 * invalidated. 9191 * @param value the x position to scroll to 9192 */ 9193 public void setScrollX(int value) { 9194 scrollTo(value, mScrollY); 9195 } 9196 9197 /** 9198 * Set the vertical scrolled position of your view. This will cause a call to 9199 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9200 * invalidated. 9201 * @param value the y position to scroll to 9202 */ 9203 public void setScrollY(int value) { 9204 scrollTo(mScrollX, value); 9205 } 9206 9207 /** 9208 * Return the scrolled left position of this view. This is the left edge of 9209 * the displayed part of your view. You do not need to draw any pixels 9210 * farther left, since those are outside of the frame of your view on 9211 * screen. 9212 * 9213 * @return The left edge of the displayed part of your view, in pixels. 9214 */ 9215 public final int getScrollX() { 9216 return mScrollX; 9217 } 9218 9219 /** 9220 * Return the scrolled top position of this view. This is the top edge of 9221 * the displayed part of your view. You do not need to draw any pixels above 9222 * it, since those are outside of the frame of your view on screen. 9223 * 9224 * @return The top edge of the displayed part of your view, in pixels. 9225 */ 9226 public final int getScrollY() { 9227 return mScrollY; 9228 } 9229 9230 /** 9231 * Return the width of the your view. 9232 * 9233 * @return The width of your view, in pixels. 9234 */ 9235 @ViewDebug.ExportedProperty(category = "layout") 9236 public final int getWidth() { 9237 return mRight - mLeft; 9238 } 9239 9240 /** 9241 * Return the height of your view. 9242 * 9243 * @return The height of your view, in pixels. 9244 */ 9245 @ViewDebug.ExportedProperty(category = "layout") 9246 public final int getHeight() { 9247 return mBottom - mTop; 9248 } 9249 9250 /** 9251 * Return the visible drawing bounds of your view. Fills in the output 9252 * rectangle with the values from getScrollX(), getScrollY(), 9253 * getWidth(), and getHeight(). These bounds do not account for any 9254 * transformation properties currently set on the view, such as 9255 * {@link #setScaleX(float)} or {@link #setRotation(float)}. 9256 * 9257 * @param outRect The (scrolled) drawing bounds of the view. 9258 */ 9259 public void getDrawingRect(Rect outRect) { 9260 outRect.left = mScrollX; 9261 outRect.top = mScrollY; 9262 outRect.right = mScrollX + (mRight - mLeft); 9263 outRect.bottom = mScrollY + (mBottom - mTop); 9264 } 9265 9266 /** 9267 * Like {@link #getMeasuredWidthAndState()}, but only returns the 9268 * raw width component (that is the result is masked by 9269 * {@link #MEASURED_SIZE_MASK}). 9270 * 9271 * @return The raw measured width of this view. 9272 */ 9273 public final int getMeasuredWidth() { 9274 return mMeasuredWidth & MEASURED_SIZE_MASK; 9275 } 9276 9277 /** 9278 * Return the full width measurement information for this view as computed 9279 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 9280 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 9281 * This should be used during measurement and layout calculations only. Use 9282 * {@link #getWidth()} to see how wide a view is after layout. 9283 * 9284 * @return The measured width of this view as a bit mask. 9285 */ 9286 public final int getMeasuredWidthAndState() { 9287 return mMeasuredWidth; 9288 } 9289 9290 /** 9291 * Like {@link #getMeasuredHeightAndState()}, but only returns the 9292 * raw width component (that is the result is masked by 9293 * {@link #MEASURED_SIZE_MASK}). 9294 * 9295 * @return The raw measured height of this view. 9296 */ 9297 public final int getMeasuredHeight() { 9298 return mMeasuredHeight & MEASURED_SIZE_MASK; 9299 } 9300 9301 /** 9302 * Return the full height measurement information for this view as computed 9303 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 9304 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 9305 * This should be used during measurement and layout calculations only. Use 9306 * {@link #getHeight()} to see how wide a view is after layout. 9307 * 9308 * @return The measured width of this view as a bit mask. 9309 */ 9310 public final int getMeasuredHeightAndState() { 9311 return mMeasuredHeight; 9312 } 9313 9314 /** 9315 * Return only the state bits of {@link #getMeasuredWidthAndState()} 9316 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 9317 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 9318 * and the height component is at the shifted bits 9319 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 9320 */ 9321 public final int getMeasuredState() { 9322 return (mMeasuredWidth&MEASURED_STATE_MASK) 9323 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 9324 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 9325 } 9326 9327 /** 9328 * The transform matrix of this view, which is calculated based on the current 9329 * roation, scale, and pivot properties. 9330 * 9331 * @see #getRotation() 9332 * @see #getScaleX() 9333 * @see #getScaleY() 9334 * @see #getPivotX() 9335 * @see #getPivotY() 9336 * @return The current transform matrix for the view 9337 */ 9338 public Matrix getMatrix() { 9339 if (mTransformationInfo != null) { 9340 updateMatrix(); 9341 return mTransformationInfo.mMatrix; 9342 } 9343 return Matrix.IDENTITY_MATRIX; 9344 } 9345 9346 /** 9347 * Utility function to determine if the value is far enough away from zero to be 9348 * considered non-zero. 9349 * @param value A floating point value to check for zero-ness 9350 * @return whether the passed-in value is far enough away from zero to be considered non-zero 9351 */ 9352 private static boolean nonzero(float value) { 9353 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON); 9354 } 9355 9356 /** 9357 * Returns true if the transform matrix is the identity matrix. 9358 * Recomputes the matrix if necessary. 9359 * 9360 * @return True if the transform matrix is the identity matrix, false otherwise. 9361 */ 9362 final boolean hasIdentityMatrix() { 9363 if (mTransformationInfo != null) { 9364 updateMatrix(); 9365 return mTransformationInfo.mMatrixIsIdentity; 9366 } 9367 return true; 9368 } 9369 9370 void ensureTransformationInfo() { 9371 if (mTransformationInfo == null) { 9372 mTransformationInfo = new TransformationInfo(); 9373 } 9374 } 9375 9376 /** 9377 * Recomputes the transform matrix if necessary. 9378 */ 9379 private void updateMatrix() { 9380 final TransformationInfo info = mTransformationInfo; 9381 if (info == null) { 9382 return; 9383 } 9384 if (info.mMatrixDirty) { 9385 // transform-related properties have changed since the last time someone 9386 // asked for the matrix; recalculate it with the current values 9387 9388 // Figure out if we need to update the pivot point 9389 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 9390 if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) { 9391 info.mPrevWidth = mRight - mLeft; 9392 info.mPrevHeight = mBottom - mTop; 9393 info.mPivotX = info.mPrevWidth / 2f; 9394 info.mPivotY = info.mPrevHeight / 2f; 9395 } 9396 } 9397 info.mMatrix.reset(); 9398 if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) { 9399 info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY); 9400 info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY); 9401 info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY); 9402 } else { 9403 if (info.mCamera == null) { 9404 info.mCamera = new Camera(); 9405 info.matrix3D = new Matrix(); 9406 } 9407 info.mCamera.save(); 9408 info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY); 9409 info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation); 9410 info.mCamera.getMatrix(info.matrix3D); 9411 info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY); 9412 info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX, 9413 info.mPivotY + info.mTranslationY); 9414 info.mMatrix.postConcat(info.matrix3D); 9415 info.mCamera.restore(); 9416 } 9417 info.mMatrixDirty = false; 9418 info.mMatrixIsIdentity = info.mMatrix.isIdentity(); 9419 info.mInverseMatrixDirty = true; 9420 } 9421 } 9422 9423 /** 9424 * Utility method to retrieve the inverse of the current mMatrix property. 9425 * We cache the matrix to avoid recalculating it when transform properties 9426 * have not changed. 9427 * 9428 * @return The inverse of the current matrix of this view. 9429 */ 9430 final Matrix getInverseMatrix() { 9431 final TransformationInfo info = mTransformationInfo; 9432 if (info != null) { 9433 updateMatrix(); 9434 if (info.mInverseMatrixDirty) { 9435 if (info.mInverseMatrix == null) { 9436 info.mInverseMatrix = new Matrix(); 9437 } 9438 info.mMatrix.invert(info.mInverseMatrix); 9439 info.mInverseMatrixDirty = false; 9440 } 9441 return info.mInverseMatrix; 9442 } 9443 return Matrix.IDENTITY_MATRIX; 9444 } 9445 9446 /** 9447 * Gets the distance along the Z axis from the camera to this view. 9448 * 9449 * @see #setCameraDistance(float) 9450 * 9451 * @return The distance along the Z axis. 9452 */ 9453 public float getCameraDistance() { 9454 ensureTransformationInfo(); 9455 final float dpi = mResources.getDisplayMetrics().densityDpi; 9456 final TransformationInfo info = mTransformationInfo; 9457 if (info.mCamera == null) { 9458 info.mCamera = new Camera(); 9459 info.matrix3D = new Matrix(); 9460 } 9461 return -(info.mCamera.getLocationZ() * dpi); 9462 } 9463 9464 /** 9465 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 9466 * views are drawn) from the camera to this view. The camera's distance 9467 * affects 3D transformations, for instance rotations around the X and Y 9468 * axis. If the rotationX or rotationY properties are changed and this view is 9469 * large (more than half the size of the screen), it is recommended to always 9470 * use a camera distance that's greater than the height (X axis rotation) or 9471 * the width (Y axis rotation) of this view.</p> 9472 * 9473 * <p>The distance of the camera from the view plane can have an affect on the 9474 * perspective distortion of the view when it is rotated around the x or y axis. 9475 * For example, a large distance will result in a large viewing angle, and there 9476 * will not be much perspective distortion of the view as it rotates. A short 9477 * distance may cause much more perspective distortion upon rotation, and can 9478 * also result in some drawing artifacts if the rotated view ends up partially 9479 * behind the camera (which is why the recommendation is to use a distance at 9480 * least as far as the size of the view, if the view is to be rotated.)</p> 9481 * 9482 * <p>The distance is expressed in "depth pixels." The default distance depends 9483 * on the screen density. For instance, on a medium density display, the 9484 * default distance is 1280. On a high density display, the default distance 9485 * is 1920.</p> 9486 * 9487 * <p>If you want to specify a distance that leads to visually consistent 9488 * results across various densities, use the following formula:</p> 9489 * <pre> 9490 * float scale = context.getResources().getDisplayMetrics().density; 9491 * view.setCameraDistance(distance * scale); 9492 * </pre> 9493 * 9494 * <p>The density scale factor of a high density display is 1.5, 9495 * and 1920 = 1280 * 1.5.</p> 9496 * 9497 * @param distance The distance in "depth pixels", if negative the opposite 9498 * value is used 9499 * 9500 * @see #setRotationX(float) 9501 * @see #setRotationY(float) 9502 */ 9503 public void setCameraDistance(float distance) { 9504 invalidateViewProperty(true, false); 9505 9506 ensureTransformationInfo(); 9507 final float dpi = mResources.getDisplayMetrics().densityDpi; 9508 final TransformationInfo info = mTransformationInfo; 9509 if (info.mCamera == null) { 9510 info.mCamera = new Camera(); 9511 info.matrix3D = new Matrix(); 9512 } 9513 9514 info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi); 9515 info.mMatrixDirty = true; 9516 9517 invalidateViewProperty(false, false); 9518 if (mDisplayList != null) { 9519 mDisplayList.setCameraDistance(-Math.abs(distance) / dpi); 9520 } 9521 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9522 // View was rejected last time it was drawn by its parent; this may have changed 9523 invalidateParentIfNeeded(); 9524 } 9525 } 9526 9527 /** 9528 * The degrees that the view is rotated around the pivot point. 9529 * 9530 * @see #setRotation(float) 9531 * @see #getPivotX() 9532 * @see #getPivotY() 9533 * 9534 * @return The degrees of rotation. 9535 */ 9536 @ViewDebug.ExportedProperty(category = "drawing") 9537 public float getRotation() { 9538 return mTransformationInfo != null ? mTransformationInfo.mRotation : 0; 9539 } 9540 9541 /** 9542 * Sets the degrees that the view is rotated around the pivot point. Increasing values 9543 * result in clockwise rotation. 9544 * 9545 * @param rotation The degrees of rotation. 9546 * 9547 * @see #getRotation() 9548 * @see #getPivotX() 9549 * @see #getPivotY() 9550 * @see #setRotationX(float) 9551 * @see #setRotationY(float) 9552 * 9553 * @attr ref android.R.styleable#View_rotation 9554 */ 9555 public void setRotation(float rotation) { 9556 ensureTransformationInfo(); 9557 final TransformationInfo info = mTransformationInfo; 9558 if (info.mRotation != rotation) { 9559 // Double-invalidation is necessary to capture view's old and new areas 9560 invalidateViewProperty(true, false); 9561 info.mRotation = rotation; 9562 info.mMatrixDirty = true; 9563 invalidateViewProperty(false, true); 9564 if (mDisplayList != null) { 9565 mDisplayList.setRotation(rotation); 9566 } 9567 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9568 // View was rejected last time it was drawn by its parent; this may have changed 9569 invalidateParentIfNeeded(); 9570 } 9571 } 9572 } 9573 9574 /** 9575 * The degrees that the view is rotated around the vertical axis through the pivot point. 9576 * 9577 * @see #getPivotX() 9578 * @see #getPivotY() 9579 * @see #setRotationY(float) 9580 * 9581 * @return The degrees of Y rotation. 9582 */ 9583 @ViewDebug.ExportedProperty(category = "drawing") 9584 public float getRotationY() { 9585 return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0; 9586 } 9587 9588 /** 9589 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 9590 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 9591 * down the y axis. 9592 * 9593 * When rotating large views, it is recommended to adjust the camera distance 9594 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 9595 * 9596 * @param rotationY The degrees of Y rotation. 9597 * 9598 * @see #getRotationY() 9599 * @see #getPivotX() 9600 * @see #getPivotY() 9601 * @see #setRotation(float) 9602 * @see #setRotationX(float) 9603 * @see #setCameraDistance(float) 9604 * 9605 * @attr ref android.R.styleable#View_rotationY 9606 */ 9607 public void setRotationY(float rotationY) { 9608 ensureTransformationInfo(); 9609 final TransformationInfo info = mTransformationInfo; 9610 if (info.mRotationY != rotationY) { 9611 invalidateViewProperty(true, false); 9612 info.mRotationY = rotationY; 9613 info.mMatrixDirty = true; 9614 invalidateViewProperty(false, true); 9615 if (mDisplayList != null) { 9616 mDisplayList.setRotationY(rotationY); 9617 } 9618 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9619 // View was rejected last time it was drawn by its parent; this may have changed 9620 invalidateParentIfNeeded(); 9621 } 9622 } 9623 } 9624 9625 /** 9626 * The degrees that the view is rotated around the horizontal axis through the pivot point. 9627 * 9628 * @see #getPivotX() 9629 * @see #getPivotY() 9630 * @see #setRotationX(float) 9631 * 9632 * @return The degrees of X rotation. 9633 */ 9634 @ViewDebug.ExportedProperty(category = "drawing") 9635 public float getRotationX() { 9636 return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0; 9637 } 9638 9639 /** 9640 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 9641 * Increasing values result in clockwise rotation from the viewpoint of looking down the 9642 * x axis. 9643 * 9644 * When rotating large views, it is recommended to adjust the camera distance 9645 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 9646 * 9647 * @param rotationX The degrees of X rotation. 9648 * 9649 * @see #getRotationX() 9650 * @see #getPivotX() 9651 * @see #getPivotY() 9652 * @see #setRotation(float) 9653 * @see #setRotationY(float) 9654 * @see #setCameraDistance(float) 9655 * 9656 * @attr ref android.R.styleable#View_rotationX 9657 */ 9658 public void setRotationX(float rotationX) { 9659 ensureTransformationInfo(); 9660 final TransformationInfo info = mTransformationInfo; 9661 if (info.mRotationX != rotationX) { 9662 invalidateViewProperty(true, false); 9663 info.mRotationX = rotationX; 9664 info.mMatrixDirty = true; 9665 invalidateViewProperty(false, true); 9666 if (mDisplayList != null) { 9667 mDisplayList.setRotationX(rotationX); 9668 } 9669 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9670 // View was rejected last time it was drawn by its parent; this may have changed 9671 invalidateParentIfNeeded(); 9672 } 9673 } 9674 } 9675 9676 /** 9677 * The amount that the view is scaled in x around the pivot point, as a proportion of 9678 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 9679 * 9680 * <p>By default, this is 1.0f. 9681 * 9682 * @see #getPivotX() 9683 * @see #getPivotY() 9684 * @return The scaling factor. 9685 */ 9686 @ViewDebug.ExportedProperty(category = "drawing") 9687 public float getScaleX() { 9688 return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1; 9689 } 9690 9691 /** 9692 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 9693 * the view's unscaled width. A value of 1 means that no scaling is applied. 9694 * 9695 * @param scaleX The scaling factor. 9696 * @see #getPivotX() 9697 * @see #getPivotY() 9698 * 9699 * @attr ref android.R.styleable#View_scaleX 9700 */ 9701 public void setScaleX(float scaleX) { 9702 ensureTransformationInfo(); 9703 final TransformationInfo info = mTransformationInfo; 9704 if (info.mScaleX != scaleX) { 9705 invalidateViewProperty(true, false); 9706 info.mScaleX = scaleX; 9707 info.mMatrixDirty = true; 9708 invalidateViewProperty(false, true); 9709 if (mDisplayList != null) { 9710 mDisplayList.setScaleX(scaleX); 9711 } 9712 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9713 // View was rejected last time it was drawn by its parent; this may have changed 9714 invalidateParentIfNeeded(); 9715 } 9716 } 9717 } 9718 9719 /** 9720 * The amount that the view is scaled in y around the pivot point, as a proportion of 9721 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 9722 * 9723 * <p>By default, this is 1.0f. 9724 * 9725 * @see #getPivotX() 9726 * @see #getPivotY() 9727 * @return The scaling factor. 9728 */ 9729 @ViewDebug.ExportedProperty(category = "drawing") 9730 public float getScaleY() { 9731 return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1; 9732 } 9733 9734 /** 9735 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 9736 * the view's unscaled width. A value of 1 means that no scaling is applied. 9737 * 9738 * @param scaleY The scaling factor. 9739 * @see #getPivotX() 9740 * @see #getPivotY() 9741 * 9742 * @attr ref android.R.styleable#View_scaleY 9743 */ 9744 public void setScaleY(float scaleY) { 9745 ensureTransformationInfo(); 9746 final TransformationInfo info = mTransformationInfo; 9747 if (info.mScaleY != scaleY) { 9748 invalidateViewProperty(true, false); 9749 info.mScaleY = scaleY; 9750 info.mMatrixDirty = true; 9751 invalidateViewProperty(false, true); 9752 if (mDisplayList != null) { 9753 mDisplayList.setScaleY(scaleY); 9754 } 9755 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9756 // View was rejected last time it was drawn by its parent; this may have changed 9757 invalidateParentIfNeeded(); 9758 } 9759 } 9760 } 9761 9762 /** 9763 * The x location of the point around which the view is {@link #setRotation(float) rotated} 9764 * and {@link #setScaleX(float) scaled}. 9765 * 9766 * @see #getRotation() 9767 * @see #getScaleX() 9768 * @see #getScaleY() 9769 * @see #getPivotY() 9770 * @return The x location of the pivot point. 9771 * 9772 * @attr ref android.R.styleable#View_transformPivotX 9773 */ 9774 @ViewDebug.ExportedProperty(category = "drawing") 9775 public float getPivotX() { 9776 return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0; 9777 } 9778 9779 /** 9780 * Sets the x location of the point around which the view is 9781 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 9782 * By default, the pivot point is centered on the object. 9783 * Setting this property disables this behavior and causes the view to use only the 9784 * explicitly set pivotX and pivotY values. 9785 * 9786 * @param pivotX The x location of the pivot point. 9787 * @see #getRotation() 9788 * @see #getScaleX() 9789 * @see #getScaleY() 9790 * @see #getPivotY() 9791 * 9792 * @attr ref android.R.styleable#View_transformPivotX 9793 */ 9794 public void setPivotX(float pivotX) { 9795 ensureTransformationInfo(); 9796 final TransformationInfo info = mTransformationInfo; 9797 boolean pivotSet = (mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 9798 PFLAG_PIVOT_EXPLICITLY_SET; 9799 if (info.mPivotX != pivotX || !pivotSet) { 9800 mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET; 9801 invalidateViewProperty(true, false); 9802 info.mPivotX = pivotX; 9803 info.mMatrixDirty = true; 9804 invalidateViewProperty(false, true); 9805 if (mDisplayList != null) { 9806 mDisplayList.setPivotX(pivotX); 9807 } 9808 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9809 // View was rejected last time it was drawn by its parent; this may have changed 9810 invalidateParentIfNeeded(); 9811 } 9812 } 9813 } 9814 9815 /** 9816 * The y location of the point around which the view is {@link #setRotation(float) rotated} 9817 * and {@link #setScaleY(float) scaled}. 9818 * 9819 * @see #getRotation() 9820 * @see #getScaleX() 9821 * @see #getScaleY() 9822 * @see #getPivotY() 9823 * @return The y location of the pivot point. 9824 * 9825 * @attr ref android.R.styleable#View_transformPivotY 9826 */ 9827 @ViewDebug.ExportedProperty(category = "drawing") 9828 public float getPivotY() { 9829 return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0; 9830 } 9831 9832 /** 9833 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 9834 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 9835 * Setting this property disables this behavior and causes the view to use only the 9836 * explicitly set pivotX and pivotY values. 9837 * 9838 * @param pivotY The y location of the pivot point. 9839 * @see #getRotation() 9840 * @see #getScaleX() 9841 * @see #getScaleY() 9842 * @see #getPivotY() 9843 * 9844 * @attr ref android.R.styleable#View_transformPivotY 9845 */ 9846 public void setPivotY(float pivotY) { 9847 ensureTransformationInfo(); 9848 final TransformationInfo info = mTransformationInfo; 9849 boolean pivotSet = (mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 9850 PFLAG_PIVOT_EXPLICITLY_SET; 9851 if (info.mPivotY != pivotY || !pivotSet) { 9852 mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET; 9853 invalidateViewProperty(true, false); 9854 info.mPivotY = pivotY; 9855 info.mMatrixDirty = true; 9856 invalidateViewProperty(false, true); 9857 if (mDisplayList != null) { 9858 mDisplayList.setPivotY(pivotY); 9859 } 9860 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9861 // View was rejected last time it was drawn by its parent; this may have changed 9862 invalidateParentIfNeeded(); 9863 } 9864 } 9865 } 9866 9867 /** 9868 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 9869 * completely transparent and 1 means the view is completely opaque. 9870 * 9871 * <p>By default this is 1.0f. 9872 * @return The opacity of the view. 9873 */ 9874 @ViewDebug.ExportedProperty(category = "drawing") 9875 public float getAlpha() { 9876 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 9877 } 9878 9879 /** 9880 * Returns whether this View has content which overlaps. This function, intended to be 9881 * overridden by specific View types, is an optimization when alpha is set on a view. If 9882 * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer 9883 * and then composited it into place, which can be expensive. If the view has no overlapping 9884 * rendering, the view can draw each primitive with the appropriate alpha value directly. 9885 * An example of overlapping rendering is a TextView with a background image, such as a 9886 * Button. An example of non-overlapping rendering is a TextView with no background, or 9887 * an ImageView with only the foreground image. The default implementation returns true; 9888 * subclasses should override if they have cases which can be optimized. 9889 * 9890 * @return true if the content in this view might overlap, false otherwise. 9891 */ 9892 public boolean hasOverlappingRendering() { 9893 return true; 9894 } 9895 9896 /** 9897 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 9898 * completely transparent and 1 means the view is completely opaque.</p> 9899 * 9900 * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant 9901 * performance implications, especially for large views. It is best to use the alpha property 9902 * sparingly and transiently, as in the case of fading animations.</p> 9903 * 9904 * <p>For a view with a frequently changing alpha, such as during a fading animation, it is 9905 * strongly recommended for performance reasons to either override 9906 * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a 9907 * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p> 9908 * 9909 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 9910 * responsible for applying the opacity itself.</p> 9911 * 9912 * <p>Note that if the view is backed by a 9913 * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a 9914 * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than 9915 * 1.0 will supercede the alpha of the layer paint.</p> 9916 * 9917 * @param alpha The opacity of the view. 9918 * 9919 * @see #hasOverlappingRendering() 9920 * @see #setLayerType(int, android.graphics.Paint) 9921 * 9922 * @attr ref android.R.styleable#View_alpha 9923 */ 9924 public void setAlpha(float alpha) { 9925 ensureTransformationInfo(); 9926 if (mTransformationInfo.mAlpha != alpha) { 9927 mTransformationInfo.mAlpha = alpha; 9928 if (onSetAlpha((int) (alpha * 255))) { 9929 mPrivateFlags |= PFLAG_ALPHA_SET; 9930 // subclass is handling alpha - don't optimize rendering cache invalidation 9931 invalidateParentCaches(); 9932 invalidate(true); 9933 } else { 9934 mPrivateFlags &= ~PFLAG_ALPHA_SET; 9935 invalidateViewProperty(true, false); 9936 if (mDisplayList != null) { 9937 mDisplayList.setAlpha(getFinalAlpha()); 9938 } 9939 } 9940 } 9941 } 9942 9943 /** 9944 * Faster version of setAlpha() which performs the same steps except there are 9945 * no calls to invalidate(). The caller of this function should perform proper invalidation 9946 * on the parent and this object. The return value indicates whether the subclass handles 9947 * alpha (the return value for onSetAlpha()). 9948 * 9949 * @param alpha The new value for the alpha property 9950 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 9951 * the new value for the alpha property is different from the old value 9952 */ 9953 boolean setAlphaNoInvalidation(float alpha) { 9954 ensureTransformationInfo(); 9955 if (mTransformationInfo.mAlpha != alpha) { 9956 mTransformationInfo.mAlpha = alpha; 9957 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 9958 if (subclassHandlesAlpha) { 9959 mPrivateFlags |= PFLAG_ALPHA_SET; 9960 return true; 9961 } else { 9962 mPrivateFlags &= ~PFLAG_ALPHA_SET; 9963 if (mDisplayList != null) { 9964 mDisplayList.setAlpha(getFinalAlpha()); 9965 } 9966 } 9967 } 9968 return false; 9969 } 9970 9971 /** 9972 * This property is hidden and intended only for use by the Fade transition, which 9973 * animates it to produce a visual translucency that does not side-effect (or get 9974 * affected by) the real alpha property. This value is composited with the other 9975 * alpha value (and the AlphaAnimation value, when that is present) to produce 9976 * a final visual translucency result, which is what is passed into the DisplayList. 9977 * 9978 * @hide 9979 */ 9980 public void setTransitionAlpha(float alpha) { 9981 ensureTransformationInfo(); 9982 if (mTransformationInfo.mTransitionAlpha != alpha) { 9983 mTransformationInfo.mTransitionAlpha = alpha; 9984 mPrivateFlags &= ~PFLAG_ALPHA_SET; 9985 invalidateViewProperty(true, false); 9986 if (mDisplayList != null) { 9987 mDisplayList.setAlpha(getFinalAlpha()); 9988 } 9989 } 9990 } 9991 9992 /** 9993 * Calculates the visual alpha of this view, which is a combination of the actual 9994 * alpha value and the transitionAlpha value (if set). 9995 */ 9996 private float getFinalAlpha() { 9997 if (mTransformationInfo != null) { 9998 return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha; 9999 } 10000 return 1; 10001 } 10002 10003 /** 10004 * This property is hidden and intended only for use by the Fade transition, which 10005 * animates it to produce a visual translucency that does not side-effect (or get 10006 * affected by) the real alpha property. This value is composited with the other 10007 * alpha value (and the AlphaAnimation value, when that is present) to produce 10008 * a final visual translucency result, which is what is passed into the DisplayList. 10009 * 10010 * @hide 10011 */ 10012 public float getTransitionAlpha() { 10013 return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1; 10014 } 10015 10016 /** 10017 * Top position of this view relative to its parent. 10018 * 10019 * @return The top of this view, in pixels. 10020 */ 10021 @ViewDebug.CapturedViewProperty 10022 public final int getTop() { 10023 return mTop; 10024 } 10025 10026 /** 10027 * Sets the top position of this view relative to its parent. This method is meant to be called 10028 * by the layout system and should not generally be called otherwise, because the property 10029 * may be changed at any time by the layout. 10030 * 10031 * @param top The top of this view, in pixels. 10032 */ 10033 public final void setTop(int top) { 10034 if (top != mTop) { 10035 updateMatrix(); 10036 final boolean matrixIsIdentity = mTransformationInfo == null 10037 || mTransformationInfo.mMatrixIsIdentity; 10038 if (matrixIsIdentity) { 10039 if (mAttachInfo != null) { 10040 int minTop; 10041 int yLoc; 10042 if (top < mTop) { 10043 minTop = top; 10044 yLoc = top - mTop; 10045 } else { 10046 minTop = mTop; 10047 yLoc = 0; 10048 } 10049 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 10050 } 10051 } else { 10052 // Double-invalidation is necessary to capture view's old and new areas 10053 invalidate(true); 10054 } 10055 10056 int width = mRight - mLeft; 10057 int oldHeight = mBottom - mTop; 10058 10059 mTop = top; 10060 if (mDisplayList != null) { 10061 mDisplayList.setTop(mTop); 10062 } 10063 10064 sizeChange(width, mBottom - mTop, width, oldHeight); 10065 10066 if (!matrixIsIdentity) { 10067 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 10068 // A change in dimension means an auto-centered pivot point changes, too 10069 mTransformationInfo.mMatrixDirty = true; 10070 } 10071 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10072 invalidate(true); 10073 } 10074 mBackgroundSizeChanged = true; 10075 invalidateParentIfNeeded(); 10076 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10077 // View was rejected last time it was drawn by its parent; this may have changed 10078 invalidateParentIfNeeded(); 10079 } 10080 } 10081 } 10082 10083 /** 10084 * Bottom position of this view relative to its parent. 10085 * 10086 * @return The bottom of this view, in pixels. 10087 */ 10088 @ViewDebug.CapturedViewProperty 10089 public final int getBottom() { 10090 return mBottom; 10091 } 10092 10093 /** 10094 * True if this view has changed since the last time being drawn. 10095 * 10096 * @return The dirty state of this view. 10097 */ 10098 public boolean isDirty() { 10099 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 10100 } 10101 10102 /** 10103 * Sets the bottom position of this view relative to its parent. This method is meant to be 10104 * called by the layout system and should not generally be called otherwise, because the 10105 * property may be changed at any time by the layout. 10106 * 10107 * @param bottom The bottom of this view, in pixels. 10108 */ 10109 public final void setBottom(int bottom) { 10110 if (bottom != mBottom) { 10111 updateMatrix(); 10112 final boolean matrixIsIdentity = mTransformationInfo == null 10113 || mTransformationInfo.mMatrixIsIdentity; 10114 if (matrixIsIdentity) { 10115 if (mAttachInfo != null) { 10116 int maxBottom; 10117 if (bottom < mBottom) { 10118 maxBottom = mBottom; 10119 } else { 10120 maxBottom = bottom; 10121 } 10122 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 10123 } 10124 } else { 10125 // Double-invalidation is necessary to capture view's old and new areas 10126 invalidate(true); 10127 } 10128 10129 int width = mRight - mLeft; 10130 int oldHeight = mBottom - mTop; 10131 10132 mBottom = bottom; 10133 if (mDisplayList != null) { 10134 mDisplayList.setBottom(mBottom); 10135 } 10136 10137 sizeChange(width, mBottom - mTop, width, oldHeight); 10138 10139 if (!matrixIsIdentity) { 10140 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 10141 // A change in dimension means an auto-centered pivot point changes, too 10142 mTransformationInfo.mMatrixDirty = true; 10143 } 10144 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10145 invalidate(true); 10146 } 10147 mBackgroundSizeChanged = true; 10148 invalidateParentIfNeeded(); 10149 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10150 // View was rejected last time it was drawn by its parent; this may have changed 10151 invalidateParentIfNeeded(); 10152 } 10153 } 10154 } 10155 10156 /** 10157 * Left position of this view relative to its parent. 10158 * 10159 * @return The left edge of this view, in pixels. 10160 */ 10161 @ViewDebug.CapturedViewProperty 10162 public final int getLeft() { 10163 return mLeft; 10164 } 10165 10166 /** 10167 * Sets the left position of this view relative to its parent. This method is meant to be called 10168 * by the layout system and should not generally be called otherwise, because the property 10169 * may be changed at any time by the layout. 10170 * 10171 * @param left The bottom of this view, in pixels. 10172 */ 10173 public final void setLeft(int left) { 10174 if (left != mLeft) { 10175 updateMatrix(); 10176 final boolean matrixIsIdentity = mTransformationInfo == null 10177 || mTransformationInfo.mMatrixIsIdentity; 10178 if (matrixIsIdentity) { 10179 if (mAttachInfo != null) { 10180 int minLeft; 10181 int xLoc; 10182 if (left < mLeft) { 10183 minLeft = left; 10184 xLoc = left - mLeft; 10185 } else { 10186 minLeft = mLeft; 10187 xLoc = 0; 10188 } 10189 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 10190 } 10191 } else { 10192 // Double-invalidation is necessary to capture view's old and new areas 10193 invalidate(true); 10194 } 10195 10196 int oldWidth = mRight - mLeft; 10197 int height = mBottom - mTop; 10198 10199 mLeft = left; 10200 if (mDisplayList != null) { 10201 mDisplayList.setLeft(left); 10202 } 10203 10204 sizeChange(mRight - mLeft, height, oldWidth, height); 10205 10206 if (!matrixIsIdentity) { 10207 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 10208 // A change in dimension means an auto-centered pivot point changes, too 10209 mTransformationInfo.mMatrixDirty = true; 10210 } 10211 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10212 invalidate(true); 10213 } 10214 mBackgroundSizeChanged = true; 10215 invalidateParentIfNeeded(); 10216 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10217 // View was rejected last time it was drawn by its parent; this may have changed 10218 invalidateParentIfNeeded(); 10219 } 10220 } 10221 } 10222 10223 /** 10224 * Right position of this view relative to its parent. 10225 * 10226 * @return The right edge of this view, in pixels. 10227 */ 10228 @ViewDebug.CapturedViewProperty 10229 public final int getRight() { 10230 return mRight; 10231 } 10232 10233 /** 10234 * Sets the right position of this view relative to its parent. This method is meant to be called 10235 * by the layout system and should not generally be called otherwise, because the property 10236 * may be changed at any time by the layout. 10237 * 10238 * @param right The bottom of this view, in pixels. 10239 */ 10240 public final void setRight(int right) { 10241 if (right != mRight) { 10242 updateMatrix(); 10243 final boolean matrixIsIdentity = mTransformationInfo == null 10244 || mTransformationInfo.mMatrixIsIdentity; 10245 if (matrixIsIdentity) { 10246 if (mAttachInfo != null) { 10247 int maxRight; 10248 if (right < mRight) { 10249 maxRight = mRight; 10250 } else { 10251 maxRight = right; 10252 } 10253 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 10254 } 10255 } else { 10256 // Double-invalidation is necessary to capture view's old and new areas 10257 invalidate(true); 10258 } 10259 10260 int oldWidth = mRight - mLeft; 10261 int height = mBottom - mTop; 10262 10263 mRight = right; 10264 if (mDisplayList != null) { 10265 mDisplayList.setRight(mRight); 10266 } 10267 10268 sizeChange(mRight - mLeft, height, oldWidth, height); 10269 10270 if (!matrixIsIdentity) { 10271 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 10272 // A change in dimension means an auto-centered pivot point changes, too 10273 mTransformationInfo.mMatrixDirty = true; 10274 } 10275 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10276 invalidate(true); 10277 } 10278 mBackgroundSizeChanged = true; 10279 invalidateParentIfNeeded(); 10280 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10281 // View was rejected last time it was drawn by its parent; this may have changed 10282 invalidateParentIfNeeded(); 10283 } 10284 } 10285 } 10286 10287 /** 10288 * The visual x position of this view, in pixels. This is equivalent to the 10289 * {@link #setTranslationX(float) translationX} property plus the current 10290 * {@link #getLeft() left} property. 10291 * 10292 * @return The visual x position of this view, in pixels. 10293 */ 10294 @ViewDebug.ExportedProperty(category = "drawing") 10295 public float getX() { 10296 return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0); 10297 } 10298 10299 /** 10300 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 10301 * {@link #setTranslationX(float) translationX} property to be the difference between 10302 * the x value passed in and the current {@link #getLeft() left} property. 10303 * 10304 * @param x The visual x position of this view, in pixels. 10305 */ 10306 public void setX(float x) { 10307 setTranslationX(x - mLeft); 10308 } 10309 10310 /** 10311 * The visual y position of this view, in pixels. This is equivalent to the 10312 * {@link #setTranslationY(float) translationY} property plus the current 10313 * {@link #getTop() top} property. 10314 * 10315 * @return The visual y position of this view, in pixels. 10316 */ 10317 @ViewDebug.ExportedProperty(category = "drawing") 10318 public float getY() { 10319 return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0); 10320 } 10321 10322 /** 10323 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 10324 * {@link #setTranslationY(float) translationY} property to be the difference between 10325 * the y value passed in and the current {@link #getTop() top} property. 10326 * 10327 * @param y The visual y position of this view, in pixels. 10328 */ 10329 public void setY(float y) { 10330 setTranslationY(y - mTop); 10331 } 10332 10333 10334 /** 10335 * The horizontal location of this view relative to its {@link #getLeft() left} position. 10336 * This position is post-layout, in addition to wherever the object's 10337 * layout placed it. 10338 * 10339 * @return The horizontal position of this view relative to its left position, in pixels. 10340 */ 10341 @ViewDebug.ExportedProperty(category = "drawing") 10342 public float getTranslationX() { 10343 return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0; 10344 } 10345 10346 /** 10347 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 10348 * This effectively positions the object post-layout, in addition to wherever the object's 10349 * layout placed it. 10350 * 10351 * @param translationX The horizontal position of this view relative to its left position, 10352 * in pixels. 10353 * 10354 * @attr ref android.R.styleable#View_translationX 10355 */ 10356 public void setTranslationX(float translationX) { 10357 ensureTransformationInfo(); 10358 final TransformationInfo info = mTransformationInfo; 10359 if (info.mTranslationX != translationX) { 10360 // Double-invalidation is necessary to capture view's old and new areas 10361 invalidateViewProperty(true, false); 10362 info.mTranslationX = translationX; 10363 info.mMatrixDirty = true; 10364 invalidateViewProperty(false, true); 10365 if (mDisplayList != null) { 10366 mDisplayList.setTranslationX(translationX); 10367 } 10368 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10369 // View was rejected last time it was drawn by its parent; this may have changed 10370 invalidateParentIfNeeded(); 10371 } 10372 } 10373 } 10374 10375 /** 10376 * The horizontal location of this view relative to its {@link #getTop() top} position. 10377 * This position is post-layout, in addition to wherever the object's 10378 * layout placed it. 10379 * 10380 * @return The vertical position of this view relative to its top position, 10381 * in pixels. 10382 */ 10383 @ViewDebug.ExportedProperty(category = "drawing") 10384 public float getTranslationY() { 10385 return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0; 10386 } 10387 10388 /** 10389 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 10390 * This effectively positions the object post-layout, in addition to wherever the object's 10391 * layout placed it. 10392 * 10393 * @param translationY The vertical position of this view relative to its top position, 10394 * in pixels. 10395 * 10396 * @attr ref android.R.styleable#View_translationY 10397 */ 10398 public void setTranslationY(float translationY) { 10399 ensureTransformationInfo(); 10400 final TransformationInfo info = mTransformationInfo; 10401 if (info.mTranslationY != translationY) { 10402 invalidateViewProperty(true, false); 10403 info.mTranslationY = translationY; 10404 info.mMatrixDirty = true; 10405 invalidateViewProperty(false, true); 10406 if (mDisplayList != null) { 10407 mDisplayList.setTranslationY(translationY); 10408 } 10409 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10410 // View was rejected last time it was drawn by its parent; this may have changed 10411 invalidateParentIfNeeded(); 10412 } 10413 } 10414 } 10415 10416 /** 10417 * Hit rectangle in parent's coordinates 10418 * 10419 * @param outRect The hit rectangle of the view. 10420 */ 10421 public void getHitRect(Rect outRect) { 10422 updateMatrix(); 10423 final TransformationInfo info = mTransformationInfo; 10424 if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) { 10425 outRect.set(mLeft, mTop, mRight, mBottom); 10426 } else { 10427 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 10428 tmpRect.set(0, 0, getWidth(), getHeight()); 10429 info.mMatrix.mapRect(tmpRect); 10430 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 10431 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 10432 } 10433 } 10434 10435 /** 10436 * Determines whether the given point, in local coordinates is inside the view. 10437 */ 10438 /*package*/ final boolean pointInView(float localX, float localY) { 10439 return localX >= 0 && localX < (mRight - mLeft) 10440 && localY >= 0 && localY < (mBottom - mTop); 10441 } 10442 10443 /** 10444 * Utility method to determine whether the given point, in local coordinates, 10445 * is inside the view, where the area of the view is expanded by the slop factor. 10446 * This method is called while processing touch-move events to determine if the event 10447 * is still within the view. 10448 * 10449 * @hide 10450 */ 10451 public boolean pointInView(float localX, float localY, float slop) { 10452 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 10453 localY < ((mBottom - mTop) + slop); 10454 } 10455 10456 /** 10457 * When a view has focus and the user navigates away from it, the next view is searched for 10458 * starting from the rectangle filled in by this method. 10459 * 10460 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 10461 * of the view. However, if your view maintains some idea of internal selection, 10462 * such as a cursor, or a selected row or column, you should override this method and 10463 * fill in a more specific rectangle. 10464 * 10465 * @param r The rectangle to fill in, in this view's coordinates. 10466 */ 10467 public void getFocusedRect(Rect r) { 10468 getDrawingRect(r); 10469 } 10470 10471 /** 10472 * If some part of this view is not clipped by any of its parents, then 10473 * return that area in r in global (root) coordinates. To convert r to local 10474 * coordinates (without taking possible View rotations into account), offset 10475 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 10476 * If the view is completely clipped or translated out, return false. 10477 * 10478 * @param r If true is returned, r holds the global coordinates of the 10479 * visible portion of this view. 10480 * @param globalOffset If true is returned, globalOffset holds the dx,dy 10481 * between this view and its root. globalOffet may be null. 10482 * @return true if r is non-empty (i.e. part of the view is visible at the 10483 * root level. 10484 */ 10485 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 10486 int width = mRight - mLeft; 10487 int height = mBottom - mTop; 10488 if (width > 0 && height > 0) { 10489 r.set(0, 0, width, height); 10490 if (globalOffset != null) { 10491 globalOffset.set(-mScrollX, -mScrollY); 10492 } 10493 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 10494 } 10495 return false; 10496 } 10497 10498 public final boolean getGlobalVisibleRect(Rect r) { 10499 return getGlobalVisibleRect(r, null); 10500 } 10501 10502 public final boolean getLocalVisibleRect(Rect r) { 10503 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 10504 if (getGlobalVisibleRect(r, offset)) { 10505 r.offset(-offset.x, -offset.y); // make r local 10506 return true; 10507 } 10508 return false; 10509 } 10510 10511 /** 10512 * Offset this view's vertical location by the specified number of pixels. 10513 * 10514 * @param offset the number of pixels to offset the view by 10515 */ 10516 public void offsetTopAndBottom(int offset) { 10517 if (offset != 0) { 10518 updateMatrix(); 10519 final boolean matrixIsIdentity = mTransformationInfo == null 10520 || mTransformationInfo.mMatrixIsIdentity; 10521 if (matrixIsIdentity) { 10522 if (mDisplayList != null) { 10523 invalidateViewProperty(false, false); 10524 } else { 10525 final ViewParent p = mParent; 10526 if (p != null && mAttachInfo != null) { 10527 final Rect r = mAttachInfo.mTmpInvalRect; 10528 int minTop; 10529 int maxBottom; 10530 int yLoc; 10531 if (offset < 0) { 10532 minTop = mTop + offset; 10533 maxBottom = mBottom; 10534 yLoc = offset; 10535 } else { 10536 minTop = mTop; 10537 maxBottom = mBottom + offset; 10538 yLoc = 0; 10539 } 10540 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 10541 p.invalidateChild(this, r); 10542 } 10543 } 10544 } else { 10545 invalidateViewProperty(false, false); 10546 } 10547 10548 mTop += offset; 10549 mBottom += offset; 10550 if (mDisplayList != null) { 10551 mDisplayList.offsetTopAndBottom(offset); 10552 invalidateViewProperty(false, false); 10553 } else { 10554 if (!matrixIsIdentity) { 10555 invalidateViewProperty(false, true); 10556 } 10557 invalidateParentIfNeeded(); 10558 } 10559 } 10560 } 10561 10562 /** 10563 * Offset this view's horizontal location by the specified amount of pixels. 10564 * 10565 * @param offset the number of pixels to offset the view by 10566 */ 10567 public void offsetLeftAndRight(int offset) { 10568 if (offset != 0) { 10569 updateMatrix(); 10570 final boolean matrixIsIdentity = mTransformationInfo == null 10571 || mTransformationInfo.mMatrixIsIdentity; 10572 if (matrixIsIdentity) { 10573 if (mDisplayList != null) { 10574 invalidateViewProperty(false, false); 10575 } else { 10576 final ViewParent p = mParent; 10577 if (p != null && mAttachInfo != null) { 10578 final Rect r = mAttachInfo.mTmpInvalRect; 10579 int minLeft; 10580 int maxRight; 10581 if (offset < 0) { 10582 minLeft = mLeft + offset; 10583 maxRight = mRight; 10584 } else { 10585 minLeft = mLeft; 10586 maxRight = mRight + offset; 10587 } 10588 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 10589 p.invalidateChild(this, r); 10590 } 10591 } 10592 } else { 10593 invalidateViewProperty(false, false); 10594 } 10595 10596 mLeft += offset; 10597 mRight += offset; 10598 if (mDisplayList != null) { 10599 mDisplayList.offsetLeftAndRight(offset); 10600 invalidateViewProperty(false, false); 10601 } else { 10602 if (!matrixIsIdentity) { 10603 invalidateViewProperty(false, true); 10604 } 10605 invalidateParentIfNeeded(); 10606 } 10607 } 10608 } 10609 10610 /** 10611 * Get the LayoutParams associated with this view. All views should have 10612 * layout parameters. These supply parameters to the <i>parent</i> of this 10613 * view specifying how it should be arranged. There are many subclasses of 10614 * ViewGroup.LayoutParams, and these correspond to the different subclasses 10615 * of ViewGroup that are responsible for arranging their children. 10616 * 10617 * This method may return null if this View is not attached to a parent 10618 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 10619 * was not invoked successfully. When a View is attached to a parent 10620 * ViewGroup, this method must not return null. 10621 * 10622 * @return The LayoutParams associated with this view, or null if no 10623 * parameters have been set yet 10624 */ 10625 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 10626 public ViewGroup.LayoutParams getLayoutParams() { 10627 return mLayoutParams; 10628 } 10629 10630 /** 10631 * Set the layout parameters associated with this view. These supply 10632 * parameters to the <i>parent</i> of this view specifying how it should be 10633 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 10634 * correspond to the different subclasses of ViewGroup that are responsible 10635 * for arranging their children. 10636 * 10637 * @param params The layout parameters for this view, cannot be null 10638 */ 10639 public void setLayoutParams(ViewGroup.LayoutParams params) { 10640 if (params == null) { 10641 throw new NullPointerException("Layout parameters cannot be null"); 10642 } 10643 mLayoutParams = params; 10644 resolveLayoutParams(); 10645 if (mParent instanceof ViewGroup) { 10646 ((ViewGroup) mParent).onSetLayoutParams(this, params); 10647 } 10648 requestLayout(); 10649 } 10650 10651 /** 10652 * Resolve the layout parameters depending on the resolved layout direction 10653 * 10654 * @hide 10655 */ 10656 public void resolveLayoutParams() { 10657 if (mLayoutParams != null) { 10658 mLayoutParams.resolveLayoutDirection(getLayoutDirection()); 10659 } 10660 } 10661 10662 /** 10663 * Set the scrolled position of your view. This will cause a call to 10664 * {@link #onScrollChanged(int, int, int, int)} and the view will be 10665 * invalidated. 10666 * @param x the x position to scroll to 10667 * @param y the y position to scroll to 10668 */ 10669 public void scrollTo(int x, int y) { 10670 if (mScrollX != x || mScrollY != y) { 10671 int oldX = mScrollX; 10672 int oldY = mScrollY; 10673 mScrollX = x; 10674 mScrollY = y; 10675 invalidateParentCaches(); 10676 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 10677 if (!awakenScrollBars()) { 10678 postInvalidateOnAnimation(); 10679 } 10680 } 10681 } 10682 10683 /** 10684 * Move the scrolled position of your view. This will cause a call to 10685 * {@link #onScrollChanged(int, int, int, int)} and the view will be 10686 * invalidated. 10687 * @param x the amount of pixels to scroll by horizontally 10688 * @param y the amount of pixels to scroll by vertically 10689 */ 10690 public void scrollBy(int x, int y) { 10691 scrollTo(mScrollX + x, mScrollY + y); 10692 } 10693 10694 /** 10695 * <p>Trigger the scrollbars to draw. When invoked this method starts an 10696 * animation to fade the scrollbars out after a default delay. If a subclass 10697 * provides animated scrolling, the start delay should equal the duration 10698 * of the scrolling animation.</p> 10699 * 10700 * <p>The animation starts only if at least one of the scrollbars is 10701 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 10702 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 10703 * this method returns true, and false otherwise. If the animation is 10704 * started, this method calls {@link #invalidate()}; in that case the 10705 * caller should not call {@link #invalidate()}.</p> 10706 * 10707 * <p>This method should be invoked every time a subclass directly updates 10708 * the scroll parameters.</p> 10709 * 10710 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 10711 * and {@link #scrollTo(int, int)}.</p> 10712 * 10713 * @return true if the animation is played, false otherwise 10714 * 10715 * @see #awakenScrollBars(int) 10716 * @see #scrollBy(int, int) 10717 * @see #scrollTo(int, int) 10718 * @see #isHorizontalScrollBarEnabled() 10719 * @see #isVerticalScrollBarEnabled() 10720 * @see #setHorizontalScrollBarEnabled(boolean) 10721 * @see #setVerticalScrollBarEnabled(boolean) 10722 */ 10723 protected boolean awakenScrollBars() { 10724 return mScrollCache != null && 10725 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 10726 } 10727 10728 /** 10729 * Trigger the scrollbars to draw. 10730 * This method differs from awakenScrollBars() only in its default duration. 10731 * initialAwakenScrollBars() will show the scroll bars for longer than 10732 * usual to give the user more of a chance to notice them. 10733 * 10734 * @return true if the animation is played, false otherwise. 10735 */ 10736 private boolean initialAwakenScrollBars() { 10737 return mScrollCache != null && 10738 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 10739 } 10740 10741 /** 10742 * <p> 10743 * Trigger the scrollbars to draw. When invoked this method starts an 10744 * animation to fade the scrollbars out after a fixed delay. If a subclass 10745 * provides animated scrolling, the start delay should equal the duration of 10746 * the scrolling animation. 10747 * </p> 10748 * 10749 * <p> 10750 * The animation starts only if at least one of the scrollbars is enabled, 10751 * as specified by {@link #isHorizontalScrollBarEnabled()} and 10752 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 10753 * this method returns true, and false otherwise. If the animation is 10754 * started, this method calls {@link #invalidate()}; in that case the caller 10755 * should not call {@link #invalidate()}. 10756 * </p> 10757 * 10758 * <p> 10759 * This method should be invoked everytime a subclass directly updates the 10760 * scroll parameters. 10761 * </p> 10762 * 10763 * @param startDelay the delay, in milliseconds, after which the animation 10764 * should start; when the delay is 0, the animation starts 10765 * immediately 10766 * @return true if the animation is played, false otherwise 10767 * 10768 * @see #scrollBy(int, int) 10769 * @see #scrollTo(int, int) 10770 * @see #isHorizontalScrollBarEnabled() 10771 * @see #isVerticalScrollBarEnabled() 10772 * @see #setHorizontalScrollBarEnabled(boolean) 10773 * @see #setVerticalScrollBarEnabled(boolean) 10774 */ 10775 protected boolean awakenScrollBars(int startDelay) { 10776 return awakenScrollBars(startDelay, true); 10777 } 10778 10779 /** 10780 * <p> 10781 * Trigger the scrollbars to draw. When invoked this method starts an 10782 * animation to fade the scrollbars out after a fixed delay. If a subclass 10783 * provides animated scrolling, the start delay should equal the duration of 10784 * the scrolling animation. 10785 * </p> 10786 * 10787 * <p> 10788 * The animation starts only if at least one of the scrollbars is enabled, 10789 * as specified by {@link #isHorizontalScrollBarEnabled()} and 10790 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 10791 * this method returns true, and false otherwise. If the animation is 10792 * started, this method calls {@link #invalidate()} if the invalidate parameter 10793 * is set to true; in that case the caller 10794 * should not call {@link #invalidate()}. 10795 * </p> 10796 * 10797 * <p> 10798 * This method should be invoked everytime a subclass directly updates the 10799 * scroll parameters. 10800 * </p> 10801 * 10802 * @param startDelay the delay, in milliseconds, after which the animation 10803 * should start; when the delay is 0, the animation starts 10804 * immediately 10805 * 10806 * @param invalidate Wheter this method should call invalidate 10807 * 10808 * @return true if the animation is played, false otherwise 10809 * 10810 * @see #scrollBy(int, int) 10811 * @see #scrollTo(int, int) 10812 * @see #isHorizontalScrollBarEnabled() 10813 * @see #isVerticalScrollBarEnabled() 10814 * @see #setHorizontalScrollBarEnabled(boolean) 10815 * @see #setVerticalScrollBarEnabled(boolean) 10816 */ 10817 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 10818 final ScrollabilityCache scrollCache = mScrollCache; 10819 10820 if (scrollCache == null || !scrollCache.fadeScrollBars) { 10821 return false; 10822 } 10823 10824 if (scrollCache.scrollBar == null) { 10825 scrollCache.scrollBar = new ScrollBarDrawable(); 10826 } 10827 10828 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 10829 10830 if (invalidate) { 10831 // Invalidate to show the scrollbars 10832 postInvalidateOnAnimation(); 10833 } 10834 10835 if (scrollCache.state == ScrollabilityCache.OFF) { 10836 // FIXME: this is copied from WindowManagerService. 10837 // We should get this value from the system when it 10838 // is possible to do so. 10839 final int KEY_REPEAT_FIRST_DELAY = 750; 10840 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 10841 } 10842 10843 // Tell mScrollCache when we should start fading. This may 10844 // extend the fade start time if one was already scheduled 10845 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 10846 scrollCache.fadeStartTime = fadeStartTime; 10847 scrollCache.state = ScrollabilityCache.ON; 10848 10849 // Schedule our fader to run, unscheduling any old ones first 10850 if (mAttachInfo != null) { 10851 mAttachInfo.mHandler.removeCallbacks(scrollCache); 10852 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 10853 } 10854 10855 return true; 10856 } 10857 10858 return false; 10859 } 10860 10861 /** 10862 * Do not invalidate views which are not visible and which are not running an animation. They 10863 * will not get drawn and they should not set dirty flags as if they will be drawn 10864 */ 10865 private boolean skipInvalidate() { 10866 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 10867 (!(mParent instanceof ViewGroup) || 10868 !((ViewGroup) mParent).isViewTransitioning(this)); 10869 } 10870 /** 10871 * Mark the area defined by dirty as needing to be drawn. If the view is 10872 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point 10873 * in the future. This must be called from a UI thread. To call from a non-UI 10874 * thread, call {@link #postInvalidate()}. 10875 * 10876 * WARNING: This method is destructive to dirty. 10877 * @param dirty the rectangle representing the bounds of the dirty region 10878 */ 10879 public void invalidate(Rect dirty) { 10880 if (skipInvalidate()) { 10881 return; 10882 } 10883 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) || 10884 (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID || 10885 (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) { 10886 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 10887 mPrivateFlags |= PFLAG_INVALIDATED; 10888 mPrivateFlags |= PFLAG_DIRTY; 10889 final ViewParent p = mParent; 10890 final AttachInfo ai = mAttachInfo; 10891 //noinspection PointlessBooleanExpression,ConstantConditions 10892 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 10893 if (p != null && ai != null && ai.mHardwareAccelerated) { 10894 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 10895 // with a null dirty rect, which tells the ViewAncestor to redraw everything 10896 p.invalidateChild(this, null); 10897 return; 10898 } 10899 } 10900 if (p != null && ai != null) { 10901 final int scrollX = mScrollX; 10902 final int scrollY = mScrollY; 10903 final Rect r = ai.mTmpInvalRect; 10904 r.set(dirty.left - scrollX, dirty.top - scrollY, 10905 dirty.right - scrollX, dirty.bottom - scrollY); 10906 mParent.invalidateChild(this, r); 10907 } 10908 } 10909 } 10910 10911 /** 10912 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. 10913 * The coordinates of the dirty rect are relative to the view. 10914 * If the view is visible, {@link #onDraw(android.graphics.Canvas)} 10915 * will be called at some point in the future. This must be called from 10916 * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}. 10917 * @param l the left position of the dirty region 10918 * @param t the top position of the dirty region 10919 * @param r the right position of the dirty region 10920 * @param b the bottom position of the dirty region 10921 */ 10922 public void invalidate(int l, int t, int r, int b) { 10923 if (skipInvalidate()) { 10924 return; 10925 } 10926 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) || 10927 (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID || 10928 (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) { 10929 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 10930 mPrivateFlags |= PFLAG_INVALIDATED; 10931 mPrivateFlags |= PFLAG_DIRTY; 10932 final ViewParent p = mParent; 10933 final AttachInfo ai = mAttachInfo; 10934 //noinspection PointlessBooleanExpression,ConstantConditions 10935 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 10936 if (p != null && ai != null && ai.mHardwareAccelerated) { 10937 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 10938 // with a null dirty rect, which tells the ViewAncestor to redraw everything 10939 p.invalidateChild(this, null); 10940 return; 10941 } 10942 } 10943 if (p != null && ai != null && l < r && t < b) { 10944 final int scrollX = mScrollX; 10945 final int scrollY = mScrollY; 10946 final Rect tmpr = ai.mTmpInvalRect; 10947 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY); 10948 p.invalidateChild(this, tmpr); 10949 } 10950 } 10951 } 10952 10953 /** 10954 * Invalidate the whole view. If the view is visible, 10955 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 10956 * the future. This must be called from a UI thread. To call from a non-UI thread, 10957 * call {@link #postInvalidate()}. 10958 */ 10959 public void invalidate() { 10960 invalidate(true); 10961 } 10962 10963 /** 10964 * This is where the invalidate() work actually happens. A full invalidate() 10965 * causes the drawing cache to be invalidated, but this function can be called with 10966 * invalidateCache set to false to skip that invalidation step for cases that do not 10967 * need it (for example, a component that remains at the same dimensions with the same 10968 * content). 10969 * 10970 * @param invalidateCache Whether the drawing cache for this view should be invalidated as 10971 * well. This is usually true for a full invalidate, but may be set to false if the 10972 * View's contents or dimensions have not changed. 10973 */ 10974 void invalidate(boolean invalidateCache) { 10975 if (skipInvalidate()) { 10976 return; 10977 } 10978 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) || 10979 (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) || 10980 (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED || isOpaque() != mLastIsOpaque) { 10981 mLastIsOpaque = isOpaque(); 10982 mPrivateFlags &= ~PFLAG_DRAWN; 10983 mPrivateFlags |= PFLAG_DIRTY; 10984 if (invalidateCache) { 10985 mPrivateFlags |= PFLAG_INVALIDATED; 10986 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 10987 } 10988 final AttachInfo ai = mAttachInfo; 10989 final ViewParent p = mParent; 10990 //noinspection PointlessBooleanExpression,ConstantConditions 10991 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 10992 if (p != null && ai != null && ai.mHardwareAccelerated) { 10993 // fast-track for GL-enabled applications; just invalidate the whole hierarchy 10994 // with a null dirty rect, which tells the ViewAncestor to redraw everything 10995 p.invalidateChild(this, null); 10996 return; 10997 } 10998 } 10999 11000 if (p != null && ai != null) { 11001 final Rect r = ai.mTmpInvalRect; 11002 r.set(0, 0, mRight - mLeft, mBottom - mTop); 11003 // Don't call invalidate -- we don't want to internally scroll 11004 // our own bounds 11005 p.invalidateChild(this, r); 11006 } 11007 } 11008 } 11009 11010 /** 11011 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 11012 * set any flags or handle all of the cases handled by the default invalidation methods. 11013 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 11014 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 11015 * walk up the hierarchy, transforming the dirty rect as necessary. 11016 * 11017 * The method also handles normal invalidation logic if display list properties are not 11018 * being used in this view. The invalidateParent and forceRedraw flags are used by that 11019 * backup approach, to handle these cases used in the various property-setting methods. 11020 * 11021 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 11022 * are not being used in this view 11023 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 11024 * list properties are not being used in this view 11025 */ 11026 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 11027 if (mDisplayList == null || (mPrivateFlags & PFLAG_DRAW_ANIMATION) == PFLAG_DRAW_ANIMATION) { 11028 if (invalidateParent) { 11029 invalidateParentCaches(); 11030 } 11031 if (forceRedraw) { 11032 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 11033 } 11034 invalidate(false); 11035 } else { 11036 final AttachInfo ai = mAttachInfo; 11037 final ViewParent p = mParent; 11038 if (p != null && ai != null) { 11039 final Rect r = ai.mTmpInvalRect; 11040 r.set(0, 0, mRight - mLeft, mBottom - mTop); 11041 if (mParent instanceof ViewGroup) { 11042 ((ViewGroup) mParent).invalidateChildFast(this, r); 11043 } else { 11044 mParent.invalidateChild(this, r); 11045 } 11046 } 11047 } 11048 } 11049 11050 /** 11051 * Utility method to transform a given Rect by the current matrix of this view. 11052 */ 11053 void transformRect(final Rect rect) { 11054 if (!getMatrix().isIdentity()) { 11055 RectF boundingRect = mAttachInfo.mTmpTransformRect; 11056 boundingRect.set(rect); 11057 getMatrix().mapRect(boundingRect); 11058 rect.set((int) Math.floor(boundingRect.left), 11059 (int) Math.floor(boundingRect.top), 11060 (int) Math.ceil(boundingRect.right), 11061 (int) Math.ceil(boundingRect.bottom)); 11062 } 11063 } 11064 11065 /** 11066 * Used to indicate that the parent of this view should clear its caches. This functionality 11067 * is used to force the parent to rebuild its display list (when hardware-accelerated), 11068 * which is necessary when various parent-managed properties of the view change, such as 11069 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 11070 * clears the parent caches and does not causes an invalidate event. 11071 * 11072 * @hide 11073 */ 11074 protected void invalidateParentCaches() { 11075 if (mParent instanceof View) { 11076 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 11077 } 11078 } 11079 11080 /** 11081 * Used to indicate that the parent of this view should be invalidated. This functionality 11082 * is used to force the parent to rebuild its display list (when hardware-accelerated), 11083 * which is necessary when various parent-managed properties of the view change, such as 11084 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 11085 * an invalidation event to the parent. 11086 * 11087 * @hide 11088 */ 11089 protected void invalidateParentIfNeeded() { 11090 if (isHardwareAccelerated() && mParent instanceof View) { 11091 ((View) mParent).invalidate(true); 11092 } 11093 } 11094 11095 /** 11096 * Indicates whether this View is opaque. An opaque View guarantees that it will 11097 * draw all the pixels overlapping its bounds using a fully opaque color. 11098 * 11099 * Subclasses of View should override this method whenever possible to indicate 11100 * whether an instance is opaque. Opaque Views are treated in a special way by 11101 * the View hierarchy, possibly allowing it to perform optimizations during 11102 * invalidate/draw passes. 11103 * 11104 * @return True if this View is guaranteed to be fully opaque, false otherwise. 11105 */ 11106 @ViewDebug.ExportedProperty(category = "drawing") 11107 public boolean isOpaque() { 11108 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 11109 getFinalAlpha() >= 1.0f; 11110 } 11111 11112 /** 11113 * @hide 11114 */ 11115 protected void computeOpaqueFlags() { 11116 // Opaque if: 11117 // - Has a background 11118 // - Background is opaque 11119 // - Doesn't have scrollbars or scrollbars overlay 11120 11121 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 11122 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 11123 } else { 11124 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 11125 } 11126 11127 final int flags = mViewFlags; 11128 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 11129 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY || 11130 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) { 11131 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 11132 } else { 11133 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 11134 } 11135 } 11136 11137 /** 11138 * @hide 11139 */ 11140 protected boolean hasOpaqueScrollbars() { 11141 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 11142 } 11143 11144 /** 11145 * @return A handler associated with the thread running the View. This 11146 * handler can be used to pump events in the UI events queue. 11147 */ 11148 public Handler getHandler() { 11149 final AttachInfo attachInfo = mAttachInfo; 11150 if (attachInfo != null) { 11151 return attachInfo.mHandler; 11152 } 11153 return null; 11154 } 11155 11156 /** 11157 * Gets the view root associated with the View. 11158 * @return The view root, or null if none. 11159 * @hide 11160 */ 11161 public ViewRootImpl getViewRootImpl() { 11162 if (mAttachInfo != null) { 11163 return mAttachInfo.mViewRootImpl; 11164 } 11165 return null; 11166 } 11167 11168 /** 11169 * <p>Causes the Runnable to be added to the message queue. 11170 * The runnable will be run on the user interface thread.</p> 11171 * 11172 * @param action The Runnable that will be executed. 11173 * 11174 * @return Returns true if the Runnable was successfully placed in to the 11175 * message queue. Returns false on failure, usually because the 11176 * looper processing the message queue is exiting. 11177 * 11178 * @see #postDelayed 11179 * @see #removeCallbacks 11180 */ 11181 public boolean post(Runnable action) { 11182 final AttachInfo attachInfo = mAttachInfo; 11183 if (attachInfo != null) { 11184 return attachInfo.mHandler.post(action); 11185 } 11186 // Assume that post will succeed later 11187 ViewRootImpl.getRunQueue().post(action); 11188 return true; 11189 } 11190 11191 /** 11192 * <p>Causes the Runnable to be added to the message queue, to be run 11193 * after the specified amount of time elapses. 11194 * The runnable will be run on the user interface thread.</p> 11195 * 11196 * @param action The Runnable that will be executed. 11197 * @param delayMillis The delay (in milliseconds) until the Runnable 11198 * will be executed. 11199 * 11200 * @return true if the Runnable was successfully placed in to the 11201 * message queue. Returns false on failure, usually because the 11202 * looper processing the message queue is exiting. Note that a 11203 * result of true does not mean the Runnable will be processed -- 11204 * if the looper is quit before the delivery time of the message 11205 * occurs then the message will be dropped. 11206 * 11207 * @see #post 11208 * @see #removeCallbacks 11209 */ 11210 public boolean postDelayed(Runnable action, long delayMillis) { 11211 final AttachInfo attachInfo = mAttachInfo; 11212 if (attachInfo != null) { 11213 return attachInfo.mHandler.postDelayed(action, delayMillis); 11214 } 11215 // Assume that post will succeed later 11216 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 11217 return true; 11218 } 11219 11220 /** 11221 * <p>Causes the Runnable to execute on the next animation time step. 11222 * The runnable will be run on the user interface thread.</p> 11223 * 11224 * @param action The Runnable that will be executed. 11225 * 11226 * @see #postOnAnimationDelayed 11227 * @see #removeCallbacks 11228 */ 11229 public void postOnAnimation(Runnable action) { 11230 final AttachInfo attachInfo = mAttachInfo; 11231 if (attachInfo != null) { 11232 attachInfo.mViewRootImpl.mChoreographer.postCallback( 11233 Choreographer.CALLBACK_ANIMATION, action, null); 11234 } else { 11235 // Assume that post will succeed later 11236 ViewRootImpl.getRunQueue().post(action); 11237 } 11238 } 11239 11240 /** 11241 * <p>Causes the Runnable to execute on the next animation time step, 11242 * after the specified amount of time elapses. 11243 * The runnable will be run on the user interface thread.</p> 11244 * 11245 * @param action The Runnable that will be executed. 11246 * @param delayMillis The delay (in milliseconds) until the Runnable 11247 * will be executed. 11248 * 11249 * @see #postOnAnimation 11250 * @see #removeCallbacks 11251 */ 11252 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 11253 final AttachInfo attachInfo = mAttachInfo; 11254 if (attachInfo != null) { 11255 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 11256 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 11257 } else { 11258 // Assume that post will succeed later 11259 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 11260 } 11261 } 11262 11263 /** 11264 * <p>Removes the specified Runnable from the message queue.</p> 11265 * 11266 * @param action The Runnable to remove from the message handling queue 11267 * 11268 * @return true if this view could ask the Handler to remove the Runnable, 11269 * false otherwise. When the returned value is true, the Runnable 11270 * may or may not have been actually removed from the message queue 11271 * (for instance, if the Runnable was not in the queue already.) 11272 * 11273 * @see #post 11274 * @see #postDelayed 11275 * @see #postOnAnimation 11276 * @see #postOnAnimationDelayed 11277 */ 11278 public boolean removeCallbacks(Runnable action) { 11279 if (action != null) { 11280 final AttachInfo attachInfo = mAttachInfo; 11281 if (attachInfo != null) { 11282 attachInfo.mHandler.removeCallbacks(action); 11283 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 11284 Choreographer.CALLBACK_ANIMATION, action, null); 11285 } else { 11286 // Assume that post will succeed later 11287 ViewRootImpl.getRunQueue().removeCallbacks(action); 11288 } 11289 } 11290 return true; 11291 } 11292 11293 /** 11294 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 11295 * Use this to invalidate the View from a non-UI thread.</p> 11296 * 11297 * <p>This method can be invoked from outside of the UI thread 11298 * only when this View is attached to a window.</p> 11299 * 11300 * @see #invalidate() 11301 * @see #postInvalidateDelayed(long) 11302 */ 11303 public void postInvalidate() { 11304 postInvalidateDelayed(0); 11305 } 11306 11307 /** 11308 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 11309 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 11310 * 11311 * <p>This method can be invoked from outside of the UI thread 11312 * only when this View is attached to a window.</p> 11313 * 11314 * @param left The left coordinate of the rectangle to invalidate. 11315 * @param top The top coordinate of the rectangle to invalidate. 11316 * @param right The right coordinate of the rectangle to invalidate. 11317 * @param bottom The bottom coordinate of the rectangle to invalidate. 11318 * 11319 * @see #invalidate(int, int, int, int) 11320 * @see #invalidate(Rect) 11321 * @see #postInvalidateDelayed(long, int, int, int, int) 11322 */ 11323 public void postInvalidate(int left, int top, int right, int bottom) { 11324 postInvalidateDelayed(0, left, top, right, bottom); 11325 } 11326 11327 /** 11328 * <p>Cause an invalidate to happen on a subsequent cycle through the event 11329 * loop. Waits for the specified amount of time.</p> 11330 * 11331 * <p>This method can be invoked from outside of the UI thread 11332 * only when this View is attached to a window.</p> 11333 * 11334 * @param delayMilliseconds the duration in milliseconds to delay the 11335 * invalidation by 11336 * 11337 * @see #invalidate() 11338 * @see #postInvalidate() 11339 */ 11340 public void postInvalidateDelayed(long delayMilliseconds) { 11341 // We try only with the AttachInfo because there's no point in invalidating 11342 // if we are not attached to our window 11343 final AttachInfo attachInfo = mAttachInfo; 11344 if (attachInfo != null) { 11345 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 11346 } 11347 } 11348 11349 /** 11350 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 11351 * through the event loop. Waits for the specified amount of time.</p> 11352 * 11353 * <p>This method can be invoked from outside of the UI thread 11354 * only when this View is attached to a window.</p> 11355 * 11356 * @param delayMilliseconds the duration in milliseconds to delay the 11357 * invalidation by 11358 * @param left The left coordinate of the rectangle to invalidate. 11359 * @param top The top coordinate of the rectangle to invalidate. 11360 * @param right The right coordinate of the rectangle to invalidate. 11361 * @param bottom The bottom coordinate of the rectangle to invalidate. 11362 * 11363 * @see #invalidate(int, int, int, int) 11364 * @see #invalidate(Rect) 11365 * @see #postInvalidate(int, int, int, int) 11366 */ 11367 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 11368 int right, int bottom) { 11369 11370 // We try only with the AttachInfo because there's no point in invalidating 11371 // if we are not attached to our window 11372 final AttachInfo attachInfo = mAttachInfo; 11373 if (attachInfo != null) { 11374 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 11375 info.target = this; 11376 info.left = left; 11377 info.top = top; 11378 info.right = right; 11379 info.bottom = bottom; 11380 11381 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 11382 } 11383 } 11384 11385 /** 11386 * <p>Cause an invalidate to happen on the next animation time step, typically the 11387 * next display frame.</p> 11388 * 11389 * <p>This method can be invoked from outside of the UI thread 11390 * only when this View is attached to a window.</p> 11391 * 11392 * @see #invalidate() 11393 */ 11394 public void postInvalidateOnAnimation() { 11395 // We try only with the AttachInfo because there's no point in invalidating 11396 // if we are not attached to our window 11397 final AttachInfo attachInfo = mAttachInfo; 11398 if (attachInfo != null) { 11399 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 11400 } 11401 } 11402 11403 /** 11404 * <p>Cause an invalidate of the specified area to happen on the next animation 11405 * time step, typically the next display frame.</p> 11406 * 11407 * <p>This method can be invoked from outside of the UI thread 11408 * only when this View is attached to a window.</p> 11409 * 11410 * @param left The left coordinate of the rectangle to invalidate. 11411 * @param top The top coordinate of the rectangle to invalidate. 11412 * @param right The right coordinate of the rectangle to invalidate. 11413 * @param bottom The bottom coordinate of the rectangle to invalidate. 11414 * 11415 * @see #invalidate(int, int, int, int) 11416 * @see #invalidate(Rect) 11417 */ 11418 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 11419 // We try only with the AttachInfo because there's no point in invalidating 11420 // if we are not attached to our window 11421 final AttachInfo attachInfo = mAttachInfo; 11422 if (attachInfo != null) { 11423 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 11424 info.target = this; 11425 info.left = left; 11426 info.top = top; 11427 info.right = right; 11428 info.bottom = bottom; 11429 11430 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 11431 } 11432 } 11433 11434 /** 11435 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 11436 * This event is sent at most once every 11437 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 11438 */ 11439 private void postSendViewScrolledAccessibilityEventCallback() { 11440 if (mSendViewScrolledAccessibilityEvent == null) { 11441 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 11442 } 11443 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 11444 mSendViewScrolledAccessibilityEvent.mIsPending = true; 11445 postDelayed(mSendViewScrolledAccessibilityEvent, 11446 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 11447 } 11448 } 11449 11450 /** 11451 * Called by a parent to request that a child update its values for mScrollX 11452 * and mScrollY if necessary. This will typically be done if the child is 11453 * animating a scroll using a {@link android.widget.Scroller Scroller} 11454 * object. 11455 */ 11456 public void computeScroll() { 11457 } 11458 11459 /** 11460 * <p>Indicate whether the horizontal edges are faded when the view is 11461 * scrolled horizontally.</p> 11462 * 11463 * @return true if the horizontal edges should are faded on scroll, false 11464 * otherwise 11465 * 11466 * @see #setHorizontalFadingEdgeEnabled(boolean) 11467 * 11468 * @attr ref android.R.styleable#View_requiresFadingEdge 11469 */ 11470 public boolean isHorizontalFadingEdgeEnabled() { 11471 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 11472 } 11473 11474 /** 11475 * <p>Define whether the horizontal edges should be faded when this view 11476 * is scrolled horizontally.</p> 11477 * 11478 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 11479 * be faded when the view is scrolled 11480 * horizontally 11481 * 11482 * @see #isHorizontalFadingEdgeEnabled() 11483 * 11484 * @attr ref android.R.styleable#View_requiresFadingEdge 11485 */ 11486 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 11487 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 11488 if (horizontalFadingEdgeEnabled) { 11489 initScrollCache(); 11490 } 11491 11492 mViewFlags ^= FADING_EDGE_HORIZONTAL; 11493 } 11494 } 11495 11496 /** 11497 * <p>Indicate whether the vertical edges are faded when the view is 11498 * scrolled horizontally.</p> 11499 * 11500 * @return true if the vertical edges should are faded on scroll, false 11501 * otherwise 11502 * 11503 * @see #setVerticalFadingEdgeEnabled(boolean) 11504 * 11505 * @attr ref android.R.styleable#View_requiresFadingEdge 11506 */ 11507 public boolean isVerticalFadingEdgeEnabled() { 11508 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 11509 } 11510 11511 /** 11512 * <p>Define whether the vertical edges should be faded when this view 11513 * is scrolled vertically.</p> 11514 * 11515 * @param verticalFadingEdgeEnabled true if the vertical edges should 11516 * be faded when the view is scrolled 11517 * vertically 11518 * 11519 * @see #isVerticalFadingEdgeEnabled() 11520 * 11521 * @attr ref android.R.styleable#View_requiresFadingEdge 11522 */ 11523 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 11524 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 11525 if (verticalFadingEdgeEnabled) { 11526 initScrollCache(); 11527 } 11528 11529 mViewFlags ^= FADING_EDGE_VERTICAL; 11530 } 11531 } 11532 11533 /** 11534 * Returns the strength, or intensity, of the top faded edge. The strength is 11535 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11536 * returns 0.0 or 1.0 but no value in between. 11537 * 11538 * Subclasses should override this method to provide a smoother fade transition 11539 * when scrolling occurs. 11540 * 11541 * @return the intensity of the top fade as a float between 0.0f and 1.0f 11542 */ 11543 protected float getTopFadingEdgeStrength() { 11544 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 11545 } 11546 11547 /** 11548 * Returns the strength, or intensity, of the bottom faded edge. The strength is 11549 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11550 * returns 0.0 or 1.0 but no value in between. 11551 * 11552 * Subclasses should override this method to provide a smoother fade transition 11553 * when scrolling occurs. 11554 * 11555 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 11556 */ 11557 protected float getBottomFadingEdgeStrength() { 11558 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 11559 computeVerticalScrollRange() ? 1.0f : 0.0f; 11560 } 11561 11562 /** 11563 * Returns the strength, or intensity, of the left faded edge. The strength is 11564 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11565 * returns 0.0 or 1.0 but no value in between. 11566 * 11567 * Subclasses should override this method to provide a smoother fade transition 11568 * when scrolling occurs. 11569 * 11570 * @return the intensity of the left fade as a float between 0.0f and 1.0f 11571 */ 11572 protected float getLeftFadingEdgeStrength() { 11573 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 11574 } 11575 11576 /** 11577 * Returns the strength, or intensity, of the right faded edge. The strength is 11578 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11579 * returns 0.0 or 1.0 but no value in between. 11580 * 11581 * Subclasses should override this method to provide a smoother fade transition 11582 * when scrolling occurs. 11583 * 11584 * @return the intensity of the right fade as a float between 0.0f and 1.0f 11585 */ 11586 protected float getRightFadingEdgeStrength() { 11587 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 11588 computeHorizontalScrollRange() ? 1.0f : 0.0f; 11589 } 11590 11591 /** 11592 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 11593 * scrollbar is not drawn by default.</p> 11594 * 11595 * @return true if the horizontal scrollbar should be painted, false 11596 * otherwise 11597 * 11598 * @see #setHorizontalScrollBarEnabled(boolean) 11599 */ 11600 public boolean isHorizontalScrollBarEnabled() { 11601 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 11602 } 11603 11604 /** 11605 * <p>Define whether the horizontal scrollbar should be drawn or not. The 11606 * scrollbar is not drawn by default.</p> 11607 * 11608 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 11609 * be painted 11610 * 11611 * @see #isHorizontalScrollBarEnabled() 11612 */ 11613 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 11614 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 11615 mViewFlags ^= SCROLLBARS_HORIZONTAL; 11616 computeOpaqueFlags(); 11617 resolvePadding(); 11618 } 11619 } 11620 11621 /** 11622 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 11623 * scrollbar is not drawn by default.</p> 11624 * 11625 * @return true if the vertical scrollbar should be painted, false 11626 * otherwise 11627 * 11628 * @see #setVerticalScrollBarEnabled(boolean) 11629 */ 11630 public boolean isVerticalScrollBarEnabled() { 11631 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 11632 } 11633 11634 /** 11635 * <p>Define whether the vertical scrollbar should be drawn or not. The 11636 * scrollbar is not drawn by default.</p> 11637 * 11638 * @param verticalScrollBarEnabled true if the vertical scrollbar should 11639 * be painted 11640 * 11641 * @see #isVerticalScrollBarEnabled() 11642 */ 11643 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 11644 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 11645 mViewFlags ^= SCROLLBARS_VERTICAL; 11646 computeOpaqueFlags(); 11647 resolvePadding(); 11648 } 11649 } 11650 11651 /** 11652 * @hide 11653 */ 11654 protected void recomputePadding() { 11655 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 11656 } 11657 11658 /** 11659 * Define whether scrollbars will fade when the view is not scrolling. 11660 * 11661 * @param fadeScrollbars wheter to enable fading 11662 * 11663 * @attr ref android.R.styleable#View_fadeScrollbars 11664 */ 11665 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 11666 initScrollCache(); 11667 final ScrollabilityCache scrollabilityCache = mScrollCache; 11668 scrollabilityCache.fadeScrollBars = fadeScrollbars; 11669 if (fadeScrollbars) { 11670 scrollabilityCache.state = ScrollabilityCache.OFF; 11671 } else { 11672 scrollabilityCache.state = ScrollabilityCache.ON; 11673 } 11674 } 11675 11676 /** 11677 * 11678 * Returns true if scrollbars will fade when this view is not scrolling 11679 * 11680 * @return true if scrollbar fading is enabled 11681 * 11682 * @attr ref android.R.styleable#View_fadeScrollbars 11683 */ 11684 public boolean isScrollbarFadingEnabled() { 11685 return mScrollCache != null && mScrollCache.fadeScrollBars; 11686 } 11687 11688 /** 11689 * 11690 * Returns the delay before scrollbars fade. 11691 * 11692 * @return the delay before scrollbars fade 11693 * 11694 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 11695 */ 11696 public int getScrollBarDefaultDelayBeforeFade() { 11697 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 11698 mScrollCache.scrollBarDefaultDelayBeforeFade; 11699 } 11700 11701 /** 11702 * Define the delay before scrollbars fade. 11703 * 11704 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 11705 * 11706 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 11707 */ 11708 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 11709 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 11710 } 11711 11712 /** 11713 * 11714 * Returns the scrollbar fade duration. 11715 * 11716 * @return the scrollbar fade duration 11717 * 11718 * @attr ref android.R.styleable#View_scrollbarFadeDuration 11719 */ 11720 public int getScrollBarFadeDuration() { 11721 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 11722 mScrollCache.scrollBarFadeDuration; 11723 } 11724 11725 /** 11726 * Define the scrollbar fade duration. 11727 * 11728 * @param scrollBarFadeDuration - the scrollbar fade duration 11729 * 11730 * @attr ref android.R.styleable#View_scrollbarFadeDuration 11731 */ 11732 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 11733 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 11734 } 11735 11736 /** 11737 * 11738 * Returns the scrollbar size. 11739 * 11740 * @return the scrollbar size 11741 * 11742 * @attr ref android.R.styleable#View_scrollbarSize 11743 */ 11744 public int getScrollBarSize() { 11745 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 11746 mScrollCache.scrollBarSize; 11747 } 11748 11749 /** 11750 * Define the scrollbar size. 11751 * 11752 * @param scrollBarSize - the scrollbar size 11753 * 11754 * @attr ref android.R.styleable#View_scrollbarSize 11755 */ 11756 public void setScrollBarSize(int scrollBarSize) { 11757 getScrollCache().scrollBarSize = scrollBarSize; 11758 } 11759 11760 /** 11761 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 11762 * inset. When inset, they add to the padding of the view. And the scrollbars 11763 * can be drawn inside the padding area or on the edge of the view. For example, 11764 * if a view has a background drawable and you want to draw the scrollbars 11765 * inside the padding specified by the drawable, you can use 11766 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 11767 * appear at the edge of the view, ignoring the padding, then you can use 11768 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 11769 * @param style the style of the scrollbars. Should be one of 11770 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 11771 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 11772 * @see #SCROLLBARS_INSIDE_OVERLAY 11773 * @see #SCROLLBARS_INSIDE_INSET 11774 * @see #SCROLLBARS_OUTSIDE_OVERLAY 11775 * @see #SCROLLBARS_OUTSIDE_INSET 11776 * 11777 * @attr ref android.R.styleable#View_scrollbarStyle 11778 */ 11779 public void setScrollBarStyle(@ScrollBarStyle int style) { 11780 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 11781 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 11782 computeOpaqueFlags(); 11783 resolvePadding(); 11784 } 11785 } 11786 11787 /** 11788 * <p>Returns the current scrollbar style.</p> 11789 * @return the current scrollbar style 11790 * @see #SCROLLBARS_INSIDE_OVERLAY 11791 * @see #SCROLLBARS_INSIDE_INSET 11792 * @see #SCROLLBARS_OUTSIDE_OVERLAY 11793 * @see #SCROLLBARS_OUTSIDE_INSET 11794 * 11795 * @attr ref android.R.styleable#View_scrollbarStyle 11796 */ 11797 @ViewDebug.ExportedProperty(mapping = { 11798 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 11799 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 11800 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 11801 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 11802 }) 11803 @ScrollBarStyle 11804 public int getScrollBarStyle() { 11805 return mViewFlags & SCROLLBARS_STYLE_MASK; 11806 } 11807 11808 /** 11809 * <p>Compute the horizontal range that the horizontal scrollbar 11810 * represents.</p> 11811 * 11812 * <p>The range is expressed in arbitrary units that must be the same as the 11813 * units used by {@link #computeHorizontalScrollExtent()} and 11814 * {@link #computeHorizontalScrollOffset()}.</p> 11815 * 11816 * <p>The default range is the drawing width of this view.</p> 11817 * 11818 * @return the total horizontal range represented by the horizontal 11819 * scrollbar 11820 * 11821 * @see #computeHorizontalScrollExtent() 11822 * @see #computeHorizontalScrollOffset() 11823 * @see android.widget.ScrollBarDrawable 11824 */ 11825 protected int computeHorizontalScrollRange() { 11826 return getWidth(); 11827 } 11828 11829 /** 11830 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 11831 * within the horizontal range. This value is used to compute the position 11832 * of the thumb within the scrollbar's track.</p> 11833 * 11834 * <p>The range is expressed in arbitrary units that must be the same as the 11835 * units used by {@link #computeHorizontalScrollRange()} and 11836 * {@link #computeHorizontalScrollExtent()}.</p> 11837 * 11838 * <p>The default offset is the scroll offset of this view.</p> 11839 * 11840 * @return the horizontal offset of the scrollbar's thumb 11841 * 11842 * @see #computeHorizontalScrollRange() 11843 * @see #computeHorizontalScrollExtent() 11844 * @see android.widget.ScrollBarDrawable 11845 */ 11846 protected int computeHorizontalScrollOffset() { 11847 return mScrollX; 11848 } 11849 11850 /** 11851 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 11852 * within the horizontal range. This value is used to compute the length 11853 * of the thumb within the scrollbar's track.</p> 11854 * 11855 * <p>The range is expressed in arbitrary units that must be the same as the 11856 * units used by {@link #computeHorizontalScrollRange()} and 11857 * {@link #computeHorizontalScrollOffset()}.</p> 11858 * 11859 * <p>The default extent is the drawing width of this view.</p> 11860 * 11861 * @return the horizontal extent of the scrollbar's thumb 11862 * 11863 * @see #computeHorizontalScrollRange() 11864 * @see #computeHorizontalScrollOffset() 11865 * @see android.widget.ScrollBarDrawable 11866 */ 11867 protected int computeHorizontalScrollExtent() { 11868 return getWidth(); 11869 } 11870 11871 /** 11872 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 11873 * 11874 * <p>The range is expressed in arbitrary units that must be the same as the 11875 * units used by {@link #computeVerticalScrollExtent()} and 11876 * {@link #computeVerticalScrollOffset()}.</p> 11877 * 11878 * @return the total vertical range represented by the vertical scrollbar 11879 * 11880 * <p>The default range is the drawing height of this view.</p> 11881 * 11882 * @see #computeVerticalScrollExtent() 11883 * @see #computeVerticalScrollOffset() 11884 * @see android.widget.ScrollBarDrawable 11885 */ 11886 protected int computeVerticalScrollRange() { 11887 return getHeight(); 11888 } 11889 11890 /** 11891 * <p>Compute the vertical offset of the vertical scrollbar's thumb 11892 * within the horizontal range. This value is used to compute the position 11893 * of the thumb within the scrollbar's track.</p> 11894 * 11895 * <p>The range is expressed in arbitrary units that must be the same as the 11896 * units used by {@link #computeVerticalScrollRange()} and 11897 * {@link #computeVerticalScrollExtent()}.</p> 11898 * 11899 * <p>The default offset is the scroll offset of this view.</p> 11900 * 11901 * @return the vertical offset of the scrollbar's thumb 11902 * 11903 * @see #computeVerticalScrollRange() 11904 * @see #computeVerticalScrollExtent() 11905 * @see android.widget.ScrollBarDrawable 11906 */ 11907 protected int computeVerticalScrollOffset() { 11908 return mScrollY; 11909 } 11910 11911 /** 11912 * <p>Compute the vertical extent of the horizontal scrollbar's thumb 11913 * within the vertical range. This value is used to compute the length 11914 * of the thumb within the scrollbar's track.</p> 11915 * 11916 * <p>The range is expressed in arbitrary units that must be the same as the 11917 * units used by {@link #computeVerticalScrollRange()} and 11918 * {@link #computeVerticalScrollOffset()}.</p> 11919 * 11920 * <p>The default extent is the drawing height of this view.</p> 11921 * 11922 * @return the vertical extent of the scrollbar's thumb 11923 * 11924 * @see #computeVerticalScrollRange() 11925 * @see #computeVerticalScrollOffset() 11926 * @see android.widget.ScrollBarDrawable 11927 */ 11928 protected int computeVerticalScrollExtent() { 11929 return getHeight(); 11930 } 11931 11932 /** 11933 * Check if this view can be scrolled horizontally in a certain direction. 11934 * 11935 * @param direction Negative to check scrolling left, positive to check scrolling right. 11936 * @return true if this view can be scrolled in the specified direction, false otherwise. 11937 */ 11938 public boolean canScrollHorizontally(int direction) { 11939 final int offset = computeHorizontalScrollOffset(); 11940 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 11941 if (range == 0) return false; 11942 if (direction < 0) { 11943 return offset > 0; 11944 } else { 11945 return offset < range - 1; 11946 } 11947 } 11948 11949 /** 11950 * Check if this view can be scrolled vertically in a certain direction. 11951 * 11952 * @param direction Negative to check scrolling up, positive to check scrolling down. 11953 * @return true if this view can be scrolled in the specified direction, false otherwise. 11954 */ 11955 public boolean canScrollVertically(int direction) { 11956 final int offset = computeVerticalScrollOffset(); 11957 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 11958 if (range == 0) return false; 11959 if (direction < 0) { 11960 return offset > 0; 11961 } else { 11962 return offset < range - 1; 11963 } 11964 } 11965 11966 /** 11967 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 11968 * scrollbars are painted only if they have been awakened first.</p> 11969 * 11970 * @param canvas the canvas on which to draw the scrollbars 11971 * 11972 * @see #awakenScrollBars(int) 11973 */ 11974 protected final void onDrawScrollBars(Canvas canvas) { 11975 // scrollbars are drawn only when the animation is running 11976 final ScrollabilityCache cache = mScrollCache; 11977 if (cache != null) { 11978 11979 int state = cache.state; 11980 11981 if (state == ScrollabilityCache.OFF) { 11982 return; 11983 } 11984 11985 boolean invalidate = false; 11986 11987 if (state == ScrollabilityCache.FADING) { 11988 // We're fading -- get our fade interpolation 11989 if (cache.interpolatorValues == null) { 11990 cache.interpolatorValues = new float[1]; 11991 } 11992 11993 float[] values = cache.interpolatorValues; 11994 11995 // Stops the animation if we're done 11996 if (cache.scrollBarInterpolator.timeToValues(values) == 11997 Interpolator.Result.FREEZE_END) { 11998 cache.state = ScrollabilityCache.OFF; 11999 } else { 12000 cache.scrollBar.setAlpha(Math.round(values[0])); 12001 } 12002 12003 // This will make the scroll bars inval themselves after 12004 // drawing. We only want this when we're fading so that 12005 // we prevent excessive redraws 12006 invalidate = true; 12007 } else { 12008 // We're just on -- but we may have been fading before so 12009 // reset alpha 12010 cache.scrollBar.setAlpha(255); 12011 } 12012 12013 12014 final int viewFlags = mViewFlags; 12015 12016 final boolean drawHorizontalScrollBar = 12017 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 12018 final boolean drawVerticalScrollBar = 12019 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 12020 && !isVerticalScrollBarHidden(); 12021 12022 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 12023 final int width = mRight - mLeft; 12024 final int height = mBottom - mTop; 12025 12026 final ScrollBarDrawable scrollBar = cache.scrollBar; 12027 12028 final int scrollX = mScrollX; 12029 final int scrollY = mScrollY; 12030 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 12031 12032 int left; 12033 int top; 12034 int right; 12035 int bottom; 12036 12037 if (drawHorizontalScrollBar) { 12038 int size = scrollBar.getSize(false); 12039 if (size <= 0) { 12040 size = cache.scrollBarSize; 12041 } 12042 12043 scrollBar.setParameters(computeHorizontalScrollRange(), 12044 computeHorizontalScrollOffset(), 12045 computeHorizontalScrollExtent(), false); 12046 final int verticalScrollBarGap = drawVerticalScrollBar ? 12047 getVerticalScrollbarWidth() : 0; 12048 top = scrollY + height - size - (mUserPaddingBottom & inside); 12049 left = scrollX + (mPaddingLeft & inside); 12050 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 12051 bottom = top + size; 12052 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 12053 if (invalidate) { 12054 invalidate(left, top, right, bottom); 12055 } 12056 } 12057 12058 if (drawVerticalScrollBar) { 12059 int size = scrollBar.getSize(true); 12060 if (size <= 0) { 12061 size = cache.scrollBarSize; 12062 } 12063 12064 scrollBar.setParameters(computeVerticalScrollRange(), 12065 computeVerticalScrollOffset(), 12066 computeVerticalScrollExtent(), true); 12067 int verticalScrollbarPosition = mVerticalScrollbarPosition; 12068 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 12069 verticalScrollbarPosition = isLayoutRtl() ? 12070 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 12071 } 12072 switch (verticalScrollbarPosition) { 12073 default: 12074 case SCROLLBAR_POSITION_RIGHT: 12075 left = scrollX + width - size - (mUserPaddingRight & inside); 12076 break; 12077 case SCROLLBAR_POSITION_LEFT: 12078 left = scrollX + (mUserPaddingLeft & inside); 12079 break; 12080 } 12081 top = scrollY + (mPaddingTop & inside); 12082 right = left + size; 12083 bottom = scrollY + height - (mUserPaddingBottom & inside); 12084 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 12085 if (invalidate) { 12086 invalidate(left, top, right, bottom); 12087 } 12088 } 12089 } 12090 } 12091 } 12092 12093 /** 12094 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 12095 * FastScroller is visible. 12096 * @return whether to temporarily hide the vertical scrollbar 12097 * @hide 12098 */ 12099 protected boolean isVerticalScrollBarHidden() { 12100 return false; 12101 } 12102 12103 /** 12104 * <p>Draw the horizontal scrollbar if 12105 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 12106 * 12107 * @param canvas the canvas on which to draw the scrollbar 12108 * @param scrollBar the scrollbar's drawable 12109 * 12110 * @see #isHorizontalScrollBarEnabled() 12111 * @see #computeHorizontalScrollRange() 12112 * @see #computeHorizontalScrollExtent() 12113 * @see #computeHorizontalScrollOffset() 12114 * @see android.widget.ScrollBarDrawable 12115 * @hide 12116 */ 12117 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 12118 int l, int t, int r, int b) { 12119 scrollBar.setBounds(l, t, r, b); 12120 scrollBar.draw(canvas); 12121 } 12122 12123 /** 12124 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 12125 * returns true.</p> 12126 * 12127 * @param canvas the canvas on which to draw the scrollbar 12128 * @param scrollBar the scrollbar's drawable 12129 * 12130 * @see #isVerticalScrollBarEnabled() 12131 * @see #computeVerticalScrollRange() 12132 * @see #computeVerticalScrollExtent() 12133 * @see #computeVerticalScrollOffset() 12134 * @see android.widget.ScrollBarDrawable 12135 * @hide 12136 */ 12137 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 12138 int l, int t, int r, int b) { 12139 scrollBar.setBounds(l, t, r, b); 12140 scrollBar.draw(canvas); 12141 } 12142 12143 /** 12144 * Implement this to do your drawing. 12145 * 12146 * @param canvas the canvas on which the background will be drawn 12147 */ 12148 protected void onDraw(Canvas canvas) { 12149 } 12150 12151 /* 12152 * Caller is responsible for calling requestLayout if necessary. 12153 * (This allows addViewInLayout to not request a new layout.) 12154 */ 12155 void assignParent(ViewParent parent) { 12156 if (mParent == null) { 12157 mParent = parent; 12158 } else if (parent == null) { 12159 mParent = null; 12160 } else { 12161 throw new RuntimeException("view " + this + " being added, but" 12162 + " it already has a parent"); 12163 } 12164 } 12165 12166 /** 12167 * This is called when the view is attached to a window. At this point it 12168 * has a Surface and will start drawing. Note that this function is 12169 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 12170 * however it may be called any time before the first onDraw -- including 12171 * before or after {@link #onMeasure(int, int)}. 12172 * 12173 * @see #onDetachedFromWindow() 12174 */ 12175 protected void onAttachedToWindow() { 12176 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 12177 mParent.requestTransparentRegion(this); 12178 } 12179 12180 if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 12181 initialAwakenScrollBars(); 12182 mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 12183 } 12184 12185 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 12186 12187 jumpDrawablesToCurrentState(); 12188 12189 resetSubtreeAccessibilityStateChanged(); 12190 12191 if (isFocused()) { 12192 InputMethodManager imm = InputMethodManager.peekInstance(); 12193 imm.focusIn(this); 12194 } 12195 12196 if (mDisplayList != null) { 12197 mDisplayList.clearDirty(); 12198 } 12199 } 12200 12201 /** 12202 * Resolve all RTL related properties. 12203 * 12204 * @return true if resolution of RTL properties has been done 12205 * 12206 * @hide 12207 */ 12208 public boolean resolveRtlPropertiesIfNeeded() { 12209 if (!needRtlPropertiesResolution()) return false; 12210 12211 // Order is important here: LayoutDirection MUST be resolved first 12212 if (!isLayoutDirectionResolved()) { 12213 resolveLayoutDirection(); 12214 resolveLayoutParams(); 12215 } 12216 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 12217 if (!isTextDirectionResolved()) { 12218 resolveTextDirection(); 12219 } 12220 if (!isTextAlignmentResolved()) { 12221 resolveTextAlignment(); 12222 } 12223 if (!isPaddingResolved()) { 12224 resolvePadding(); 12225 } 12226 if (!isDrawablesResolved()) { 12227 resolveDrawables(); 12228 } 12229 onRtlPropertiesChanged(getLayoutDirection()); 12230 return true; 12231 } 12232 12233 /** 12234 * Reset resolution of all RTL related properties. 12235 * 12236 * @hide 12237 */ 12238 public void resetRtlProperties() { 12239 resetResolvedLayoutDirection(); 12240 resetResolvedTextDirection(); 12241 resetResolvedTextAlignment(); 12242 resetResolvedPadding(); 12243 resetResolvedDrawables(); 12244 } 12245 12246 /** 12247 * @see #onScreenStateChanged(int) 12248 */ 12249 void dispatchScreenStateChanged(int screenState) { 12250 onScreenStateChanged(screenState); 12251 } 12252 12253 /** 12254 * This method is called whenever the state of the screen this view is 12255 * attached to changes. A state change will usually occurs when the screen 12256 * turns on or off (whether it happens automatically or the user does it 12257 * manually.) 12258 * 12259 * @param screenState The new state of the screen. Can be either 12260 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 12261 */ 12262 public void onScreenStateChanged(int screenState) { 12263 } 12264 12265 /** 12266 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 12267 */ 12268 private boolean hasRtlSupport() { 12269 return mContext.getApplicationInfo().hasRtlSupport(); 12270 } 12271 12272 /** 12273 * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or 12274 * RTL not supported) 12275 */ 12276 private boolean isRtlCompatibilityMode() { 12277 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 12278 return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport(); 12279 } 12280 12281 /** 12282 * @return true if RTL properties need resolution. 12283 * 12284 */ 12285 private boolean needRtlPropertiesResolution() { 12286 return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED; 12287 } 12288 12289 /** 12290 * Called when any RTL property (layout direction or text direction or text alignment) has 12291 * been changed. 12292 * 12293 * Subclasses need to override this method to take care of cached information that depends on the 12294 * resolved layout direction, or to inform child views that inherit their layout direction. 12295 * 12296 * The default implementation does nothing. 12297 * 12298 * @param layoutDirection the direction of the layout 12299 * 12300 * @see #LAYOUT_DIRECTION_LTR 12301 * @see #LAYOUT_DIRECTION_RTL 12302 */ 12303 public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) { 12304 } 12305 12306 /** 12307 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 12308 * that the parent directionality can and will be resolved before its children. 12309 * 12310 * @return true if resolution has been done, false otherwise. 12311 * 12312 * @hide 12313 */ 12314 public boolean resolveLayoutDirection() { 12315 // Clear any previous layout direction resolution 12316 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 12317 12318 if (hasRtlSupport()) { 12319 // Set resolved depending on layout direction 12320 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 12321 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 12322 case LAYOUT_DIRECTION_INHERIT: 12323 // We cannot resolve yet. LTR is by default and let the resolution happen again 12324 // later to get the correct resolved value 12325 if (!canResolveLayoutDirection()) return false; 12326 12327 // Parent has not yet resolved, LTR is still the default 12328 try { 12329 if (!mParent.isLayoutDirectionResolved()) return false; 12330 12331 if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 12332 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12333 } 12334 } catch (AbstractMethodError e) { 12335 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 12336 " does not fully implement ViewParent", e); 12337 } 12338 break; 12339 case LAYOUT_DIRECTION_RTL: 12340 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12341 break; 12342 case LAYOUT_DIRECTION_LOCALE: 12343 if((LAYOUT_DIRECTION_RTL == 12344 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) { 12345 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12346 } 12347 break; 12348 default: 12349 // Nothing to do, LTR by default 12350 } 12351 } 12352 12353 // Set to resolved 12354 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 12355 return true; 12356 } 12357 12358 /** 12359 * Check if layout direction resolution can be done. 12360 * 12361 * @return true if layout direction resolution can be done otherwise return false. 12362 */ 12363 public boolean canResolveLayoutDirection() { 12364 switch (getRawLayoutDirection()) { 12365 case LAYOUT_DIRECTION_INHERIT: 12366 if (mParent != null) { 12367 try { 12368 return mParent.canResolveLayoutDirection(); 12369 } catch (AbstractMethodError e) { 12370 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 12371 " does not fully implement ViewParent", e); 12372 } 12373 } 12374 return false; 12375 12376 default: 12377 return true; 12378 } 12379 } 12380 12381 /** 12382 * Reset the resolved layout direction. Layout direction will be resolved during a call to 12383 * {@link #onMeasure(int, int)}. 12384 * 12385 * @hide 12386 */ 12387 public void resetResolvedLayoutDirection() { 12388 // Reset the current resolved bits 12389 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 12390 } 12391 12392 /** 12393 * @return true if the layout direction is inherited. 12394 * 12395 * @hide 12396 */ 12397 public boolean isLayoutDirectionInherited() { 12398 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT); 12399 } 12400 12401 /** 12402 * @return true if layout direction has been resolved. 12403 */ 12404 public boolean isLayoutDirectionResolved() { 12405 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED; 12406 } 12407 12408 /** 12409 * Return if padding has been resolved 12410 * 12411 * @hide 12412 */ 12413 boolean isPaddingResolved() { 12414 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED; 12415 } 12416 12417 /** 12418 * Resolves padding depending on layout direction, if applicable, and 12419 * recomputes internal padding values to adjust for scroll bars. 12420 * 12421 * @hide 12422 */ 12423 public void resolvePadding() { 12424 final int resolvedLayoutDirection = getLayoutDirection(); 12425 12426 if (!isRtlCompatibilityMode()) { 12427 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 12428 // If start / end padding are defined, they will be resolved (hence overriding) to 12429 // left / right or right / left depending on the resolved layout direction. 12430 // If start / end padding are not defined, use the left / right ones. 12431 switch (resolvedLayoutDirection) { 12432 case LAYOUT_DIRECTION_RTL: 12433 if (mUserPaddingStart != UNDEFINED_PADDING) { 12434 mUserPaddingRight = mUserPaddingStart; 12435 } else { 12436 mUserPaddingRight = mUserPaddingRightInitial; 12437 } 12438 if (mUserPaddingEnd != UNDEFINED_PADDING) { 12439 mUserPaddingLeft = mUserPaddingEnd; 12440 } else { 12441 mUserPaddingLeft = mUserPaddingLeftInitial; 12442 } 12443 break; 12444 case LAYOUT_DIRECTION_LTR: 12445 default: 12446 if (mUserPaddingStart != UNDEFINED_PADDING) { 12447 mUserPaddingLeft = mUserPaddingStart; 12448 } else { 12449 mUserPaddingLeft = mUserPaddingLeftInitial; 12450 } 12451 if (mUserPaddingEnd != UNDEFINED_PADDING) { 12452 mUserPaddingRight = mUserPaddingEnd; 12453 } else { 12454 mUserPaddingRight = mUserPaddingRightInitial; 12455 } 12456 } 12457 12458 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 12459 } 12460 12461 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 12462 onRtlPropertiesChanged(resolvedLayoutDirection); 12463 12464 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 12465 } 12466 12467 /** 12468 * Reset the resolved layout direction. 12469 * 12470 * @hide 12471 */ 12472 public void resetResolvedPadding() { 12473 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 12474 } 12475 12476 /** 12477 * This is called when the view is detached from a window. At this point it 12478 * no longer has a surface for drawing. 12479 * 12480 * @see #onAttachedToWindow() 12481 */ 12482 protected void onDetachedFromWindow() { 12483 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 12484 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 12485 12486 removeUnsetPressCallback(); 12487 removeLongPressCallback(); 12488 removePerformClickCallback(); 12489 removeSendViewScrolledAccessibilityEventCallback(); 12490 12491 destroyDrawingCache(); 12492 destroyLayer(false); 12493 12494 cleanupDraw(); 12495 12496 mCurrentAnimation = null; 12497 } 12498 12499 private void cleanupDraw() { 12500 if (mAttachInfo != null) { 12501 if (mDisplayList != null) { 12502 mDisplayList.markDirty(); 12503 mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList); 12504 } 12505 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 12506 } else { 12507 // Should never happen 12508 resetDisplayList(); 12509 } 12510 } 12511 12512 /** 12513 * This method ensures the hardware renderer is in a valid state 12514 * before executing the specified action. 12515 * 12516 * This method will attempt to set a valid state even if the window 12517 * the renderer is attached to was destroyed. 12518 * 12519 * This method is not guaranteed to work. If the hardware renderer 12520 * does not exist or cannot be put in a valid state, this method 12521 * will not executed the specified action. 12522 * 12523 * The specified action is executed synchronously. 12524 * 12525 * @param action The action to execute after the renderer is in a valid state 12526 * 12527 * @return True if the specified Runnable was executed, false otherwise 12528 * 12529 * @hide 12530 */ 12531 public boolean executeHardwareAction(Runnable action) { 12532 //noinspection SimplifiableIfStatement 12533 if (mAttachInfo != null && mAttachInfo.mHardwareRenderer != null) { 12534 return mAttachInfo.mHardwareRenderer.safelyRun(action); 12535 } 12536 return false; 12537 } 12538 12539 void invalidateInheritedLayoutMode(int layoutModeOfRoot) { 12540 } 12541 12542 /** 12543 * @return The number of times this view has been attached to a window 12544 */ 12545 protected int getWindowAttachCount() { 12546 return mWindowAttachCount; 12547 } 12548 12549 /** 12550 * Retrieve a unique token identifying the window this view is attached to. 12551 * @return Return the window's token for use in 12552 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 12553 */ 12554 public IBinder getWindowToken() { 12555 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 12556 } 12557 12558 /** 12559 * Retrieve the {@link WindowId} for the window this view is 12560 * currently attached to. 12561 */ 12562 public WindowId getWindowId() { 12563 if (mAttachInfo == null) { 12564 return null; 12565 } 12566 if (mAttachInfo.mWindowId == null) { 12567 try { 12568 mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId( 12569 mAttachInfo.mWindowToken); 12570 mAttachInfo.mWindowId = new WindowId( 12571 mAttachInfo.mIWindowId); 12572 } catch (RemoteException e) { 12573 } 12574 } 12575 return mAttachInfo.mWindowId; 12576 } 12577 12578 /** 12579 * Retrieve a unique token identifying the top-level "real" window of 12580 * the window that this view is attached to. That is, this is like 12581 * {@link #getWindowToken}, except if the window this view in is a panel 12582 * window (attached to another containing window), then the token of 12583 * the containing window is returned instead. 12584 * 12585 * @return Returns the associated window token, either 12586 * {@link #getWindowToken()} or the containing window's token. 12587 */ 12588 public IBinder getApplicationWindowToken() { 12589 AttachInfo ai = mAttachInfo; 12590 if (ai != null) { 12591 IBinder appWindowToken = ai.mPanelParentWindowToken; 12592 if (appWindowToken == null) { 12593 appWindowToken = ai.mWindowToken; 12594 } 12595 return appWindowToken; 12596 } 12597 return null; 12598 } 12599 12600 /** 12601 * Gets the logical display to which the view's window has been attached. 12602 * 12603 * @return The logical display, or null if the view is not currently attached to a window. 12604 */ 12605 public Display getDisplay() { 12606 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 12607 } 12608 12609 /** 12610 * Retrieve private session object this view hierarchy is using to 12611 * communicate with the window manager. 12612 * @return the session object to communicate with the window manager 12613 */ 12614 /*package*/ IWindowSession getWindowSession() { 12615 return mAttachInfo != null ? mAttachInfo.mSession : null; 12616 } 12617 12618 /** 12619 * @param info the {@link android.view.View.AttachInfo} to associated with 12620 * this view 12621 */ 12622 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 12623 //System.out.println("Attached! " + this); 12624 mAttachInfo = info; 12625 if (mOverlay != null) { 12626 mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility); 12627 } 12628 mWindowAttachCount++; 12629 // We will need to evaluate the drawable state at least once. 12630 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 12631 if (mFloatingTreeObserver != null) { 12632 info.mTreeObserver.merge(mFloatingTreeObserver); 12633 mFloatingTreeObserver = null; 12634 } 12635 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 12636 mAttachInfo.mScrollContainers.add(this); 12637 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 12638 } 12639 performCollectViewAttributes(mAttachInfo, visibility); 12640 onAttachedToWindow(); 12641 12642 ListenerInfo li = mListenerInfo; 12643 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 12644 li != null ? li.mOnAttachStateChangeListeners : null; 12645 if (listeners != null && listeners.size() > 0) { 12646 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 12647 // perform the dispatching. The iterator is a safe guard against listeners that 12648 // could mutate the list by calling the various add/remove methods. This prevents 12649 // the array from being modified while we iterate it. 12650 for (OnAttachStateChangeListener listener : listeners) { 12651 listener.onViewAttachedToWindow(this); 12652 } 12653 } 12654 12655 int vis = info.mWindowVisibility; 12656 if (vis != GONE) { 12657 onWindowVisibilityChanged(vis); 12658 } 12659 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 12660 // If nobody has evaluated the drawable state yet, then do it now. 12661 refreshDrawableState(); 12662 } 12663 needGlobalAttributesUpdate(false); 12664 } 12665 12666 void dispatchDetachedFromWindow() { 12667 AttachInfo info = mAttachInfo; 12668 if (info != null) { 12669 int vis = info.mWindowVisibility; 12670 if (vis != GONE) { 12671 onWindowVisibilityChanged(GONE); 12672 } 12673 } 12674 12675 onDetachedFromWindow(); 12676 12677 ListenerInfo li = mListenerInfo; 12678 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 12679 li != null ? li.mOnAttachStateChangeListeners : null; 12680 if (listeners != null && listeners.size() > 0) { 12681 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 12682 // perform the dispatching. The iterator is a safe guard against listeners that 12683 // could mutate the list by calling the various add/remove methods. This prevents 12684 // the array from being modified while we iterate it. 12685 for (OnAttachStateChangeListener listener : listeners) { 12686 listener.onViewDetachedFromWindow(this); 12687 } 12688 } 12689 12690 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 12691 mAttachInfo.mScrollContainers.remove(this); 12692 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 12693 } 12694 12695 mAttachInfo = null; 12696 if (mOverlay != null) { 12697 mOverlay.getOverlayView().dispatchDetachedFromWindow(); 12698 } 12699 } 12700 12701 /** 12702 * Cancel any deferred high-level input events that were previously posted to the event queue. 12703 * 12704 * <p>Many views post high-level events such as click handlers to the event queue 12705 * to run deferred in order to preserve a desired user experience - clearing visible 12706 * pressed states before executing, etc. This method will abort any events of this nature 12707 * that are currently in flight.</p> 12708 * 12709 * <p>Custom views that generate their own high-level deferred input events should override 12710 * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p> 12711 * 12712 * <p>This will also cancel pending input events for any child views.</p> 12713 * 12714 * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases. 12715 * This will not impact newer events posted after this call that may occur as a result of 12716 * lower-level input events still waiting in the queue. If you are trying to prevent 12717 * double-submitted events for the duration of some sort of asynchronous transaction 12718 * you should also take other steps to protect against unexpected double inputs e.g. calling 12719 * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when 12720 * the transaction completes, tracking already submitted transaction IDs, etc.</p> 12721 */ 12722 public final void cancelPendingInputEvents() { 12723 dispatchCancelPendingInputEvents(); 12724 } 12725 12726 /** 12727 * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight. 12728 * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling. 12729 */ 12730 void dispatchCancelPendingInputEvents() { 12731 mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER; 12732 onCancelPendingInputEvents(); 12733 if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) { 12734 throw new SuperNotCalledException("View " + getClass().getSimpleName() + 12735 " did not call through to super.onCancelPendingInputEvents()"); 12736 } 12737 } 12738 12739 /** 12740 * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or 12741 * a parent view. 12742 * 12743 * <p>This method is responsible for removing any pending high-level input events that were 12744 * posted to the event queue to run later. Custom view classes that post their own deferred 12745 * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or 12746 * {@link android.os.Handler} should override this method, call 12747 * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate. 12748 * </p> 12749 */ 12750 public void onCancelPendingInputEvents() { 12751 removePerformClickCallback(); 12752 cancelLongPress(); 12753 mPrivateFlags3 |= PFLAG3_CALLED_SUPER; 12754 } 12755 12756 /** 12757 * Store this view hierarchy's frozen state into the given container. 12758 * 12759 * @param container The SparseArray in which to save the view's state. 12760 * 12761 * @see #restoreHierarchyState(android.util.SparseArray) 12762 * @see #dispatchSaveInstanceState(android.util.SparseArray) 12763 * @see #onSaveInstanceState() 12764 */ 12765 public void saveHierarchyState(SparseArray<Parcelable> container) { 12766 dispatchSaveInstanceState(container); 12767 } 12768 12769 /** 12770 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 12771 * this view and its children. May be overridden to modify how freezing happens to a 12772 * view's children; for example, some views may want to not store state for their children. 12773 * 12774 * @param container The SparseArray in which to save the view's state. 12775 * 12776 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 12777 * @see #saveHierarchyState(android.util.SparseArray) 12778 * @see #onSaveInstanceState() 12779 */ 12780 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 12781 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 12782 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 12783 Parcelable state = onSaveInstanceState(); 12784 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 12785 throw new IllegalStateException( 12786 "Derived class did not call super.onSaveInstanceState()"); 12787 } 12788 if (state != null) { 12789 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 12790 // + ": " + state); 12791 container.put(mID, state); 12792 } 12793 } 12794 } 12795 12796 /** 12797 * Hook allowing a view to generate a representation of its internal state 12798 * that can later be used to create a new instance with that same state. 12799 * This state should only contain information that is not persistent or can 12800 * not be reconstructed later. For example, you will never store your 12801 * current position on screen because that will be computed again when a 12802 * new instance of the view is placed in its view hierarchy. 12803 * <p> 12804 * Some examples of things you may store here: the current cursor position 12805 * in a text view (but usually not the text itself since that is stored in a 12806 * content provider or other persistent storage), the currently selected 12807 * item in a list view. 12808 * 12809 * @return Returns a Parcelable object containing the view's current dynamic 12810 * state, or null if there is nothing interesting to save. The 12811 * default implementation returns null. 12812 * @see #onRestoreInstanceState(android.os.Parcelable) 12813 * @see #saveHierarchyState(android.util.SparseArray) 12814 * @see #dispatchSaveInstanceState(android.util.SparseArray) 12815 * @see #setSaveEnabled(boolean) 12816 */ 12817 protected Parcelable onSaveInstanceState() { 12818 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 12819 return BaseSavedState.EMPTY_STATE; 12820 } 12821 12822 /** 12823 * Restore this view hierarchy's frozen state from the given container. 12824 * 12825 * @param container The SparseArray which holds previously frozen states. 12826 * 12827 * @see #saveHierarchyState(android.util.SparseArray) 12828 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 12829 * @see #onRestoreInstanceState(android.os.Parcelable) 12830 */ 12831 public void restoreHierarchyState(SparseArray<Parcelable> container) { 12832 dispatchRestoreInstanceState(container); 12833 } 12834 12835 /** 12836 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 12837 * state for this view and its children. May be overridden to modify how restoring 12838 * happens to a view's children; for example, some views may want to not store state 12839 * for their children. 12840 * 12841 * @param container The SparseArray which holds previously saved state. 12842 * 12843 * @see #dispatchSaveInstanceState(android.util.SparseArray) 12844 * @see #restoreHierarchyState(android.util.SparseArray) 12845 * @see #onRestoreInstanceState(android.os.Parcelable) 12846 */ 12847 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 12848 if (mID != NO_ID) { 12849 Parcelable state = container.get(mID); 12850 if (state != null) { 12851 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 12852 // + ": " + state); 12853 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 12854 onRestoreInstanceState(state); 12855 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 12856 throw new IllegalStateException( 12857 "Derived class did not call super.onRestoreInstanceState()"); 12858 } 12859 } 12860 } 12861 } 12862 12863 /** 12864 * Hook allowing a view to re-apply a representation of its internal state that had previously 12865 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 12866 * null state. 12867 * 12868 * @param state The frozen state that had previously been returned by 12869 * {@link #onSaveInstanceState}. 12870 * 12871 * @see #onSaveInstanceState() 12872 * @see #restoreHierarchyState(android.util.SparseArray) 12873 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 12874 */ 12875 protected void onRestoreInstanceState(Parcelable state) { 12876 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 12877 if (state != BaseSavedState.EMPTY_STATE && state != null) { 12878 throw new IllegalArgumentException("Wrong state class, expecting View State but " 12879 + "received " + state.getClass().toString() + " instead. This usually happens " 12880 + "when two views of different type have the same id in the same hierarchy. " 12881 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 12882 + "other views do not use the same id."); 12883 } 12884 } 12885 12886 /** 12887 * <p>Return the time at which the drawing of the view hierarchy started.</p> 12888 * 12889 * @return the drawing start time in milliseconds 12890 */ 12891 public long getDrawingTime() { 12892 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 12893 } 12894 12895 /** 12896 * <p>Enables or disables the duplication of the parent's state into this view. When 12897 * duplication is enabled, this view gets its drawable state from its parent rather 12898 * than from its own internal properties.</p> 12899 * 12900 * <p>Note: in the current implementation, setting this property to true after the 12901 * view was added to a ViewGroup might have no effect at all. This property should 12902 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 12903 * 12904 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 12905 * property is enabled, an exception will be thrown.</p> 12906 * 12907 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 12908 * parent, these states should not be affected by this method.</p> 12909 * 12910 * @param enabled True to enable duplication of the parent's drawable state, false 12911 * to disable it. 12912 * 12913 * @see #getDrawableState() 12914 * @see #isDuplicateParentStateEnabled() 12915 */ 12916 public void setDuplicateParentStateEnabled(boolean enabled) { 12917 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 12918 } 12919 12920 /** 12921 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 12922 * 12923 * @return True if this view's drawable state is duplicated from the parent, 12924 * false otherwise 12925 * 12926 * @see #getDrawableState() 12927 * @see #setDuplicateParentStateEnabled(boolean) 12928 */ 12929 public boolean isDuplicateParentStateEnabled() { 12930 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 12931 } 12932 12933 /** 12934 * <p>Specifies the type of layer backing this view. The layer can be 12935 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 12936 * {@link #LAYER_TYPE_HARDWARE}.</p> 12937 * 12938 * <p>A layer is associated with an optional {@link android.graphics.Paint} 12939 * instance that controls how the layer is composed on screen. The following 12940 * properties of the paint are taken into account when composing the layer:</p> 12941 * <ul> 12942 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 12943 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 12944 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 12945 * </ul> 12946 * 12947 * <p>If this view has an alpha value set to < 1.0 by calling 12948 * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded 12949 * by this view's alpha value.</p> 12950 * 12951 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE}, 12952 * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE} 12953 * for more information on when and how to use layers.</p> 12954 * 12955 * @param layerType The type of layer to use with this view, must be one of 12956 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 12957 * {@link #LAYER_TYPE_HARDWARE} 12958 * @param paint The paint used to compose the layer. This argument is optional 12959 * and can be null. It is ignored when the layer type is 12960 * {@link #LAYER_TYPE_NONE} 12961 * 12962 * @see #getLayerType() 12963 * @see #LAYER_TYPE_NONE 12964 * @see #LAYER_TYPE_SOFTWARE 12965 * @see #LAYER_TYPE_HARDWARE 12966 * @see #setAlpha(float) 12967 * 12968 * @attr ref android.R.styleable#View_layerType 12969 */ 12970 public void setLayerType(int layerType, Paint paint) { 12971 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 12972 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 12973 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 12974 } 12975 12976 if (layerType == mLayerType) { 12977 if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) { 12978 mLayerPaint = paint == null ? new Paint() : paint; 12979 invalidateParentCaches(); 12980 invalidate(true); 12981 } 12982 return; 12983 } 12984 12985 // Destroy any previous software drawing cache if needed 12986 switch (mLayerType) { 12987 case LAYER_TYPE_HARDWARE: 12988 destroyLayer(false); 12989 // fall through - non-accelerated views may use software layer mechanism instead 12990 case LAYER_TYPE_SOFTWARE: 12991 destroyDrawingCache(); 12992 break; 12993 default: 12994 break; 12995 } 12996 12997 mLayerType = layerType; 12998 final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE; 12999 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 13000 mLocalDirtyRect = layerDisabled ? null : new Rect(); 13001 13002 invalidateParentCaches(); 13003 invalidate(true); 13004 } 13005 13006 /** 13007 * Updates the {@link Paint} object used with the current layer (used only if the current 13008 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 13009 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 13010 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 13011 * ensure that the view gets redrawn immediately. 13012 * 13013 * <p>A layer is associated with an optional {@link android.graphics.Paint} 13014 * instance that controls how the layer is composed on screen. The following 13015 * properties of the paint are taken into account when composing the layer:</p> 13016 * <ul> 13017 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 13018 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 13019 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 13020 * </ul> 13021 * 13022 * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the 13023 * alpha value of the layer's paint is superceded by this view's alpha value.</p> 13024 * 13025 * @param paint The paint used to compose the layer. This argument is optional 13026 * and can be null. It is ignored when the layer type is 13027 * {@link #LAYER_TYPE_NONE} 13028 * 13029 * @see #setLayerType(int, android.graphics.Paint) 13030 */ 13031 public void setLayerPaint(Paint paint) { 13032 int layerType = getLayerType(); 13033 if (layerType != LAYER_TYPE_NONE) { 13034 mLayerPaint = paint == null ? new Paint() : paint; 13035 if (layerType == LAYER_TYPE_HARDWARE) { 13036 HardwareLayer layer = getHardwareLayer(); 13037 if (layer != null) { 13038 layer.setLayerPaint(paint); 13039 } 13040 invalidateViewProperty(false, false); 13041 } else { 13042 invalidate(); 13043 } 13044 } 13045 } 13046 13047 /** 13048 * Indicates whether this view has a static layer. A view with layer type 13049 * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are 13050 * dynamic. 13051 */ 13052 boolean hasStaticLayer() { 13053 return true; 13054 } 13055 13056 /** 13057 * Indicates what type of layer is currently associated with this view. By default 13058 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 13059 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 13060 * for more information on the different types of layers. 13061 * 13062 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13063 * {@link #LAYER_TYPE_HARDWARE} 13064 * 13065 * @see #setLayerType(int, android.graphics.Paint) 13066 * @see #buildLayer() 13067 * @see #LAYER_TYPE_NONE 13068 * @see #LAYER_TYPE_SOFTWARE 13069 * @see #LAYER_TYPE_HARDWARE 13070 */ 13071 public int getLayerType() { 13072 return mLayerType; 13073 } 13074 13075 /** 13076 * Forces this view's layer to be created and this view to be rendered 13077 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 13078 * invoking this method will have no effect. 13079 * 13080 * This method can for instance be used to render a view into its layer before 13081 * starting an animation. If this view is complex, rendering into the layer 13082 * before starting the animation will avoid skipping frames. 13083 * 13084 * @throws IllegalStateException If this view is not attached to a window 13085 * 13086 * @see #setLayerType(int, android.graphics.Paint) 13087 */ 13088 public void buildLayer() { 13089 if (mLayerType == LAYER_TYPE_NONE) return; 13090 13091 final AttachInfo attachInfo = mAttachInfo; 13092 if (attachInfo == null) { 13093 throw new IllegalStateException("This view must be attached to a window first"); 13094 } 13095 13096 switch (mLayerType) { 13097 case LAYER_TYPE_HARDWARE: 13098 if (attachInfo.mHardwareRenderer != null && 13099 attachInfo.mHardwareRenderer.isEnabled() && 13100 attachInfo.mHardwareRenderer.validate()) { 13101 getHardwareLayer(); 13102 // TODO: We need a better way to handle this case 13103 // If views have registered pre-draw listeners they need 13104 // to be notified before we build the layer. Those listeners 13105 // may however rely on other events to happen first so we 13106 // cannot just invoke them here until they don't cancel the 13107 // current frame 13108 if (!attachInfo.mTreeObserver.hasOnPreDrawListeners()) { 13109 attachInfo.mViewRootImpl.dispatchFlushHardwareLayerUpdates(); 13110 } 13111 } 13112 break; 13113 case LAYER_TYPE_SOFTWARE: 13114 buildDrawingCache(true); 13115 break; 13116 } 13117 } 13118 13119 /** 13120 * <p>Returns a hardware layer that can be used to draw this view again 13121 * without executing its draw method.</p> 13122 * 13123 * @return A HardwareLayer ready to render, or null if an error occurred. 13124 */ 13125 HardwareLayer getHardwareLayer() { 13126 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null || 13127 !mAttachInfo.mHardwareRenderer.isEnabled()) { 13128 return null; 13129 } 13130 13131 if (!mAttachInfo.mHardwareRenderer.validate()) return null; 13132 13133 final int width = mRight - mLeft; 13134 final int height = mBottom - mTop; 13135 13136 if (width == 0 || height == 0) { 13137 return null; 13138 } 13139 13140 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) { 13141 if (mHardwareLayer == null) { 13142 mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer( 13143 width, height, isOpaque()); 13144 mLocalDirtyRect.set(0, 0, width, height); 13145 } else { 13146 if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) { 13147 if (mHardwareLayer.resize(width, height)) { 13148 mLocalDirtyRect.set(0, 0, width, height); 13149 } 13150 } 13151 13152 // This should not be necessary but applications that change 13153 // the parameters of their background drawable without calling 13154 // this.setBackground(Drawable) can leave the view in a bad state 13155 // (for instance isOpaque() returns true, but the background is 13156 // not opaque.) 13157 computeOpaqueFlags(); 13158 13159 final boolean opaque = isOpaque(); 13160 if (mHardwareLayer.isValid() && mHardwareLayer.isOpaque() != opaque) { 13161 mHardwareLayer.setOpaque(opaque); 13162 mLocalDirtyRect.set(0, 0, width, height); 13163 } 13164 } 13165 13166 // The layer is not valid if the underlying GPU resources cannot be allocated 13167 if (!mHardwareLayer.isValid()) { 13168 return null; 13169 } 13170 13171 mHardwareLayer.setLayerPaint(mLayerPaint); 13172 mHardwareLayer.redrawLater(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect); 13173 ViewRootImpl viewRoot = getViewRootImpl(); 13174 if (viewRoot != null) viewRoot.pushHardwareLayerUpdate(mHardwareLayer); 13175 13176 mLocalDirtyRect.setEmpty(); 13177 } 13178 13179 return mHardwareLayer; 13180 } 13181 13182 /** 13183 * Destroys this View's hardware layer if possible. 13184 * 13185 * @return True if the layer was destroyed, false otherwise. 13186 * 13187 * @see #setLayerType(int, android.graphics.Paint) 13188 * @see #LAYER_TYPE_HARDWARE 13189 */ 13190 boolean destroyLayer(boolean valid) { 13191 if (mHardwareLayer != null) { 13192 AttachInfo info = mAttachInfo; 13193 if (info != null && info.mHardwareRenderer != null && 13194 info.mHardwareRenderer.isEnabled() && 13195 (valid || info.mHardwareRenderer.validate())) { 13196 13197 info.mHardwareRenderer.cancelLayerUpdate(mHardwareLayer); 13198 mHardwareLayer.destroy(); 13199 mHardwareLayer = null; 13200 13201 invalidate(true); 13202 invalidateParentCaches(); 13203 } 13204 return true; 13205 } 13206 return false; 13207 } 13208 13209 /** 13210 * Destroys all hardware rendering resources. This method is invoked 13211 * when the system needs to reclaim resources. Upon execution of this 13212 * method, you should free any OpenGL resources created by the view. 13213 * 13214 * Note: you <strong>must</strong> call 13215 * <code>super.destroyHardwareResources()</code> when overriding 13216 * this method. 13217 * 13218 * @hide 13219 */ 13220 protected void destroyHardwareResources() { 13221 resetDisplayList(); 13222 destroyLayer(true); 13223 } 13224 13225 /** 13226 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 13227 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 13228 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 13229 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 13230 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 13231 * null.</p> 13232 * 13233 * <p>Enabling the drawing cache is similar to 13234 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 13235 * acceleration is turned off. When hardware acceleration is turned on, enabling the 13236 * drawing cache has no effect on rendering because the system uses a different mechanism 13237 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 13238 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 13239 * for information on how to enable software and hardware layers.</p> 13240 * 13241 * <p>This API can be used to manually generate 13242 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 13243 * {@link #getDrawingCache()}.</p> 13244 * 13245 * @param enabled true to enable the drawing cache, false otherwise 13246 * 13247 * @see #isDrawingCacheEnabled() 13248 * @see #getDrawingCache() 13249 * @see #buildDrawingCache() 13250 * @see #setLayerType(int, android.graphics.Paint) 13251 */ 13252 public void setDrawingCacheEnabled(boolean enabled) { 13253 mCachingFailed = false; 13254 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 13255 } 13256 13257 /** 13258 * <p>Indicates whether the drawing cache is enabled for this view.</p> 13259 * 13260 * @return true if the drawing cache is enabled 13261 * 13262 * @see #setDrawingCacheEnabled(boolean) 13263 * @see #getDrawingCache() 13264 */ 13265 @ViewDebug.ExportedProperty(category = "drawing") 13266 public boolean isDrawingCacheEnabled() { 13267 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 13268 } 13269 13270 /** 13271 * Debugging utility which recursively outputs the dirty state of a view and its 13272 * descendants. 13273 * 13274 * @hide 13275 */ 13276 @SuppressWarnings({"UnusedDeclaration"}) 13277 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 13278 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 13279 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 13280 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 13281 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 13282 if (clear) { 13283 mPrivateFlags &= clearMask; 13284 } 13285 if (this instanceof ViewGroup) { 13286 ViewGroup parent = (ViewGroup) this; 13287 final int count = parent.getChildCount(); 13288 for (int i = 0; i < count; i++) { 13289 final View child = parent.getChildAt(i); 13290 child.outputDirtyFlags(indent + " ", clear, clearMask); 13291 } 13292 } 13293 } 13294 13295 /** 13296 * This method is used by ViewGroup to cause its children to restore or recreate their 13297 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 13298 * to recreate its own display list, which would happen if it went through the normal 13299 * draw/dispatchDraw mechanisms. 13300 * 13301 * @hide 13302 */ 13303 protected void dispatchGetDisplayList() {} 13304 13305 /** 13306 * A view that is not attached or hardware accelerated cannot create a display list. 13307 * This method checks these conditions and returns the appropriate result. 13308 * 13309 * @return true if view has the ability to create a display list, false otherwise. 13310 * 13311 * @hide 13312 */ 13313 public boolean canHaveDisplayList() { 13314 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 13315 } 13316 13317 /** 13318 * @return The {@link HardwareRenderer} associated with that view or null if 13319 * hardware rendering is not supported or this view is not attached 13320 * to a window. 13321 * 13322 * @hide 13323 */ 13324 public HardwareRenderer getHardwareRenderer() { 13325 if (mAttachInfo != null) { 13326 return mAttachInfo.mHardwareRenderer; 13327 } 13328 return null; 13329 } 13330 13331 /** 13332 * Returns a DisplayList. If the incoming displayList is null, one will be created. 13333 * Otherwise, the same display list will be returned (after having been rendered into 13334 * along the way, depending on the invalidation state of the view). 13335 * 13336 * @param displayList The previous version of this displayList, could be null. 13337 * @param isLayer Whether the requester of the display list is a layer. If so, 13338 * the view will avoid creating a layer inside the resulting display list. 13339 * @return A new or reused DisplayList object. 13340 */ 13341 private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) { 13342 if (!canHaveDisplayList()) { 13343 return null; 13344 } 13345 13346 if (((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || 13347 displayList == null || !displayList.isValid() || 13348 (!isLayer && mRecreateDisplayList))) { 13349 // Don't need to recreate the display list, just need to tell our 13350 // children to restore/recreate theirs 13351 if (displayList != null && displayList.isValid() && 13352 !isLayer && !mRecreateDisplayList) { 13353 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13354 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13355 dispatchGetDisplayList(); 13356 13357 return displayList; 13358 } 13359 13360 if (!isLayer) { 13361 // If we got here, we're recreating it. Mark it as such to ensure that 13362 // we copy in child display lists into ours in drawChild() 13363 mRecreateDisplayList = true; 13364 } 13365 if (displayList == null) { 13366 displayList = mAttachInfo.mHardwareRenderer.createDisplayList(getClass().getName()); 13367 // If we're creating a new display list, make sure our parent gets invalidated 13368 // since they will need to recreate their display list to account for this 13369 // new child display list. 13370 invalidateParentCaches(); 13371 } 13372 13373 boolean caching = false; 13374 int width = mRight - mLeft; 13375 int height = mBottom - mTop; 13376 int layerType = getLayerType(); 13377 13378 final HardwareCanvas canvas = displayList.start(width, height); 13379 13380 try { 13381 if (!isLayer && layerType != LAYER_TYPE_NONE) { 13382 if (layerType == LAYER_TYPE_HARDWARE) { 13383 final HardwareLayer layer = getHardwareLayer(); 13384 if (layer != null && layer.isValid()) { 13385 canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint); 13386 } else { 13387 canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint, 13388 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | 13389 Canvas.CLIP_TO_LAYER_SAVE_FLAG); 13390 } 13391 caching = true; 13392 } else { 13393 buildDrawingCache(true); 13394 Bitmap cache = getDrawingCache(true); 13395 if (cache != null) { 13396 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 13397 caching = true; 13398 } 13399 } 13400 } else { 13401 13402 computeScroll(); 13403 13404 canvas.translate(-mScrollX, -mScrollY); 13405 if (!isLayer) { 13406 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13407 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13408 } 13409 13410 // Fast path for layouts with no backgrounds 13411 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 13412 dispatchDraw(canvas); 13413 if (mOverlay != null && !mOverlay.isEmpty()) { 13414 mOverlay.getOverlayView().draw(canvas); 13415 } 13416 } else { 13417 draw(canvas); 13418 } 13419 } 13420 } finally { 13421 displayList.end(); 13422 displayList.setCaching(caching); 13423 if (isLayer) { 13424 displayList.setLeftTopRightBottom(0, 0, width, height); 13425 } else { 13426 setDisplayListProperties(displayList); 13427 } 13428 } 13429 } else if (!isLayer) { 13430 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13431 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13432 } 13433 13434 return displayList; 13435 } 13436 13437 /** 13438 * Get the DisplayList for the HardwareLayer 13439 * 13440 * @param layer The HardwareLayer whose DisplayList we want 13441 * @return A DisplayList fopr the specified HardwareLayer 13442 */ 13443 private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) { 13444 DisplayList displayList = getDisplayList(layer.getDisplayList(), true); 13445 layer.setDisplayList(displayList); 13446 return displayList; 13447 } 13448 13449 13450 /** 13451 * <p>Returns a display list that can be used to draw this view again 13452 * without executing its draw method.</p> 13453 * 13454 * @return A DisplayList ready to replay, or null if caching is not enabled. 13455 * 13456 * @hide 13457 */ 13458 public DisplayList getDisplayList() { 13459 mDisplayList = getDisplayList(mDisplayList, false); 13460 return mDisplayList; 13461 } 13462 13463 private void clearDisplayList() { 13464 if (mDisplayList != null) { 13465 mDisplayList.clear(); 13466 } 13467 } 13468 13469 private void resetDisplayList() { 13470 if (mDisplayList != null) { 13471 mDisplayList.reset(); 13472 } 13473 } 13474 13475 /** 13476 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 13477 * 13478 * @return A non-scaled bitmap representing this view or null if cache is disabled. 13479 * 13480 * @see #getDrawingCache(boolean) 13481 */ 13482 public Bitmap getDrawingCache() { 13483 return getDrawingCache(false); 13484 } 13485 13486 /** 13487 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 13488 * is null when caching is disabled. If caching is enabled and the cache is not ready, 13489 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 13490 * draw from the cache when the cache is enabled. To benefit from the cache, you must 13491 * request the drawing cache by calling this method and draw it on screen if the 13492 * returned bitmap is not null.</p> 13493 * 13494 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 13495 * this method will create a bitmap of the same size as this view. Because this bitmap 13496 * will be drawn scaled by the parent ViewGroup, the result on screen might show 13497 * scaling artifacts. To avoid such artifacts, you should call this method by setting 13498 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 13499 * size than the view. This implies that your application must be able to handle this 13500 * size.</p> 13501 * 13502 * @param autoScale Indicates whether the generated bitmap should be scaled based on 13503 * the current density of the screen when the application is in compatibility 13504 * mode. 13505 * 13506 * @return A bitmap representing this view or null if cache is disabled. 13507 * 13508 * @see #setDrawingCacheEnabled(boolean) 13509 * @see #isDrawingCacheEnabled() 13510 * @see #buildDrawingCache(boolean) 13511 * @see #destroyDrawingCache() 13512 */ 13513 public Bitmap getDrawingCache(boolean autoScale) { 13514 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 13515 return null; 13516 } 13517 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 13518 buildDrawingCache(autoScale); 13519 } 13520 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 13521 } 13522 13523 /** 13524 * <p>Frees the resources used by the drawing cache. If you call 13525 * {@link #buildDrawingCache()} manually without calling 13526 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 13527 * should cleanup the cache with this method afterwards.</p> 13528 * 13529 * @see #setDrawingCacheEnabled(boolean) 13530 * @see #buildDrawingCache() 13531 * @see #getDrawingCache() 13532 */ 13533 public void destroyDrawingCache() { 13534 if (mDrawingCache != null) { 13535 mDrawingCache.recycle(); 13536 mDrawingCache = null; 13537 } 13538 if (mUnscaledDrawingCache != null) { 13539 mUnscaledDrawingCache.recycle(); 13540 mUnscaledDrawingCache = null; 13541 } 13542 } 13543 13544 /** 13545 * Setting a solid background color for the drawing cache's bitmaps will improve 13546 * performance and memory usage. Note, though that this should only be used if this 13547 * view will always be drawn on top of a solid color. 13548 * 13549 * @param color The background color to use for the drawing cache's bitmap 13550 * 13551 * @see #setDrawingCacheEnabled(boolean) 13552 * @see #buildDrawingCache() 13553 * @see #getDrawingCache() 13554 */ 13555 public void setDrawingCacheBackgroundColor(int color) { 13556 if (color != mDrawingCacheBackgroundColor) { 13557 mDrawingCacheBackgroundColor = color; 13558 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 13559 } 13560 } 13561 13562 /** 13563 * @see #setDrawingCacheBackgroundColor(int) 13564 * 13565 * @return The background color to used for the drawing cache's bitmap 13566 */ 13567 public int getDrawingCacheBackgroundColor() { 13568 return mDrawingCacheBackgroundColor; 13569 } 13570 13571 /** 13572 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 13573 * 13574 * @see #buildDrawingCache(boolean) 13575 */ 13576 public void buildDrawingCache() { 13577 buildDrawingCache(false); 13578 } 13579 13580 /** 13581 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 13582 * 13583 * <p>If you call {@link #buildDrawingCache()} manually without calling 13584 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 13585 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 13586 * 13587 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 13588 * this method will create a bitmap of the same size as this view. Because this bitmap 13589 * will be drawn scaled by the parent ViewGroup, the result on screen might show 13590 * scaling artifacts. To avoid such artifacts, you should call this method by setting 13591 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 13592 * size than the view. This implies that your application must be able to handle this 13593 * size.</p> 13594 * 13595 * <p>You should avoid calling this method when hardware acceleration is enabled. If 13596 * you do not need the drawing cache bitmap, calling this method will increase memory 13597 * usage and cause the view to be rendered in software once, thus negatively impacting 13598 * performance.</p> 13599 * 13600 * @see #getDrawingCache() 13601 * @see #destroyDrawingCache() 13602 */ 13603 public void buildDrawingCache(boolean autoScale) { 13604 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 13605 mDrawingCache == null : mUnscaledDrawingCache == null)) { 13606 mCachingFailed = false; 13607 13608 int width = mRight - mLeft; 13609 int height = mBottom - mTop; 13610 13611 final AttachInfo attachInfo = mAttachInfo; 13612 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 13613 13614 if (autoScale && scalingRequired) { 13615 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 13616 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 13617 } 13618 13619 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 13620 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 13621 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 13622 13623 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 13624 final long drawingCacheSize = 13625 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 13626 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 13627 if (width > 0 && height > 0) { 13628 Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs " 13629 + projectedBitmapSize + " bytes, only " 13630 + drawingCacheSize + " available"); 13631 } 13632 destroyDrawingCache(); 13633 mCachingFailed = true; 13634 return; 13635 } 13636 13637 boolean clear = true; 13638 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 13639 13640 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 13641 Bitmap.Config quality; 13642 if (!opaque) { 13643 // Never pick ARGB_4444 because it looks awful 13644 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 13645 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 13646 case DRAWING_CACHE_QUALITY_AUTO: 13647 case DRAWING_CACHE_QUALITY_LOW: 13648 case DRAWING_CACHE_QUALITY_HIGH: 13649 default: 13650 quality = Bitmap.Config.ARGB_8888; 13651 break; 13652 } 13653 } else { 13654 // Optimization for translucent windows 13655 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 13656 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 13657 } 13658 13659 // Try to cleanup memory 13660 if (bitmap != null) bitmap.recycle(); 13661 13662 try { 13663 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 13664 width, height, quality); 13665 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 13666 if (autoScale) { 13667 mDrawingCache = bitmap; 13668 } else { 13669 mUnscaledDrawingCache = bitmap; 13670 } 13671 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 13672 } catch (OutOfMemoryError e) { 13673 // If there is not enough memory to create the bitmap cache, just 13674 // ignore the issue as bitmap caches are not required to draw the 13675 // view hierarchy 13676 if (autoScale) { 13677 mDrawingCache = null; 13678 } else { 13679 mUnscaledDrawingCache = null; 13680 } 13681 mCachingFailed = true; 13682 return; 13683 } 13684 13685 clear = drawingCacheBackgroundColor != 0; 13686 } 13687 13688 Canvas canvas; 13689 if (attachInfo != null) { 13690 canvas = attachInfo.mCanvas; 13691 if (canvas == null) { 13692 canvas = new Canvas(); 13693 } 13694 canvas.setBitmap(bitmap); 13695 // Temporarily clobber the cached Canvas in case one of our children 13696 // is also using a drawing cache. Without this, the children would 13697 // steal the canvas by attaching their own bitmap to it and bad, bad 13698 // thing would happen (invisible views, corrupted drawings, etc.) 13699 attachInfo.mCanvas = null; 13700 } else { 13701 // This case should hopefully never or seldom happen 13702 canvas = new Canvas(bitmap); 13703 } 13704 13705 if (clear) { 13706 bitmap.eraseColor(drawingCacheBackgroundColor); 13707 } 13708 13709 computeScroll(); 13710 final int restoreCount = canvas.save(); 13711 13712 if (autoScale && scalingRequired) { 13713 final float scale = attachInfo.mApplicationScale; 13714 canvas.scale(scale, scale); 13715 } 13716 13717 canvas.translate(-mScrollX, -mScrollY); 13718 13719 mPrivateFlags |= PFLAG_DRAWN; 13720 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 13721 mLayerType != LAYER_TYPE_NONE) { 13722 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 13723 } 13724 13725 // Fast path for layouts with no backgrounds 13726 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 13727 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13728 dispatchDraw(canvas); 13729 if (mOverlay != null && !mOverlay.isEmpty()) { 13730 mOverlay.getOverlayView().draw(canvas); 13731 } 13732 } else { 13733 draw(canvas); 13734 } 13735 13736 canvas.restoreToCount(restoreCount); 13737 canvas.setBitmap(null); 13738 13739 if (attachInfo != null) { 13740 // Restore the cached Canvas for our siblings 13741 attachInfo.mCanvas = canvas; 13742 } 13743 } 13744 } 13745 13746 /** 13747 * Create a snapshot of the view into a bitmap. We should probably make 13748 * some form of this public, but should think about the API. 13749 */ 13750 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 13751 int width = mRight - mLeft; 13752 int height = mBottom - mTop; 13753 13754 final AttachInfo attachInfo = mAttachInfo; 13755 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 13756 width = (int) ((width * scale) + 0.5f); 13757 height = (int) ((height * scale) + 0.5f); 13758 13759 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 13760 width > 0 ? width : 1, height > 0 ? height : 1, quality); 13761 if (bitmap == null) { 13762 throw new OutOfMemoryError(); 13763 } 13764 13765 Resources resources = getResources(); 13766 if (resources != null) { 13767 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 13768 } 13769 13770 Canvas canvas; 13771 if (attachInfo != null) { 13772 canvas = attachInfo.mCanvas; 13773 if (canvas == null) { 13774 canvas = new Canvas(); 13775 } 13776 canvas.setBitmap(bitmap); 13777 // Temporarily clobber the cached Canvas in case one of our children 13778 // is also using a drawing cache. Without this, the children would 13779 // steal the canvas by attaching their own bitmap to it and bad, bad 13780 // things would happen (invisible views, corrupted drawings, etc.) 13781 attachInfo.mCanvas = null; 13782 } else { 13783 // This case should hopefully never or seldom happen 13784 canvas = new Canvas(bitmap); 13785 } 13786 13787 if ((backgroundColor & 0xff000000) != 0) { 13788 bitmap.eraseColor(backgroundColor); 13789 } 13790 13791 computeScroll(); 13792 final int restoreCount = canvas.save(); 13793 canvas.scale(scale, scale); 13794 canvas.translate(-mScrollX, -mScrollY); 13795 13796 // Temporarily remove the dirty mask 13797 int flags = mPrivateFlags; 13798 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13799 13800 // Fast path for layouts with no backgrounds 13801 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 13802 dispatchDraw(canvas); 13803 if (mOverlay != null && !mOverlay.isEmpty()) { 13804 mOverlay.getOverlayView().draw(canvas); 13805 } 13806 } else { 13807 draw(canvas); 13808 } 13809 13810 mPrivateFlags = flags; 13811 13812 canvas.restoreToCount(restoreCount); 13813 canvas.setBitmap(null); 13814 13815 if (attachInfo != null) { 13816 // Restore the cached Canvas for our siblings 13817 attachInfo.mCanvas = canvas; 13818 } 13819 13820 return bitmap; 13821 } 13822 13823 /** 13824 * Indicates whether this View is currently in edit mode. A View is usually 13825 * in edit mode when displayed within a developer tool. For instance, if 13826 * this View is being drawn by a visual user interface builder, this method 13827 * should return true. 13828 * 13829 * Subclasses should check the return value of this method to provide 13830 * different behaviors if their normal behavior might interfere with the 13831 * host environment. For instance: the class spawns a thread in its 13832 * constructor, the drawing code relies on device-specific features, etc. 13833 * 13834 * This method is usually checked in the drawing code of custom widgets. 13835 * 13836 * @return True if this View is in edit mode, false otherwise. 13837 */ 13838 public boolean isInEditMode() { 13839 return false; 13840 } 13841 13842 /** 13843 * If the View draws content inside its padding and enables fading edges, 13844 * it needs to support padding offsets. Padding offsets are added to the 13845 * fading edges to extend the length of the fade so that it covers pixels 13846 * drawn inside the padding. 13847 * 13848 * Subclasses of this class should override this method if they need 13849 * to draw content inside the padding. 13850 * 13851 * @return True if padding offset must be applied, false otherwise. 13852 * 13853 * @see #getLeftPaddingOffset() 13854 * @see #getRightPaddingOffset() 13855 * @see #getTopPaddingOffset() 13856 * @see #getBottomPaddingOffset() 13857 * 13858 * @since CURRENT 13859 */ 13860 protected boolean isPaddingOffsetRequired() { 13861 return false; 13862 } 13863 13864 /** 13865 * Amount by which to extend the left fading region. Called only when 13866 * {@link #isPaddingOffsetRequired()} returns true. 13867 * 13868 * @return The left padding offset in pixels. 13869 * 13870 * @see #isPaddingOffsetRequired() 13871 * 13872 * @since CURRENT 13873 */ 13874 protected int getLeftPaddingOffset() { 13875 return 0; 13876 } 13877 13878 /** 13879 * Amount by which to extend the right fading region. Called only when 13880 * {@link #isPaddingOffsetRequired()} returns true. 13881 * 13882 * @return The right padding offset in pixels. 13883 * 13884 * @see #isPaddingOffsetRequired() 13885 * 13886 * @since CURRENT 13887 */ 13888 protected int getRightPaddingOffset() { 13889 return 0; 13890 } 13891 13892 /** 13893 * Amount by which to extend the top fading region. Called only when 13894 * {@link #isPaddingOffsetRequired()} returns true. 13895 * 13896 * @return The top padding offset in pixels. 13897 * 13898 * @see #isPaddingOffsetRequired() 13899 * 13900 * @since CURRENT 13901 */ 13902 protected int getTopPaddingOffset() { 13903 return 0; 13904 } 13905 13906 /** 13907 * Amount by which to extend the bottom fading region. Called only when 13908 * {@link #isPaddingOffsetRequired()} returns true. 13909 * 13910 * @return The bottom padding offset in pixels. 13911 * 13912 * @see #isPaddingOffsetRequired() 13913 * 13914 * @since CURRENT 13915 */ 13916 protected int getBottomPaddingOffset() { 13917 return 0; 13918 } 13919 13920 /** 13921 * @hide 13922 * @param offsetRequired 13923 */ 13924 protected int getFadeTop(boolean offsetRequired) { 13925 int top = mPaddingTop; 13926 if (offsetRequired) top += getTopPaddingOffset(); 13927 return top; 13928 } 13929 13930 /** 13931 * @hide 13932 * @param offsetRequired 13933 */ 13934 protected int getFadeHeight(boolean offsetRequired) { 13935 int padding = mPaddingTop; 13936 if (offsetRequired) padding += getTopPaddingOffset(); 13937 return mBottom - mTop - mPaddingBottom - padding; 13938 } 13939 13940 /** 13941 * <p>Indicates whether this view is attached to a hardware accelerated 13942 * window or not.</p> 13943 * 13944 * <p>Even if this method returns true, it does not mean that every call 13945 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 13946 * accelerated {@link android.graphics.Canvas}. For instance, if this view 13947 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 13948 * window is hardware accelerated, 13949 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 13950 * return false, and this method will return true.</p> 13951 * 13952 * @return True if the view is attached to a window and the window is 13953 * hardware accelerated; false in any other case. 13954 */ 13955 public boolean isHardwareAccelerated() { 13956 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 13957 } 13958 13959 /** 13960 * Sets a rectangular area on this view to which the view will be clipped 13961 * when it is drawn. Setting the value to null will remove the clip bounds 13962 * and the view will draw normally, using its full bounds. 13963 * 13964 * @param clipBounds The rectangular area, in the local coordinates of 13965 * this view, to which future drawing operations will be clipped. 13966 */ 13967 public void setClipBounds(Rect clipBounds) { 13968 if (clipBounds != null) { 13969 if (clipBounds.equals(mClipBounds)) { 13970 return; 13971 } 13972 if (mClipBounds == null) { 13973 invalidate(); 13974 mClipBounds = new Rect(clipBounds); 13975 } else { 13976 invalidate(Math.min(mClipBounds.left, clipBounds.left), 13977 Math.min(mClipBounds.top, clipBounds.top), 13978 Math.max(mClipBounds.right, clipBounds.right), 13979 Math.max(mClipBounds.bottom, clipBounds.bottom)); 13980 mClipBounds.set(clipBounds); 13981 } 13982 } else { 13983 if (mClipBounds != null) { 13984 invalidate(); 13985 mClipBounds = null; 13986 } 13987 } 13988 } 13989 13990 /** 13991 * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}. 13992 * 13993 * @return A copy of the current clip bounds if clip bounds are set, 13994 * otherwise null. 13995 */ 13996 public Rect getClipBounds() { 13997 return (mClipBounds != null) ? new Rect(mClipBounds) : null; 13998 } 13999 14000 /** 14001 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 14002 * case of an active Animation being run on the view. 14003 */ 14004 private boolean drawAnimation(ViewGroup parent, long drawingTime, 14005 Animation a, boolean scalingRequired) { 14006 Transformation invalidationTransform; 14007 final int flags = parent.mGroupFlags; 14008 final boolean initialized = a.isInitialized(); 14009 if (!initialized) { 14010 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 14011 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 14012 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 14013 onAnimationStart(); 14014 } 14015 14016 final Transformation t = parent.getChildTransformation(); 14017 boolean more = a.getTransformation(drawingTime, t, 1f); 14018 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 14019 if (parent.mInvalidationTransformation == null) { 14020 parent.mInvalidationTransformation = new Transformation(); 14021 } 14022 invalidationTransform = parent.mInvalidationTransformation; 14023 a.getTransformation(drawingTime, invalidationTransform, 1f); 14024 } else { 14025 invalidationTransform = t; 14026 } 14027 14028 if (more) { 14029 if (!a.willChangeBounds()) { 14030 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 14031 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 14032 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 14033 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 14034 // The child need to draw an animation, potentially offscreen, so 14035 // make sure we do not cancel invalidate requests 14036 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14037 parent.invalidate(mLeft, mTop, mRight, mBottom); 14038 } 14039 } else { 14040 if (parent.mInvalidateRegion == null) { 14041 parent.mInvalidateRegion = new RectF(); 14042 } 14043 final RectF region = parent.mInvalidateRegion; 14044 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 14045 invalidationTransform); 14046 14047 // The child need to draw an animation, potentially offscreen, so 14048 // make sure we do not cancel invalidate requests 14049 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14050 14051 final int left = mLeft + (int) region.left; 14052 final int top = mTop + (int) region.top; 14053 parent.invalidate(left, top, left + (int) (region.width() + .5f), 14054 top + (int) (region.height() + .5f)); 14055 } 14056 } 14057 return more; 14058 } 14059 14060 /** 14061 * This method is called by getDisplayList() when a display list is created or re-rendered. 14062 * It sets or resets the current value of all properties on that display list (resetting is 14063 * necessary when a display list is being re-created, because we need to make sure that 14064 * previously-set transform values 14065 */ 14066 void setDisplayListProperties(DisplayList displayList) { 14067 if (displayList != null) { 14068 displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 14069 displayList.setHasOverlappingRendering(hasOverlappingRendering()); 14070 if (mParent instanceof ViewGroup) { 14071 displayList.setClipToBounds( 14072 (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0); 14073 } 14074 float alpha = 1; 14075 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 14076 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14077 ViewGroup parentVG = (ViewGroup) mParent; 14078 final Transformation t = parentVG.getChildTransformation(); 14079 if (parentVG.getChildStaticTransformation(this, t)) { 14080 final int transformType = t.getTransformationType(); 14081 if (transformType != Transformation.TYPE_IDENTITY) { 14082 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 14083 alpha = t.getAlpha(); 14084 } 14085 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 14086 displayList.setMatrix(t.getMatrix()); 14087 } 14088 } 14089 } 14090 } 14091 if (mTransformationInfo != null) { 14092 alpha *= getFinalAlpha(); 14093 if (alpha < 1) { 14094 final int multipliedAlpha = (int) (255 * alpha); 14095 if (onSetAlpha(multipliedAlpha)) { 14096 alpha = 1; 14097 } 14098 } 14099 displayList.setTransformationInfo(alpha, 14100 mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY, 14101 mTransformationInfo.mRotation, mTransformationInfo.mRotationX, 14102 mTransformationInfo.mRotationY, mTransformationInfo.mScaleX, 14103 mTransformationInfo.mScaleY); 14104 if (mTransformationInfo.mCamera == null) { 14105 mTransformationInfo.mCamera = new Camera(); 14106 mTransformationInfo.matrix3D = new Matrix(); 14107 } 14108 displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ()); 14109 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == PFLAG_PIVOT_EXPLICITLY_SET) { 14110 displayList.setPivotX(getPivotX()); 14111 displayList.setPivotY(getPivotY()); 14112 } 14113 } else if (alpha < 1) { 14114 displayList.setAlpha(alpha); 14115 } 14116 } 14117 } 14118 14119 /** 14120 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 14121 * This draw() method is an implementation detail and is not intended to be overridden or 14122 * to be called from anywhere else other than ViewGroup.drawChild(). 14123 */ 14124 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 14125 boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14126 boolean more = false; 14127 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 14128 final int flags = parent.mGroupFlags; 14129 14130 if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) { 14131 parent.getChildTransformation().clear(); 14132 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14133 } 14134 14135 Transformation transformToApply = null; 14136 boolean concatMatrix = false; 14137 14138 boolean scalingRequired = false; 14139 boolean caching; 14140 int layerType = getLayerType(); 14141 14142 final boolean hardwareAccelerated = canvas.isHardwareAccelerated(); 14143 if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 || 14144 (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) { 14145 caching = true; 14146 // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList 14147 if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired; 14148 } else { 14149 caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated; 14150 } 14151 14152 final Animation a = getAnimation(); 14153 if (a != null) { 14154 more = drawAnimation(parent, drawingTime, a, scalingRequired); 14155 concatMatrix = a.willChangeTransformationMatrix(); 14156 if (concatMatrix) { 14157 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14158 } 14159 transformToApply = parent.getChildTransformation(); 14160 } else { 14161 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) == 14162 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM && mDisplayList != null) { 14163 // No longer animating: clear out old animation matrix 14164 mDisplayList.setAnimationMatrix(null); 14165 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14166 } 14167 if (!useDisplayListProperties && 14168 (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14169 final Transformation t = parent.getChildTransformation(); 14170 final boolean hasTransform = parent.getChildStaticTransformation(this, t); 14171 if (hasTransform) { 14172 final int transformType = t.getTransformationType(); 14173 transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null; 14174 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 14175 } 14176 } 14177 } 14178 14179 concatMatrix |= !childHasIdentityMatrix; 14180 14181 // Sets the flag as early as possible to allow draw() implementations 14182 // to call invalidate() successfully when doing animations 14183 mPrivateFlags |= PFLAG_DRAWN; 14184 14185 if (!concatMatrix && 14186 (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 14187 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 14188 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 14189 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 14190 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 14191 return more; 14192 } 14193 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 14194 14195 if (hardwareAccelerated) { 14196 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 14197 // retain the flag's value temporarily in the mRecreateDisplayList flag 14198 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED; 14199 mPrivateFlags &= ~PFLAG_INVALIDATED; 14200 } 14201 14202 DisplayList displayList = null; 14203 Bitmap cache = null; 14204 boolean hasDisplayList = false; 14205 if (caching) { 14206 if (!hardwareAccelerated) { 14207 if (layerType != LAYER_TYPE_NONE) { 14208 layerType = LAYER_TYPE_SOFTWARE; 14209 buildDrawingCache(true); 14210 } 14211 cache = getDrawingCache(true); 14212 } else { 14213 switch (layerType) { 14214 case LAYER_TYPE_SOFTWARE: 14215 if (useDisplayListProperties) { 14216 hasDisplayList = canHaveDisplayList(); 14217 } else { 14218 buildDrawingCache(true); 14219 cache = getDrawingCache(true); 14220 } 14221 break; 14222 case LAYER_TYPE_HARDWARE: 14223 if (useDisplayListProperties) { 14224 hasDisplayList = canHaveDisplayList(); 14225 } 14226 break; 14227 case LAYER_TYPE_NONE: 14228 // Delay getting the display list until animation-driven alpha values are 14229 // set up and possibly passed on to the view 14230 hasDisplayList = canHaveDisplayList(); 14231 break; 14232 } 14233 } 14234 } 14235 useDisplayListProperties &= hasDisplayList; 14236 if (useDisplayListProperties) { 14237 displayList = getDisplayList(); 14238 if (!displayList.isValid()) { 14239 // Uncommon, but possible. If a view is removed from the hierarchy during the call 14240 // to getDisplayList(), the display list will be marked invalid and we should not 14241 // try to use it again. 14242 displayList = null; 14243 hasDisplayList = false; 14244 useDisplayListProperties = false; 14245 } 14246 } 14247 14248 int sx = 0; 14249 int sy = 0; 14250 if (!hasDisplayList) { 14251 computeScroll(); 14252 sx = mScrollX; 14253 sy = mScrollY; 14254 } 14255 14256 final boolean hasNoCache = cache == null || hasDisplayList; 14257 final boolean offsetForScroll = cache == null && !hasDisplayList && 14258 layerType != LAYER_TYPE_HARDWARE; 14259 14260 int restoreTo = -1; 14261 if (!useDisplayListProperties || transformToApply != null) { 14262 restoreTo = canvas.save(); 14263 } 14264 if (offsetForScroll) { 14265 canvas.translate(mLeft - sx, mTop - sy); 14266 } else { 14267 if (!useDisplayListProperties) { 14268 canvas.translate(mLeft, mTop); 14269 } 14270 if (scalingRequired) { 14271 if (useDisplayListProperties) { 14272 // TODO: Might not need this if we put everything inside the DL 14273 restoreTo = canvas.save(); 14274 } 14275 // mAttachInfo cannot be null, otherwise scalingRequired == false 14276 final float scale = 1.0f / mAttachInfo.mApplicationScale; 14277 canvas.scale(scale, scale); 14278 } 14279 } 14280 14281 float alpha = useDisplayListProperties ? 1 : (getAlpha() * getTransitionAlpha()); 14282 if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() || 14283 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 14284 if (transformToApply != null || !childHasIdentityMatrix) { 14285 int transX = 0; 14286 int transY = 0; 14287 14288 if (offsetForScroll) { 14289 transX = -sx; 14290 transY = -sy; 14291 } 14292 14293 if (transformToApply != null) { 14294 if (concatMatrix) { 14295 if (useDisplayListProperties) { 14296 displayList.setAnimationMatrix(transformToApply.getMatrix()); 14297 } else { 14298 // Undo the scroll translation, apply the transformation matrix, 14299 // then redo the scroll translate to get the correct result. 14300 canvas.translate(-transX, -transY); 14301 canvas.concat(transformToApply.getMatrix()); 14302 canvas.translate(transX, transY); 14303 } 14304 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14305 } 14306 14307 float transformAlpha = transformToApply.getAlpha(); 14308 if (transformAlpha < 1) { 14309 alpha *= transformAlpha; 14310 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14311 } 14312 } 14313 14314 if (!childHasIdentityMatrix && !useDisplayListProperties) { 14315 canvas.translate(-transX, -transY); 14316 canvas.concat(getMatrix()); 14317 canvas.translate(transX, transY); 14318 } 14319 } 14320 14321 // Deal with alpha if it is or used to be <1 14322 if (alpha < 1 || 14323 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 14324 if (alpha < 1) { 14325 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 14326 } else { 14327 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 14328 } 14329 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14330 if (hasNoCache) { 14331 final int multipliedAlpha = (int) (255 * alpha); 14332 if (!onSetAlpha(multipliedAlpha)) { 14333 int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 14334 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 || 14335 layerType != LAYER_TYPE_NONE) { 14336 layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG; 14337 } 14338 if (useDisplayListProperties) { 14339 displayList.setAlpha(alpha * getAlpha() * getTransitionAlpha()); 14340 } else if (layerType == LAYER_TYPE_NONE) { 14341 final int scrollX = hasDisplayList ? 0 : sx; 14342 final int scrollY = hasDisplayList ? 0 : sy; 14343 canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft, 14344 scrollY + mBottom - mTop, multipliedAlpha, layerFlags); 14345 } 14346 } else { 14347 // Alpha is handled by the child directly, clobber the layer's alpha 14348 mPrivateFlags |= PFLAG_ALPHA_SET; 14349 } 14350 } 14351 } 14352 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 14353 onSetAlpha(255); 14354 mPrivateFlags &= ~PFLAG_ALPHA_SET; 14355 } 14356 14357 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN && 14358 !useDisplayListProperties && cache == null) { 14359 if (offsetForScroll) { 14360 canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop)); 14361 } else { 14362 if (!scalingRequired || cache == null) { 14363 canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop); 14364 } else { 14365 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 14366 } 14367 } 14368 } 14369 14370 if (!useDisplayListProperties && hasDisplayList) { 14371 displayList = getDisplayList(); 14372 if (!displayList.isValid()) { 14373 // Uncommon, but possible. If a view is removed from the hierarchy during the call 14374 // to getDisplayList(), the display list will be marked invalid and we should not 14375 // try to use it again. 14376 displayList = null; 14377 hasDisplayList = false; 14378 } 14379 } 14380 14381 if (hasNoCache) { 14382 boolean layerRendered = false; 14383 if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) { 14384 final HardwareLayer layer = getHardwareLayer(); 14385 if (layer != null && layer.isValid()) { 14386 mLayerPaint.setAlpha((int) (alpha * 255)); 14387 ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint); 14388 layerRendered = true; 14389 } else { 14390 final int scrollX = hasDisplayList ? 0 : sx; 14391 final int scrollY = hasDisplayList ? 0 : sy; 14392 canvas.saveLayer(scrollX, scrollY, 14393 scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint, 14394 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG); 14395 } 14396 } 14397 14398 if (!layerRendered) { 14399 if (!hasDisplayList) { 14400 // Fast path for layouts with no backgrounds 14401 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14402 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14403 dispatchDraw(canvas); 14404 } else { 14405 draw(canvas); 14406 } 14407 } else { 14408 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14409 ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags); 14410 } 14411 } 14412 } else if (cache != null) { 14413 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14414 Paint cachePaint; 14415 14416 if (layerType == LAYER_TYPE_NONE) { 14417 cachePaint = parent.mCachePaint; 14418 if (cachePaint == null) { 14419 cachePaint = new Paint(); 14420 cachePaint.setDither(false); 14421 parent.mCachePaint = cachePaint; 14422 } 14423 if (alpha < 1) { 14424 cachePaint.setAlpha((int) (alpha * 255)); 14425 parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 14426 } else if ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) { 14427 cachePaint.setAlpha(255); 14428 parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 14429 } 14430 } else { 14431 cachePaint = mLayerPaint; 14432 cachePaint.setAlpha((int) (alpha * 255)); 14433 } 14434 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 14435 } 14436 14437 if (restoreTo >= 0) { 14438 canvas.restoreToCount(restoreTo); 14439 } 14440 14441 if (a != null && !more) { 14442 if (!hardwareAccelerated && !a.getFillAfter()) { 14443 onSetAlpha(255); 14444 } 14445 parent.finishAnimatingView(this, a); 14446 } 14447 14448 if (more && hardwareAccelerated) { 14449 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 14450 // alpha animations should cause the child to recreate its display list 14451 invalidate(true); 14452 } 14453 } 14454 14455 mRecreateDisplayList = false; 14456 14457 return more; 14458 } 14459 14460 /** 14461 * Manually render this view (and all of its children) to the given Canvas. 14462 * The view must have already done a full layout before this function is 14463 * called. When implementing a view, implement 14464 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 14465 * If you do need to override this method, call the superclass version. 14466 * 14467 * @param canvas The Canvas to which the View is rendered. 14468 */ 14469 public void draw(Canvas canvas) { 14470 if (mClipBounds != null) { 14471 canvas.clipRect(mClipBounds); 14472 } 14473 final int privateFlags = mPrivateFlags; 14474 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 14475 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 14476 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 14477 14478 /* 14479 * Draw traversal performs several drawing steps which must be executed 14480 * in the appropriate order: 14481 * 14482 * 1. Draw the background 14483 * 2. If necessary, save the canvas' layers to prepare for fading 14484 * 3. Draw view's content 14485 * 4. Draw children 14486 * 5. If necessary, draw the fading edges and restore layers 14487 * 6. Draw decorations (scrollbars for instance) 14488 */ 14489 14490 // Step 1, draw the background, if needed 14491 int saveCount; 14492 14493 if (!dirtyOpaque) { 14494 final Drawable background = mBackground; 14495 if (background != null) { 14496 final int scrollX = mScrollX; 14497 final int scrollY = mScrollY; 14498 14499 if (mBackgroundSizeChanged) { 14500 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 14501 mBackgroundSizeChanged = false; 14502 } 14503 14504 if ((scrollX | scrollY) == 0) { 14505 background.draw(canvas); 14506 } else { 14507 canvas.translate(scrollX, scrollY); 14508 background.draw(canvas); 14509 canvas.translate(-scrollX, -scrollY); 14510 } 14511 } 14512 } 14513 14514 // skip step 2 & 5 if possible (common case) 14515 final int viewFlags = mViewFlags; 14516 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 14517 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 14518 if (!verticalEdges && !horizontalEdges) { 14519 // Step 3, draw the content 14520 if (!dirtyOpaque) onDraw(canvas); 14521 14522 // Step 4, draw the children 14523 dispatchDraw(canvas); 14524 14525 // Step 6, draw decorations (scrollbars) 14526 onDrawScrollBars(canvas); 14527 14528 if (mOverlay != null && !mOverlay.isEmpty()) { 14529 mOverlay.getOverlayView().dispatchDraw(canvas); 14530 } 14531 14532 // we're done... 14533 return; 14534 } 14535 14536 /* 14537 * Here we do the full fledged routine... 14538 * (this is an uncommon case where speed matters less, 14539 * this is why we repeat some of the tests that have been 14540 * done above) 14541 */ 14542 14543 boolean drawTop = false; 14544 boolean drawBottom = false; 14545 boolean drawLeft = false; 14546 boolean drawRight = false; 14547 14548 float topFadeStrength = 0.0f; 14549 float bottomFadeStrength = 0.0f; 14550 float leftFadeStrength = 0.0f; 14551 float rightFadeStrength = 0.0f; 14552 14553 // Step 2, save the canvas' layers 14554 int paddingLeft = mPaddingLeft; 14555 14556 final boolean offsetRequired = isPaddingOffsetRequired(); 14557 if (offsetRequired) { 14558 paddingLeft += getLeftPaddingOffset(); 14559 } 14560 14561 int left = mScrollX + paddingLeft; 14562 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 14563 int top = mScrollY + getFadeTop(offsetRequired); 14564 int bottom = top + getFadeHeight(offsetRequired); 14565 14566 if (offsetRequired) { 14567 right += getRightPaddingOffset(); 14568 bottom += getBottomPaddingOffset(); 14569 } 14570 14571 final ScrollabilityCache scrollabilityCache = mScrollCache; 14572 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 14573 int length = (int) fadeHeight; 14574 14575 // clip the fade length if top and bottom fades overlap 14576 // overlapping fades produce odd-looking artifacts 14577 if (verticalEdges && (top + length > bottom - length)) { 14578 length = (bottom - top) / 2; 14579 } 14580 14581 // also clip horizontal fades if necessary 14582 if (horizontalEdges && (left + length > right - length)) { 14583 length = (right - left) / 2; 14584 } 14585 14586 if (verticalEdges) { 14587 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 14588 drawTop = topFadeStrength * fadeHeight > 1.0f; 14589 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 14590 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 14591 } 14592 14593 if (horizontalEdges) { 14594 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 14595 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 14596 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 14597 drawRight = rightFadeStrength * fadeHeight > 1.0f; 14598 } 14599 14600 saveCount = canvas.getSaveCount(); 14601 14602 int solidColor = getSolidColor(); 14603 if (solidColor == 0) { 14604 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 14605 14606 if (drawTop) { 14607 canvas.saveLayer(left, top, right, top + length, null, flags); 14608 } 14609 14610 if (drawBottom) { 14611 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 14612 } 14613 14614 if (drawLeft) { 14615 canvas.saveLayer(left, top, left + length, bottom, null, flags); 14616 } 14617 14618 if (drawRight) { 14619 canvas.saveLayer(right - length, top, right, bottom, null, flags); 14620 } 14621 } else { 14622 scrollabilityCache.setFadeColor(solidColor); 14623 } 14624 14625 // Step 3, draw the content 14626 if (!dirtyOpaque) onDraw(canvas); 14627 14628 // Step 4, draw the children 14629 dispatchDraw(canvas); 14630 14631 // Step 5, draw the fade effect and restore layers 14632 final Paint p = scrollabilityCache.paint; 14633 final Matrix matrix = scrollabilityCache.matrix; 14634 final Shader fade = scrollabilityCache.shader; 14635 14636 if (drawTop) { 14637 matrix.setScale(1, fadeHeight * topFadeStrength); 14638 matrix.postTranslate(left, top); 14639 fade.setLocalMatrix(matrix); 14640 canvas.drawRect(left, top, right, top + length, p); 14641 } 14642 14643 if (drawBottom) { 14644 matrix.setScale(1, fadeHeight * bottomFadeStrength); 14645 matrix.postRotate(180); 14646 matrix.postTranslate(left, bottom); 14647 fade.setLocalMatrix(matrix); 14648 canvas.drawRect(left, bottom - length, right, bottom, p); 14649 } 14650 14651 if (drawLeft) { 14652 matrix.setScale(1, fadeHeight * leftFadeStrength); 14653 matrix.postRotate(-90); 14654 matrix.postTranslate(left, top); 14655 fade.setLocalMatrix(matrix); 14656 canvas.drawRect(left, top, left + length, bottom, p); 14657 } 14658 14659 if (drawRight) { 14660 matrix.setScale(1, fadeHeight * rightFadeStrength); 14661 matrix.postRotate(90); 14662 matrix.postTranslate(right, top); 14663 fade.setLocalMatrix(matrix); 14664 canvas.drawRect(right - length, top, right, bottom, p); 14665 } 14666 14667 canvas.restoreToCount(saveCount); 14668 14669 // Step 6, draw decorations (scrollbars) 14670 onDrawScrollBars(canvas); 14671 14672 if (mOverlay != null && !mOverlay.isEmpty()) { 14673 mOverlay.getOverlayView().dispatchDraw(canvas); 14674 } 14675 } 14676 14677 /** 14678 * Returns the overlay for this view, creating it if it does not yet exist. 14679 * Adding drawables to the overlay will cause them to be displayed whenever 14680 * the view itself is redrawn. Objects in the overlay should be actively 14681 * managed: remove them when they should not be displayed anymore. The 14682 * overlay will always have the same size as its host view. 14683 * 14684 * <p>Note: Overlays do not currently work correctly with {@link 14685 * SurfaceView} or {@link TextureView}; contents in overlays for these 14686 * types of views may not display correctly.</p> 14687 * 14688 * @return The ViewOverlay object for this view. 14689 * @see ViewOverlay 14690 */ 14691 public ViewOverlay getOverlay() { 14692 if (mOverlay == null) { 14693 mOverlay = new ViewOverlay(mContext, this); 14694 } 14695 return mOverlay; 14696 } 14697 14698 /** 14699 * Override this if your view is known to always be drawn on top of a solid color background, 14700 * and needs to draw fading edges. Returning a non-zero color enables the view system to 14701 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 14702 * should be set to 0xFF. 14703 * 14704 * @see #setVerticalFadingEdgeEnabled(boolean) 14705 * @see #setHorizontalFadingEdgeEnabled(boolean) 14706 * 14707 * @return The known solid color background for this view, or 0 if the color may vary 14708 */ 14709 @ViewDebug.ExportedProperty(category = "drawing") 14710 public int getSolidColor() { 14711 return 0; 14712 } 14713 14714 /** 14715 * Build a human readable string representation of the specified view flags. 14716 * 14717 * @param flags the view flags to convert to a string 14718 * @return a String representing the supplied flags 14719 */ 14720 private static String printFlags(int flags) { 14721 String output = ""; 14722 int numFlags = 0; 14723 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 14724 output += "TAKES_FOCUS"; 14725 numFlags++; 14726 } 14727 14728 switch (flags & VISIBILITY_MASK) { 14729 case INVISIBLE: 14730 if (numFlags > 0) { 14731 output += " "; 14732 } 14733 output += "INVISIBLE"; 14734 // USELESS HERE numFlags++; 14735 break; 14736 case GONE: 14737 if (numFlags > 0) { 14738 output += " "; 14739 } 14740 output += "GONE"; 14741 // USELESS HERE numFlags++; 14742 break; 14743 default: 14744 break; 14745 } 14746 return output; 14747 } 14748 14749 /** 14750 * Build a human readable string representation of the specified private 14751 * view flags. 14752 * 14753 * @param privateFlags the private view flags to convert to a string 14754 * @return a String representing the supplied flags 14755 */ 14756 private static String printPrivateFlags(int privateFlags) { 14757 String output = ""; 14758 int numFlags = 0; 14759 14760 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 14761 output += "WANTS_FOCUS"; 14762 numFlags++; 14763 } 14764 14765 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 14766 if (numFlags > 0) { 14767 output += " "; 14768 } 14769 output += "FOCUSED"; 14770 numFlags++; 14771 } 14772 14773 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 14774 if (numFlags > 0) { 14775 output += " "; 14776 } 14777 output += "SELECTED"; 14778 numFlags++; 14779 } 14780 14781 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 14782 if (numFlags > 0) { 14783 output += " "; 14784 } 14785 output += "IS_ROOT_NAMESPACE"; 14786 numFlags++; 14787 } 14788 14789 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 14790 if (numFlags > 0) { 14791 output += " "; 14792 } 14793 output += "HAS_BOUNDS"; 14794 numFlags++; 14795 } 14796 14797 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 14798 if (numFlags > 0) { 14799 output += " "; 14800 } 14801 output += "DRAWN"; 14802 // USELESS HERE numFlags++; 14803 } 14804 return output; 14805 } 14806 14807 /** 14808 * <p>Indicates whether or not this view's layout will be requested during 14809 * the next hierarchy layout pass.</p> 14810 * 14811 * @return true if the layout will be forced during next layout pass 14812 */ 14813 public boolean isLayoutRequested() { 14814 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 14815 } 14816 14817 /** 14818 * Return true if o is a ViewGroup that is laying out using optical bounds. 14819 * @hide 14820 */ 14821 public static boolean isLayoutModeOptical(Object o) { 14822 return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical(); 14823 } 14824 14825 private boolean setOpticalFrame(int left, int top, int right, int bottom) { 14826 Insets parentInsets = mParent instanceof View ? 14827 ((View) mParent).getOpticalInsets() : Insets.NONE; 14828 Insets childInsets = getOpticalInsets(); 14829 return setFrame( 14830 left + parentInsets.left - childInsets.left, 14831 top + parentInsets.top - childInsets.top, 14832 right + parentInsets.left + childInsets.right, 14833 bottom + parentInsets.top + childInsets.bottom); 14834 } 14835 14836 /** 14837 * Assign a size and position to a view and all of its 14838 * descendants 14839 * 14840 * <p>This is the second phase of the layout mechanism. 14841 * (The first is measuring). In this phase, each parent calls 14842 * layout on all of its children to position them. 14843 * This is typically done using the child measurements 14844 * that were stored in the measure pass().</p> 14845 * 14846 * <p>Derived classes should not override this method. 14847 * Derived classes with children should override 14848 * onLayout. In that method, they should 14849 * call layout on each of their children.</p> 14850 * 14851 * @param l Left position, relative to parent 14852 * @param t Top position, relative to parent 14853 * @param r Right position, relative to parent 14854 * @param b Bottom position, relative to parent 14855 */ 14856 @SuppressWarnings({"unchecked"}) 14857 public void layout(int l, int t, int r, int b) { 14858 if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) { 14859 onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec); 14860 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 14861 } 14862 14863 int oldL = mLeft; 14864 int oldT = mTop; 14865 int oldB = mBottom; 14866 int oldR = mRight; 14867 14868 boolean changed = isLayoutModeOptical(mParent) ? 14869 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); 14870 14871 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 14872 onLayout(changed, l, t, r, b); 14873 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 14874 14875 ListenerInfo li = mListenerInfo; 14876 if (li != null && li.mOnLayoutChangeListeners != null) { 14877 ArrayList<OnLayoutChangeListener> listenersCopy = 14878 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 14879 int numListeners = listenersCopy.size(); 14880 for (int i = 0; i < numListeners; ++i) { 14881 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 14882 } 14883 } 14884 } 14885 14886 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 14887 mPrivateFlags3 |= PFLAG3_IS_LAID_OUT; 14888 } 14889 14890 /** 14891 * Called from layout when this view should 14892 * assign a size and position to each of its children. 14893 * 14894 * Derived classes with children should override 14895 * this method and call layout on each of 14896 * their children. 14897 * @param changed This is a new size or position for this view 14898 * @param left Left position, relative to parent 14899 * @param top Top position, relative to parent 14900 * @param right Right position, relative to parent 14901 * @param bottom Bottom position, relative to parent 14902 */ 14903 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 14904 } 14905 14906 /** 14907 * Assign a size and position to this view. 14908 * 14909 * This is called from layout. 14910 * 14911 * @param left Left position, relative to parent 14912 * @param top Top position, relative to parent 14913 * @param right Right position, relative to parent 14914 * @param bottom Bottom position, relative to parent 14915 * @return true if the new size and position are different than the 14916 * previous ones 14917 * {@hide} 14918 */ 14919 protected boolean setFrame(int left, int top, int right, int bottom) { 14920 boolean changed = false; 14921 14922 if (DBG) { 14923 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 14924 + right + "," + bottom + ")"); 14925 } 14926 14927 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 14928 changed = true; 14929 14930 // Remember our drawn bit 14931 int drawn = mPrivateFlags & PFLAG_DRAWN; 14932 14933 int oldWidth = mRight - mLeft; 14934 int oldHeight = mBottom - mTop; 14935 int newWidth = right - left; 14936 int newHeight = bottom - top; 14937 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 14938 14939 // Invalidate our old position 14940 invalidate(sizeChanged); 14941 14942 mLeft = left; 14943 mTop = top; 14944 mRight = right; 14945 mBottom = bottom; 14946 if (mDisplayList != null) { 14947 mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 14948 } 14949 14950 mPrivateFlags |= PFLAG_HAS_BOUNDS; 14951 14952 14953 if (sizeChanged) { 14954 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 14955 // A change in dimension means an auto-centered pivot point changes, too 14956 if (mTransformationInfo != null) { 14957 mTransformationInfo.mMatrixDirty = true; 14958 } 14959 } 14960 sizeChange(newWidth, newHeight, oldWidth, oldHeight); 14961 } 14962 14963 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 14964 // If we are visible, force the DRAWN bit to on so that 14965 // this invalidate will go through (at least to our parent). 14966 // This is because someone may have invalidated this view 14967 // before this call to setFrame came in, thereby clearing 14968 // the DRAWN bit. 14969 mPrivateFlags |= PFLAG_DRAWN; 14970 invalidate(sizeChanged); 14971 // parent display list may need to be recreated based on a change in the bounds 14972 // of any child 14973 invalidateParentCaches(); 14974 } 14975 14976 // Reset drawn bit to original value (invalidate turns it off) 14977 mPrivateFlags |= drawn; 14978 14979 mBackgroundSizeChanged = true; 14980 14981 notifySubtreeAccessibilityStateChangedIfNeeded(); 14982 } 14983 return changed; 14984 } 14985 14986 private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) { 14987 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 14988 if (mOverlay != null) { 14989 mOverlay.getOverlayView().setRight(newWidth); 14990 mOverlay.getOverlayView().setBottom(newHeight); 14991 } 14992 } 14993 14994 /** 14995 * Finalize inflating a view from XML. This is called as the last phase 14996 * of inflation, after all child views have been added. 14997 * 14998 * <p>Even if the subclass overrides onFinishInflate, they should always be 14999 * sure to call the super method, so that we get called. 15000 */ 15001 protected void onFinishInflate() { 15002 } 15003 15004 /** 15005 * Returns the resources associated with this view. 15006 * 15007 * @return Resources object. 15008 */ 15009 public Resources getResources() { 15010 return mResources; 15011 } 15012 15013 /** 15014 * Invalidates the specified Drawable. 15015 * 15016 * @param drawable the drawable to invalidate 15017 */ 15018 public void invalidateDrawable(Drawable drawable) { 15019 if (verifyDrawable(drawable)) { 15020 final Rect dirty = drawable.getBounds(); 15021 final int scrollX = mScrollX; 15022 final int scrollY = mScrollY; 15023 15024 invalidate(dirty.left + scrollX, dirty.top + scrollY, 15025 dirty.right + scrollX, dirty.bottom + scrollY); 15026 } 15027 } 15028 15029 /** 15030 * Schedules an action on a drawable to occur at a specified time. 15031 * 15032 * @param who the recipient of the action 15033 * @param what the action to run on the drawable 15034 * @param when the time at which the action must occur. Uses the 15035 * {@link SystemClock#uptimeMillis} timebase. 15036 */ 15037 public void scheduleDrawable(Drawable who, Runnable what, long when) { 15038 if (verifyDrawable(who) && what != null) { 15039 final long delay = when - SystemClock.uptimeMillis(); 15040 if (mAttachInfo != null) { 15041 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 15042 Choreographer.CALLBACK_ANIMATION, what, who, 15043 Choreographer.subtractFrameDelay(delay)); 15044 } else { 15045 ViewRootImpl.getRunQueue().postDelayed(what, delay); 15046 } 15047 } 15048 } 15049 15050 /** 15051 * Cancels a scheduled action on a drawable. 15052 * 15053 * @param who the recipient of the action 15054 * @param what the action to cancel 15055 */ 15056 public void unscheduleDrawable(Drawable who, Runnable what) { 15057 if (verifyDrawable(who) && what != null) { 15058 if (mAttachInfo != null) { 15059 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15060 Choreographer.CALLBACK_ANIMATION, what, who); 15061 } else { 15062 ViewRootImpl.getRunQueue().removeCallbacks(what); 15063 } 15064 } 15065 } 15066 15067 /** 15068 * Unschedule any events associated with the given Drawable. This can be 15069 * used when selecting a new Drawable into a view, so that the previous 15070 * one is completely unscheduled. 15071 * 15072 * @param who The Drawable to unschedule. 15073 * 15074 * @see #drawableStateChanged 15075 */ 15076 public void unscheduleDrawable(Drawable who) { 15077 if (mAttachInfo != null && who != null) { 15078 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15079 Choreographer.CALLBACK_ANIMATION, null, who); 15080 } 15081 } 15082 15083 /** 15084 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 15085 * that the View directionality can and will be resolved before its Drawables. 15086 * 15087 * Will call {@link View#onResolveDrawables} when resolution is done. 15088 * 15089 * @hide 15090 */ 15091 protected void resolveDrawables() { 15092 // Drawables resolution may need to happen before resolving the layout direction (which is 15093 // done only during the measure() call). 15094 // If the layout direction is not resolved yet, we cannot resolve the Drawables except in 15095 // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT. 15096 // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or 15097 // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout 15098 // direction to be resolved as its resolved value will be the same as its raw value. 15099 if (!isLayoutDirectionResolved() && 15100 getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) { 15101 return; 15102 } 15103 15104 final int layoutDirection = isLayoutDirectionResolved() ? 15105 getLayoutDirection() : getRawLayoutDirection(); 15106 15107 if (mBackground != null) { 15108 mBackground.setLayoutDirection(layoutDirection); 15109 } 15110 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED; 15111 onResolveDrawables(layoutDirection); 15112 } 15113 15114 /** 15115 * Called when layout direction has been resolved. 15116 * 15117 * The default implementation does nothing. 15118 * 15119 * @param layoutDirection The resolved layout direction. 15120 * 15121 * @see #LAYOUT_DIRECTION_LTR 15122 * @see #LAYOUT_DIRECTION_RTL 15123 * 15124 * @hide 15125 */ 15126 public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) { 15127 } 15128 15129 /** 15130 * @hide 15131 */ 15132 protected void resetResolvedDrawables() { 15133 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED; 15134 } 15135 15136 private boolean isDrawablesResolved() { 15137 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED; 15138 } 15139 15140 /** 15141 * If your view subclass is displaying its own Drawable objects, it should 15142 * override this function and return true for any Drawable it is 15143 * displaying. This allows animations for those drawables to be 15144 * scheduled. 15145 * 15146 * <p>Be sure to call through to the super class when overriding this 15147 * function. 15148 * 15149 * @param who The Drawable to verify. Return true if it is one you are 15150 * displaying, else return the result of calling through to the 15151 * super class. 15152 * 15153 * @return boolean If true than the Drawable is being displayed in the 15154 * view; else false and it is not allowed to animate. 15155 * 15156 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 15157 * @see #drawableStateChanged() 15158 */ 15159 protected boolean verifyDrawable(Drawable who) { 15160 return who == mBackground; 15161 } 15162 15163 /** 15164 * This function is called whenever the state of the view changes in such 15165 * a way that it impacts the state of drawables being shown. 15166 * 15167 * <p>Be sure to call through to the superclass when overriding this 15168 * function. 15169 * 15170 * @see Drawable#setState(int[]) 15171 */ 15172 protected void drawableStateChanged() { 15173 Drawable d = mBackground; 15174 if (d != null && d.isStateful()) { 15175 d.setState(getDrawableState()); 15176 } 15177 } 15178 15179 /** 15180 * Call this to force a view to update its drawable state. This will cause 15181 * drawableStateChanged to be called on this view. Views that are interested 15182 * in the new state should call getDrawableState. 15183 * 15184 * @see #drawableStateChanged 15185 * @see #getDrawableState 15186 */ 15187 public void refreshDrawableState() { 15188 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 15189 drawableStateChanged(); 15190 15191 ViewParent parent = mParent; 15192 if (parent != null) { 15193 parent.childDrawableStateChanged(this); 15194 } 15195 } 15196 15197 /** 15198 * Return an array of resource IDs of the drawable states representing the 15199 * current state of the view. 15200 * 15201 * @return The current drawable state 15202 * 15203 * @see Drawable#setState(int[]) 15204 * @see #drawableStateChanged() 15205 * @see #onCreateDrawableState(int) 15206 */ 15207 public final int[] getDrawableState() { 15208 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 15209 return mDrawableState; 15210 } else { 15211 mDrawableState = onCreateDrawableState(0); 15212 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 15213 return mDrawableState; 15214 } 15215 } 15216 15217 /** 15218 * Generate the new {@link android.graphics.drawable.Drawable} state for 15219 * this view. This is called by the view 15220 * system when the cached Drawable state is determined to be invalid. To 15221 * retrieve the current state, you should use {@link #getDrawableState}. 15222 * 15223 * @param extraSpace if non-zero, this is the number of extra entries you 15224 * would like in the returned array in which you can place your own 15225 * states. 15226 * 15227 * @return Returns an array holding the current {@link Drawable} state of 15228 * the view. 15229 * 15230 * @see #mergeDrawableStates(int[], int[]) 15231 */ 15232 protected int[] onCreateDrawableState(int extraSpace) { 15233 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 15234 mParent instanceof View) { 15235 return ((View) mParent).onCreateDrawableState(extraSpace); 15236 } 15237 15238 int[] drawableState; 15239 15240 int privateFlags = mPrivateFlags; 15241 15242 int viewStateIndex = 0; 15243 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 15244 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 15245 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 15246 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 15247 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 15248 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 15249 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 15250 HardwareRenderer.isAvailable()) { 15251 // This is set if HW acceleration is requested, even if the current 15252 // process doesn't allow it. This is just to allow app preview 15253 // windows to better match their app. 15254 viewStateIndex |= VIEW_STATE_ACCELERATED; 15255 } 15256 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 15257 15258 final int privateFlags2 = mPrivateFlags2; 15259 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 15260 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 15261 15262 drawableState = VIEW_STATE_SETS[viewStateIndex]; 15263 15264 //noinspection ConstantIfStatement 15265 if (false) { 15266 Log.i("View", "drawableStateIndex=" + viewStateIndex); 15267 Log.i("View", toString() 15268 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 15269 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 15270 + " fo=" + hasFocus() 15271 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 15272 + " wf=" + hasWindowFocus() 15273 + ": " + Arrays.toString(drawableState)); 15274 } 15275 15276 if (extraSpace == 0) { 15277 return drawableState; 15278 } 15279 15280 final int[] fullState; 15281 if (drawableState != null) { 15282 fullState = new int[drawableState.length + extraSpace]; 15283 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 15284 } else { 15285 fullState = new int[extraSpace]; 15286 } 15287 15288 return fullState; 15289 } 15290 15291 /** 15292 * Merge your own state values in <var>additionalState</var> into the base 15293 * state values <var>baseState</var> that were returned by 15294 * {@link #onCreateDrawableState(int)}. 15295 * 15296 * @param baseState The base state values returned by 15297 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 15298 * own additional state values. 15299 * 15300 * @param additionalState The additional state values you would like 15301 * added to <var>baseState</var>; this array is not modified. 15302 * 15303 * @return As a convenience, the <var>baseState</var> array you originally 15304 * passed into the function is returned. 15305 * 15306 * @see #onCreateDrawableState(int) 15307 */ 15308 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 15309 final int N = baseState.length; 15310 int i = N - 1; 15311 while (i >= 0 && baseState[i] == 0) { 15312 i--; 15313 } 15314 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 15315 return baseState; 15316 } 15317 15318 /** 15319 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 15320 * on all Drawable objects associated with this view. 15321 */ 15322 public void jumpDrawablesToCurrentState() { 15323 if (mBackground != null) { 15324 mBackground.jumpToCurrentState(); 15325 } 15326 } 15327 15328 /** 15329 * Sets the background color for this view. 15330 * @param color the color of the background 15331 */ 15332 @RemotableViewMethod 15333 public void setBackgroundColor(int color) { 15334 if (mBackground instanceof ColorDrawable) { 15335 ((ColorDrawable) mBackground.mutate()).setColor(color); 15336 computeOpaqueFlags(); 15337 mBackgroundResource = 0; 15338 } else { 15339 setBackground(new ColorDrawable(color)); 15340 } 15341 } 15342 15343 /** 15344 * Set the background to a given resource. The resource should refer to 15345 * a Drawable object or 0 to remove the background. 15346 * @param resid The identifier of the resource. 15347 * 15348 * @attr ref android.R.styleable#View_background 15349 */ 15350 @RemotableViewMethod 15351 public void setBackgroundResource(int resid) { 15352 if (resid != 0 && resid == mBackgroundResource) { 15353 return; 15354 } 15355 15356 Drawable d= null; 15357 if (resid != 0) { 15358 d = mResources.getDrawable(resid); 15359 } 15360 setBackground(d); 15361 15362 mBackgroundResource = resid; 15363 } 15364 15365 /** 15366 * Set the background to a given Drawable, or remove the background. If the 15367 * background has padding, this View's padding is set to the background's 15368 * padding. However, when a background is removed, this View's padding isn't 15369 * touched. If setting the padding is desired, please use 15370 * {@link #setPadding(int, int, int, int)}. 15371 * 15372 * @param background The Drawable to use as the background, or null to remove the 15373 * background 15374 */ 15375 public void setBackground(Drawable background) { 15376 //noinspection deprecation 15377 setBackgroundDrawable(background); 15378 } 15379 15380 /** 15381 * @deprecated use {@link #setBackground(Drawable)} instead 15382 */ 15383 @Deprecated 15384 public void setBackgroundDrawable(Drawable background) { 15385 computeOpaqueFlags(); 15386 15387 if (background == mBackground) { 15388 return; 15389 } 15390 15391 boolean requestLayout = false; 15392 15393 mBackgroundResource = 0; 15394 15395 /* 15396 * Regardless of whether we're setting a new background or not, we want 15397 * to clear the previous drawable. 15398 */ 15399 if (mBackground != null) { 15400 mBackground.setCallback(null); 15401 unscheduleDrawable(mBackground); 15402 } 15403 15404 if (background != null) { 15405 Rect padding = sThreadLocal.get(); 15406 if (padding == null) { 15407 padding = new Rect(); 15408 sThreadLocal.set(padding); 15409 } 15410 resetResolvedDrawables(); 15411 background.setLayoutDirection(getLayoutDirection()); 15412 if (background.getPadding(padding)) { 15413 resetResolvedPadding(); 15414 switch (background.getLayoutDirection()) { 15415 case LAYOUT_DIRECTION_RTL: 15416 mUserPaddingLeftInitial = padding.right; 15417 mUserPaddingRightInitial = padding.left; 15418 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 15419 break; 15420 case LAYOUT_DIRECTION_LTR: 15421 default: 15422 mUserPaddingLeftInitial = padding.left; 15423 mUserPaddingRightInitial = padding.right; 15424 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 15425 } 15426 } 15427 15428 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 15429 // if it has a different minimum size, we should layout again 15430 if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() || 15431 mBackground.getMinimumWidth() != background.getMinimumWidth()) { 15432 requestLayout = true; 15433 } 15434 15435 background.setCallback(this); 15436 if (background.isStateful()) { 15437 background.setState(getDrawableState()); 15438 } 15439 background.setVisible(getVisibility() == VISIBLE, false); 15440 mBackground = background; 15441 15442 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 15443 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 15444 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 15445 requestLayout = true; 15446 } 15447 } else { 15448 /* Remove the background */ 15449 mBackground = null; 15450 15451 if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) { 15452 /* 15453 * This view ONLY drew the background before and we're removing 15454 * the background, so now it won't draw anything 15455 * (hence we SKIP_DRAW) 15456 */ 15457 mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND; 15458 mPrivateFlags |= PFLAG_SKIP_DRAW; 15459 } 15460 15461 /* 15462 * When the background is set, we try to apply its padding to this 15463 * View. When the background is removed, we don't touch this View's 15464 * padding. This is noted in the Javadocs. Hence, we don't need to 15465 * requestLayout(), the invalidate() below is sufficient. 15466 */ 15467 15468 // The old background's minimum size could have affected this 15469 // View's layout, so let's requestLayout 15470 requestLayout = true; 15471 } 15472 15473 computeOpaqueFlags(); 15474 15475 if (requestLayout) { 15476 requestLayout(); 15477 } 15478 15479 mBackgroundSizeChanged = true; 15480 invalidate(true); 15481 } 15482 15483 /** 15484 * Gets the background drawable 15485 * 15486 * @return The drawable used as the background for this view, if any. 15487 * 15488 * @see #setBackground(Drawable) 15489 * 15490 * @attr ref android.R.styleable#View_background 15491 */ 15492 public Drawable getBackground() { 15493 return mBackground; 15494 } 15495 15496 /** 15497 * Sets the padding. The view may add on the space required to display 15498 * the scrollbars, depending on the style and visibility of the scrollbars. 15499 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 15500 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 15501 * from the values set in this call. 15502 * 15503 * @attr ref android.R.styleable#View_padding 15504 * @attr ref android.R.styleable#View_paddingBottom 15505 * @attr ref android.R.styleable#View_paddingLeft 15506 * @attr ref android.R.styleable#View_paddingRight 15507 * @attr ref android.R.styleable#View_paddingTop 15508 * @param left the left padding in pixels 15509 * @param top the top padding in pixels 15510 * @param right the right padding in pixels 15511 * @param bottom the bottom padding in pixels 15512 */ 15513 public void setPadding(int left, int top, int right, int bottom) { 15514 resetResolvedPadding(); 15515 15516 mUserPaddingStart = UNDEFINED_PADDING; 15517 mUserPaddingEnd = UNDEFINED_PADDING; 15518 15519 mUserPaddingLeftInitial = left; 15520 mUserPaddingRightInitial = right; 15521 15522 internalSetPadding(left, top, right, bottom); 15523 } 15524 15525 /** 15526 * @hide 15527 */ 15528 protected void internalSetPadding(int left, int top, int right, int bottom) { 15529 mUserPaddingLeft = left; 15530 mUserPaddingRight = right; 15531 mUserPaddingBottom = bottom; 15532 15533 final int viewFlags = mViewFlags; 15534 boolean changed = false; 15535 15536 // Common case is there are no scroll bars. 15537 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 15538 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 15539 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 15540 ? 0 : getVerticalScrollbarWidth(); 15541 switch (mVerticalScrollbarPosition) { 15542 case SCROLLBAR_POSITION_DEFAULT: 15543 if (isLayoutRtl()) { 15544 left += offset; 15545 } else { 15546 right += offset; 15547 } 15548 break; 15549 case SCROLLBAR_POSITION_RIGHT: 15550 right += offset; 15551 break; 15552 case SCROLLBAR_POSITION_LEFT: 15553 left += offset; 15554 break; 15555 } 15556 } 15557 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 15558 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 15559 ? 0 : getHorizontalScrollbarHeight(); 15560 } 15561 } 15562 15563 if (mPaddingLeft != left) { 15564 changed = true; 15565 mPaddingLeft = left; 15566 } 15567 if (mPaddingTop != top) { 15568 changed = true; 15569 mPaddingTop = top; 15570 } 15571 if (mPaddingRight != right) { 15572 changed = true; 15573 mPaddingRight = right; 15574 } 15575 if (mPaddingBottom != bottom) { 15576 changed = true; 15577 mPaddingBottom = bottom; 15578 } 15579 15580 if (changed) { 15581 requestLayout(); 15582 } 15583 } 15584 15585 /** 15586 * Sets the relative padding. The view may add on the space required to display 15587 * the scrollbars, depending on the style and visibility of the scrollbars. 15588 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 15589 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 15590 * from the values set in this call. 15591 * 15592 * @attr ref android.R.styleable#View_padding 15593 * @attr ref android.R.styleable#View_paddingBottom 15594 * @attr ref android.R.styleable#View_paddingStart 15595 * @attr ref android.R.styleable#View_paddingEnd 15596 * @attr ref android.R.styleable#View_paddingTop 15597 * @param start the start padding in pixels 15598 * @param top the top padding in pixels 15599 * @param end the end padding in pixels 15600 * @param bottom the bottom padding in pixels 15601 */ 15602 public void setPaddingRelative(int start, int top, int end, int bottom) { 15603 resetResolvedPadding(); 15604 15605 mUserPaddingStart = start; 15606 mUserPaddingEnd = end; 15607 15608 switch(getLayoutDirection()) { 15609 case LAYOUT_DIRECTION_RTL: 15610 mUserPaddingLeftInitial = end; 15611 mUserPaddingRightInitial = start; 15612 internalSetPadding(end, top, start, bottom); 15613 break; 15614 case LAYOUT_DIRECTION_LTR: 15615 default: 15616 mUserPaddingLeftInitial = start; 15617 mUserPaddingRightInitial = end; 15618 internalSetPadding(start, top, end, bottom); 15619 } 15620 } 15621 15622 /** 15623 * Returns the top padding of this view. 15624 * 15625 * @return the top padding in pixels 15626 */ 15627 public int getPaddingTop() { 15628 return mPaddingTop; 15629 } 15630 15631 /** 15632 * Returns the bottom padding of this view. If there are inset and enabled 15633 * scrollbars, this value may include the space required to display the 15634 * scrollbars as well. 15635 * 15636 * @return the bottom padding in pixels 15637 */ 15638 public int getPaddingBottom() { 15639 return mPaddingBottom; 15640 } 15641 15642 /** 15643 * Returns the left padding of this view. If there are inset and enabled 15644 * scrollbars, this value may include the space required to display the 15645 * scrollbars as well. 15646 * 15647 * @return the left padding in pixels 15648 */ 15649 public int getPaddingLeft() { 15650 if (!isPaddingResolved()) { 15651 resolvePadding(); 15652 } 15653 return mPaddingLeft; 15654 } 15655 15656 /** 15657 * Returns the start padding of this view depending on its resolved layout direction. 15658 * If there are inset and enabled scrollbars, this value may include the space 15659 * required to display the scrollbars as well. 15660 * 15661 * @return the start padding in pixels 15662 */ 15663 public int getPaddingStart() { 15664 if (!isPaddingResolved()) { 15665 resolvePadding(); 15666 } 15667 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 15668 mPaddingRight : mPaddingLeft; 15669 } 15670 15671 /** 15672 * Returns the right padding of this view. If there are inset and enabled 15673 * scrollbars, this value may include the space required to display the 15674 * scrollbars as well. 15675 * 15676 * @return the right padding in pixels 15677 */ 15678 public int getPaddingRight() { 15679 if (!isPaddingResolved()) { 15680 resolvePadding(); 15681 } 15682 return mPaddingRight; 15683 } 15684 15685 /** 15686 * Returns the end padding of this view depending on its resolved layout direction. 15687 * If there are inset and enabled scrollbars, this value may include the space 15688 * required to display the scrollbars as well. 15689 * 15690 * @return the end padding in pixels 15691 */ 15692 public int getPaddingEnd() { 15693 if (!isPaddingResolved()) { 15694 resolvePadding(); 15695 } 15696 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 15697 mPaddingLeft : mPaddingRight; 15698 } 15699 15700 /** 15701 * Return if the padding as been set thru relative values 15702 * {@link #setPaddingRelative(int, int, int, int)} or thru 15703 * @attr ref android.R.styleable#View_paddingStart or 15704 * @attr ref android.R.styleable#View_paddingEnd 15705 * 15706 * @return true if the padding is relative or false if it is not. 15707 */ 15708 public boolean isPaddingRelative() { 15709 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 15710 } 15711 15712 Insets computeOpticalInsets() { 15713 return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets(); 15714 } 15715 15716 /** 15717 * @hide 15718 */ 15719 public void resetPaddingToInitialValues() { 15720 if (isRtlCompatibilityMode()) { 15721 mPaddingLeft = mUserPaddingLeftInitial; 15722 mPaddingRight = mUserPaddingRightInitial; 15723 return; 15724 } 15725 if (isLayoutRtl()) { 15726 mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial; 15727 mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial; 15728 } else { 15729 mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial; 15730 mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial; 15731 } 15732 } 15733 15734 /** 15735 * @hide 15736 */ 15737 public Insets getOpticalInsets() { 15738 if (mLayoutInsets == null) { 15739 mLayoutInsets = computeOpticalInsets(); 15740 } 15741 return mLayoutInsets; 15742 } 15743 15744 /** 15745 * Changes the selection state of this view. A view can be selected or not. 15746 * Note that selection is not the same as focus. Views are typically 15747 * selected in the context of an AdapterView like ListView or GridView; 15748 * the selected view is the view that is highlighted. 15749 * 15750 * @param selected true if the view must be selected, false otherwise 15751 */ 15752 public void setSelected(boolean selected) { 15753 //noinspection DoubleNegation 15754 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 15755 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 15756 if (!selected) resetPressedState(); 15757 invalidate(true); 15758 refreshDrawableState(); 15759 dispatchSetSelected(selected); 15760 notifyViewAccessibilityStateChangedIfNeeded( 15761 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 15762 } 15763 } 15764 15765 /** 15766 * Dispatch setSelected to all of this View's children. 15767 * 15768 * @see #setSelected(boolean) 15769 * 15770 * @param selected The new selected state 15771 */ 15772 protected void dispatchSetSelected(boolean selected) { 15773 } 15774 15775 /** 15776 * Indicates the selection state of this view. 15777 * 15778 * @return true if the view is selected, false otherwise 15779 */ 15780 @ViewDebug.ExportedProperty 15781 public boolean isSelected() { 15782 return (mPrivateFlags & PFLAG_SELECTED) != 0; 15783 } 15784 15785 /** 15786 * Changes the activated state of this view. A view can be activated or not. 15787 * Note that activation is not the same as selection. Selection is 15788 * a transient property, representing the view (hierarchy) the user is 15789 * currently interacting with. Activation is a longer-term state that the 15790 * user can move views in and out of. For example, in a list view with 15791 * single or multiple selection enabled, the views in the current selection 15792 * set are activated. (Um, yeah, we are deeply sorry about the terminology 15793 * here.) The activated state is propagated down to children of the view it 15794 * is set on. 15795 * 15796 * @param activated true if the view must be activated, false otherwise 15797 */ 15798 public void setActivated(boolean activated) { 15799 //noinspection DoubleNegation 15800 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 15801 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 15802 invalidate(true); 15803 refreshDrawableState(); 15804 dispatchSetActivated(activated); 15805 } 15806 } 15807 15808 /** 15809 * Dispatch setActivated to all of this View's children. 15810 * 15811 * @see #setActivated(boolean) 15812 * 15813 * @param activated The new activated state 15814 */ 15815 protected void dispatchSetActivated(boolean activated) { 15816 } 15817 15818 /** 15819 * Indicates the activation state of this view. 15820 * 15821 * @return true if the view is activated, false otherwise 15822 */ 15823 @ViewDebug.ExportedProperty 15824 public boolean isActivated() { 15825 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 15826 } 15827 15828 /** 15829 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 15830 * observer can be used to get notifications when global events, like 15831 * layout, happen. 15832 * 15833 * The returned ViewTreeObserver observer is not guaranteed to remain 15834 * valid for the lifetime of this View. If the caller of this method keeps 15835 * a long-lived reference to ViewTreeObserver, it should always check for 15836 * the return value of {@link ViewTreeObserver#isAlive()}. 15837 * 15838 * @return The ViewTreeObserver for this view's hierarchy. 15839 */ 15840 public ViewTreeObserver getViewTreeObserver() { 15841 if (mAttachInfo != null) { 15842 return mAttachInfo.mTreeObserver; 15843 } 15844 if (mFloatingTreeObserver == null) { 15845 mFloatingTreeObserver = new ViewTreeObserver(); 15846 } 15847 return mFloatingTreeObserver; 15848 } 15849 15850 /** 15851 * <p>Finds the topmost view in the current view hierarchy.</p> 15852 * 15853 * @return the topmost view containing this view 15854 */ 15855 public View getRootView() { 15856 if (mAttachInfo != null) { 15857 final View v = mAttachInfo.mRootView; 15858 if (v != null) { 15859 return v; 15860 } 15861 } 15862 15863 View parent = this; 15864 15865 while (parent.mParent != null && parent.mParent instanceof View) { 15866 parent = (View) parent.mParent; 15867 } 15868 15869 return parent; 15870 } 15871 15872 /** 15873 * Transforms a motion event from view-local coordinates to on-screen 15874 * coordinates. 15875 * 15876 * @param ev the view-local motion event 15877 * @return false if the transformation could not be applied 15878 * @hide 15879 */ 15880 public boolean toGlobalMotionEvent(MotionEvent ev) { 15881 final AttachInfo info = mAttachInfo; 15882 if (info == null) { 15883 return false; 15884 } 15885 15886 transformMotionEventToGlobal(ev); 15887 ev.offsetLocation(info.mWindowLeft, info.mWindowTop); 15888 return true; 15889 } 15890 15891 /** 15892 * Transforms a motion event from on-screen coordinates to view-local 15893 * coordinates. 15894 * 15895 * @param ev the on-screen motion event 15896 * @return false if the transformation could not be applied 15897 * @hide 15898 */ 15899 public boolean toLocalMotionEvent(MotionEvent ev) { 15900 final AttachInfo info = mAttachInfo; 15901 if (info == null) { 15902 return false; 15903 } 15904 15905 ev.offsetLocation(-info.mWindowLeft, -info.mWindowTop); 15906 transformMotionEventToLocal(ev); 15907 return true; 15908 } 15909 15910 /** 15911 * Recursive helper method that applies transformations in post-order. 15912 * 15913 * @param ev the on-screen motion event 15914 */ 15915 private void transformMotionEventToLocal(MotionEvent ev) { 15916 final ViewParent parent = mParent; 15917 if (parent instanceof View) { 15918 final View vp = (View) parent; 15919 vp.transformMotionEventToLocal(ev); 15920 ev.offsetLocation(vp.mScrollX, vp.mScrollY); 15921 } else if (parent instanceof ViewRootImpl) { 15922 final ViewRootImpl vr = (ViewRootImpl) parent; 15923 ev.offsetLocation(0, vr.mCurScrollY); 15924 } 15925 15926 ev.offsetLocation(-mLeft, -mTop); 15927 15928 if (!hasIdentityMatrix()) { 15929 ev.transform(getInverseMatrix()); 15930 } 15931 } 15932 15933 /** 15934 * Recursive helper method that applies transformations in pre-order. 15935 * 15936 * @param ev the on-screen motion event 15937 */ 15938 private void transformMotionEventToGlobal(MotionEvent ev) { 15939 if (!hasIdentityMatrix()) { 15940 ev.transform(getMatrix()); 15941 } 15942 15943 ev.offsetLocation(mLeft, mTop); 15944 15945 final ViewParent parent = mParent; 15946 if (parent instanceof View) { 15947 final View vp = (View) parent; 15948 ev.offsetLocation(-vp.mScrollX, -vp.mScrollY); 15949 vp.transformMotionEventToGlobal(ev); 15950 } else if (parent instanceof ViewRootImpl) { 15951 final ViewRootImpl vr = (ViewRootImpl) parent; 15952 ev.offsetLocation(0, -vr.mCurScrollY); 15953 } 15954 } 15955 15956 /** 15957 * <p>Computes the coordinates of this view on the screen. The argument 15958 * must be an array of two integers. After the method returns, the array 15959 * contains the x and y location in that order.</p> 15960 * 15961 * @param location an array of two integers in which to hold the coordinates 15962 */ 15963 public void getLocationOnScreen(int[] location) { 15964 getLocationInWindow(location); 15965 15966 final AttachInfo info = mAttachInfo; 15967 if (info != null) { 15968 location[0] += info.mWindowLeft; 15969 location[1] += info.mWindowTop; 15970 } 15971 } 15972 15973 /** 15974 * <p>Computes the coordinates of this view in its window. The argument 15975 * must be an array of two integers. After the method returns, the array 15976 * contains the x and y location in that order.</p> 15977 * 15978 * @param location an array of two integers in which to hold the coordinates 15979 */ 15980 public void getLocationInWindow(int[] location) { 15981 if (location == null || location.length < 2) { 15982 throw new IllegalArgumentException("location must be an array of two integers"); 15983 } 15984 15985 if (mAttachInfo == null) { 15986 // When the view is not attached to a window, this method does not make sense 15987 location[0] = location[1] = 0; 15988 return; 15989 } 15990 15991 float[] position = mAttachInfo.mTmpTransformLocation; 15992 position[0] = position[1] = 0.0f; 15993 15994 if (!hasIdentityMatrix()) { 15995 getMatrix().mapPoints(position); 15996 } 15997 15998 position[0] += mLeft; 15999 position[1] += mTop; 16000 16001 ViewParent viewParent = mParent; 16002 while (viewParent instanceof View) { 16003 final View view = (View) viewParent; 16004 16005 position[0] -= view.mScrollX; 16006 position[1] -= view.mScrollY; 16007 16008 if (!view.hasIdentityMatrix()) { 16009 view.getMatrix().mapPoints(position); 16010 } 16011 16012 position[0] += view.mLeft; 16013 position[1] += view.mTop; 16014 16015 viewParent = view.mParent; 16016 } 16017 16018 if (viewParent instanceof ViewRootImpl) { 16019 // *cough* 16020 final ViewRootImpl vr = (ViewRootImpl) viewParent; 16021 position[1] -= vr.mCurScrollY; 16022 } 16023 16024 location[0] = (int) (position[0] + 0.5f); 16025 location[1] = (int) (position[1] + 0.5f); 16026 } 16027 16028 /** 16029 * {@hide} 16030 * @param id the id of the view to be found 16031 * @return the view of the specified id, null if cannot be found 16032 */ 16033 protected View findViewTraversal(int id) { 16034 if (id == mID) { 16035 return this; 16036 } 16037 return null; 16038 } 16039 16040 /** 16041 * {@hide} 16042 * @param tag the tag of the view to be found 16043 * @return the view of specified tag, null if cannot be found 16044 */ 16045 protected View findViewWithTagTraversal(Object tag) { 16046 if (tag != null && tag.equals(mTag)) { 16047 return this; 16048 } 16049 return null; 16050 } 16051 16052 /** 16053 * {@hide} 16054 * @param predicate The predicate to evaluate. 16055 * @param childToSkip If not null, ignores this child during the recursive traversal. 16056 * @return The first view that matches the predicate or null. 16057 */ 16058 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 16059 if (predicate.apply(this)) { 16060 return this; 16061 } 16062 return null; 16063 } 16064 16065 /** 16066 * Look for a child view with the given id. If this view has the given 16067 * id, return this view. 16068 * 16069 * @param id The id to search for. 16070 * @return The view that has the given id in the hierarchy or null 16071 */ 16072 public final View findViewById(int id) { 16073 if (id < 0) { 16074 return null; 16075 } 16076 return findViewTraversal(id); 16077 } 16078 16079 /** 16080 * Finds a view by its unuque and stable accessibility id. 16081 * 16082 * @param accessibilityId The searched accessibility id. 16083 * @return The found view. 16084 */ 16085 final View findViewByAccessibilityId(int accessibilityId) { 16086 if (accessibilityId < 0) { 16087 return null; 16088 } 16089 return findViewByAccessibilityIdTraversal(accessibilityId); 16090 } 16091 16092 /** 16093 * Performs the traversal to find a view by its unuque and stable accessibility id. 16094 * 16095 * <strong>Note:</strong>This method does not stop at the root namespace 16096 * boundary since the user can touch the screen at an arbitrary location 16097 * potentially crossing the root namespace bounday which will send an 16098 * accessibility event to accessibility services and they should be able 16099 * to obtain the event source. Also accessibility ids are guaranteed to be 16100 * unique in the window. 16101 * 16102 * @param accessibilityId The accessibility id. 16103 * @return The found view. 16104 * 16105 * @hide 16106 */ 16107 public View findViewByAccessibilityIdTraversal(int accessibilityId) { 16108 if (getAccessibilityViewId() == accessibilityId) { 16109 return this; 16110 } 16111 return null; 16112 } 16113 16114 /** 16115 * Look for a child view with the given tag. If this view has the given 16116 * tag, return this view. 16117 * 16118 * @param tag The tag to search for, using "tag.equals(getTag())". 16119 * @return The View that has the given tag in the hierarchy or null 16120 */ 16121 public final View findViewWithTag(Object tag) { 16122 if (tag == null) { 16123 return null; 16124 } 16125 return findViewWithTagTraversal(tag); 16126 } 16127 16128 /** 16129 * {@hide} 16130 * Look for a child view that matches the specified predicate. 16131 * If this view matches the predicate, return this view. 16132 * 16133 * @param predicate The predicate to evaluate. 16134 * @return The first view that matches the predicate or null. 16135 */ 16136 public final View findViewByPredicate(Predicate<View> predicate) { 16137 return findViewByPredicateTraversal(predicate, null); 16138 } 16139 16140 /** 16141 * {@hide} 16142 * Look for a child view that matches the specified predicate, 16143 * starting with the specified view and its descendents and then 16144 * recusively searching the ancestors and siblings of that view 16145 * until this view is reached. 16146 * 16147 * This method is useful in cases where the predicate does not match 16148 * a single unique view (perhaps multiple views use the same id) 16149 * and we are trying to find the view that is "closest" in scope to the 16150 * starting view. 16151 * 16152 * @param start The view to start from. 16153 * @param predicate The predicate to evaluate. 16154 * @return The first view that matches the predicate or null. 16155 */ 16156 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 16157 View childToSkip = null; 16158 for (;;) { 16159 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 16160 if (view != null || start == this) { 16161 return view; 16162 } 16163 16164 ViewParent parent = start.getParent(); 16165 if (parent == null || !(parent instanceof View)) { 16166 return null; 16167 } 16168 16169 childToSkip = start; 16170 start = (View) parent; 16171 } 16172 } 16173 16174 /** 16175 * Sets the identifier for this view. The identifier does not have to be 16176 * unique in this view's hierarchy. The identifier should be a positive 16177 * number. 16178 * 16179 * @see #NO_ID 16180 * @see #getId() 16181 * @see #findViewById(int) 16182 * 16183 * @param id a number used to identify the view 16184 * 16185 * @attr ref android.R.styleable#View_id 16186 */ 16187 public void setId(int id) { 16188 mID = id; 16189 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 16190 mID = generateViewId(); 16191 } 16192 } 16193 16194 /** 16195 * {@hide} 16196 * 16197 * @param isRoot true if the view belongs to the root namespace, false 16198 * otherwise 16199 */ 16200 public void setIsRootNamespace(boolean isRoot) { 16201 if (isRoot) { 16202 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 16203 } else { 16204 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 16205 } 16206 } 16207 16208 /** 16209 * {@hide} 16210 * 16211 * @return true if the view belongs to the root namespace, false otherwise 16212 */ 16213 public boolean isRootNamespace() { 16214 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 16215 } 16216 16217 /** 16218 * Returns this view's identifier. 16219 * 16220 * @return a positive integer used to identify the view or {@link #NO_ID} 16221 * if the view has no ID 16222 * 16223 * @see #setId(int) 16224 * @see #findViewById(int) 16225 * @attr ref android.R.styleable#View_id 16226 */ 16227 @ViewDebug.CapturedViewProperty 16228 public int getId() { 16229 return mID; 16230 } 16231 16232 /** 16233 * Returns this view's tag. 16234 * 16235 * @return the Object stored in this view as a tag 16236 * 16237 * @see #setTag(Object) 16238 * @see #getTag(int) 16239 */ 16240 @ViewDebug.ExportedProperty 16241 public Object getTag() { 16242 return mTag; 16243 } 16244 16245 /** 16246 * Sets the tag associated with this view. A tag can be used to mark 16247 * a view in its hierarchy and does not have to be unique within the 16248 * hierarchy. Tags can also be used to store data within a view without 16249 * resorting to another data structure. 16250 * 16251 * @param tag an Object to tag the view with 16252 * 16253 * @see #getTag() 16254 * @see #setTag(int, Object) 16255 */ 16256 public void setTag(final Object tag) { 16257 mTag = tag; 16258 } 16259 16260 /** 16261 * Returns the tag associated with this view and the specified key. 16262 * 16263 * @param key The key identifying the tag 16264 * 16265 * @return the Object stored in this view as a tag 16266 * 16267 * @see #setTag(int, Object) 16268 * @see #getTag() 16269 */ 16270 public Object getTag(int key) { 16271 if (mKeyedTags != null) return mKeyedTags.get(key); 16272 return null; 16273 } 16274 16275 /** 16276 * Sets a tag associated with this view and a key. A tag can be used 16277 * to mark a view in its hierarchy and does not have to be unique within 16278 * the hierarchy. Tags can also be used to store data within a view 16279 * without resorting to another data structure. 16280 * 16281 * The specified key should be an id declared in the resources of the 16282 * application to ensure it is unique (see the <a 16283 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 16284 * Keys identified as belonging to 16285 * the Android framework or not associated with any package will cause 16286 * an {@link IllegalArgumentException} to be thrown. 16287 * 16288 * @param key The key identifying the tag 16289 * @param tag An Object to tag the view with 16290 * 16291 * @throws IllegalArgumentException If they specified key is not valid 16292 * 16293 * @see #setTag(Object) 16294 * @see #getTag(int) 16295 */ 16296 public void setTag(int key, final Object tag) { 16297 // If the package id is 0x00 or 0x01, it's either an undefined package 16298 // or a framework id 16299 if ((key >>> 24) < 2) { 16300 throw new IllegalArgumentException("The key must be an application-specific " 16301 + "resource id."); 16302 } 16303 16304 setKeyedTag(key, tag); 16305 } 16306 16307 /** 16308 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 16309 * framework id. 16310 * 16311 * @hide 16312 */ 16313 public void setTagInternal(int key, Object tag) { 16314 if ((key >>> 24) != 0x1) { 16315 throw new IllegalArgumentException("The key must be a framework-specific " 16316 + "resource id."); 16317 } 16318 16319 setKeyedTag(key, tag); 16320 } 16321 16322 private void setKeyedTag(int key, Object tag) { 16323 if (mKeyedTags == null) { 16324 mKeyedTags = new SparseArray<Object>(2); 16325 } 16326 16327 mKeyedTags.put(key, tag); 16328 } 16329 16330 /** 16331 * Prints information about this view in the log output, with the tag 16332 * {@link #VIEW_LOG_TAG}. 16333 * 16334 * @hide 16335 */ 16336 public void debug() { 16337 debug(0); 16338 } 16339 16340 /** 16341 * Prints information about this view in the log output, with the tag 16342 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 16343 * indentation defined by the <code>depth</code>. 16344 * 16345 * @param depth the indentation level 16346 * 16347 * @hide 16348 */ 16349 protected void debug(int depth) { 16350 String output = debugIndent(depth - 1); 16351 16352 output += "+ " + this; 16353 int id = getId(); 16354 if (id != -1) { 16355 output += " (id=" + id + ")"; 16356 } 16357 Object tag = getTag(); 16358 if (tag != null) { 16359 output += " (tag=" + tag + ")"; 16360 } 16361 Log.d(VIEW_LOG_TAG, output); 16362 16363 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 16364 output = debugIndent(depth) + " FOCUSED"; 16365 Log.d(VIEW_LOG_TAG, output); 16366 } 16367 16368 output = debugIndent(depth); 16369 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 16370 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 16371 + "} "; 16372 Log.d(VIEW_LOG_TAG, output); 16373 16374 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 16375 || mPaddingBottom != 0) { 16376 output = debugIndent(depth); 16377 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 16378 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 16379 Log.d(VIEW_LOG_TAG, output); 16380 } 16381 16382 output = debugIndent(depth); 16383 output += "mMeasureWidth=" + mMeasuredWidth + 16384 " mMeasureHeight=" + mMeasuredHeight; 16385 Log.d(VIEW_LOG_TAG, output); 16386 16387 output = debugIndent(depth); 16388 if (mLayoutParams == null) { 16389 output += "BAD! no layout params"; 16390 } else { 16391 output = mLayoutParams.debug(output); 16392 } 16393 Log.d(VIEW_LOG_TAG, output); 16394 16395 output = debugIndent(depth); 16396 output += "flags={"; 16397 output += View.printFlags(mViewFlags); 16398 output += "}"; 16399 Log.d(VIEW_LOG_TAG, output); 16400 16401 output = debugIndent(depth); 16402 output += "privateFlags={"; 16403 output += View.printPrivateFlags(mPrivateFlags); 16404 output += "}"; 16405 Log.d(VIEW_LOG_TAG, output); 16406 } 16407 16408 /** 16409 * Creates a string of whitespaces used for indentation. 16410 * 16411 * @param depth the indentation level 16412 * @return a String containing (depth * 2 + 3) * 2 white spaces 16413 * 16414 * @hide 16415 */ 16416 protected static String debugIndent(int depth) { 16417 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 16418 for (int i = 0; i < (depth * 2) + 3; i++) { 16419 spaces.append(' ').append(' '); 16420 } 16421 return spaces.toString(); 16422 } 16423 16424 /** 16425 * <p>Return the offset of the widget's text baseline from the widget's top 16426 * boundary. If this widget does not support baseline alignment, this 16427 * method returns -1. </p> 16428 * 16429 * @return the offset of the baseline within the widget's bounds or -1 16430 * if baseline alignment is not supported 16431 */ 16432 @ViewDebug.ExportedProperty(category = "layout") 16433 public int getBaseline() { 16434 return -1; 16435 } 16436 16437 /** 16438 * Returns whether the view hierarchy is currently undergoing a layout pass. This 16439 * information is useful to avoid situations such as calling {@link #requestLayout()} during 16440 * a layout pass. 16441 * 16442 * @return whether the view hierarchy is currently undergoing a layout pass 16443 */ 16444 public boolean isInLayout() { 16445 ViewRootImpl viewRoot = getViewRootImpl(); 16446 return (viewRoot != null && viewRoot.isInLayout()); 16447 } 16448 16449 /** 16450 * Call this when something has changed which has invalidated the 16451 * layout of this view. This will schedule a layout pass of the view 16452 * tree. This should not be called while the view hierarchy is currently in a layout 16453 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 16454 * end of the current layout pass (and then layout will run again) or after the current 16455 * frame is drawn and the next layout occurs. 16456 * 16457 * <p>Subclasses which override this method should call the superclass method to 16458 * handle possible request-during-layout errors correctly.</p> 16459 */ 16460 public void requestLayout() { 16461 if (mMeasureCache != null) mMeasureCache.clear(); 16462 16463 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) { 16464 // Only trigger request-during-layout logic if this is the view requesting it, 16465 // not the views in its parent hierarchy 16466 ViewRootImpl viewRoot = getViewRootImpl(); 16467 if (viewRoot != null && viewRoot.isInLayout()) { 16468 if (!viewRoot.requestLayoutDuringLayout(this)) { 16469 return; 16470 } 16471 } 16472 mAttachInfo.mViewRequestingLayout = this; 16473 } 16474 16475 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 16476 mPrivateFlags |= PFLAG_INVALIDATED; 16477 16478 if (mParent != null && !mParent.isLayoutRequested()) { 16479 mParent.requestLayout(); 16480 } 16481 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) { 16482 mAttachInfo.mViewRequestingLayout = null; 16483 } 16484 } 16485 16486 /** 16487 * Forces this view to be laid out during the next layout pass. 16488 * This method does not call requestLayout() or forceLayout() 16489 * on the parent. 16490 */ 16491 public void forceLayout() { 16492 if (mMeasureCache != null) mMeasureCache.clear(); 16493 16494 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 16495 mPrivateFlags |= PFLAG_INVALIDATED; 16496 } 16497 16498 /** 16499 * <p> 16500 * This is called to find out how big a view should be. The parent 16501 * supplies constraint information in the width and height parameters. 16502 * </p> 16503 * 16504 * <p> 16505 * The actual measurement work of a view is performed in 16506 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 16507 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 16508 * </p> 16509 * 16510 * 16511 * @param widthMeasureSpec Horizontal space requirements as imposed by the 16512 * parent 16513 * @param heightMeasureSpec Vertical space requirements as imposed by the 16514 * parent 16515 * 16516 * @see #onMeasure(int, int) 16517 */ 16518 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 16519 boolean optical = isLayoutModeOptical(this); 16520 if (optical != isLayoutModeOptical(mParent)) { 16521 Insets insets = getOpticalInsets(); 16522 int oWidth = insets.left + insets.right; 16523 int oHeight = insets.top + insets.bottom; 16524 widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth); 16525 heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight); 16526 } 16527 16528 // Suppress sign extension for the low bytes 16529 long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL; 16530 if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2); 16531 16532 if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT || 16533 widthMeasureSpec != mOldWidthMeasureSpec || 16534 heightMeasureSpec != mOldHeightMeasureSpec) { 16535 16536 // first clears the measured dimension flag 16537 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 16538 16539 resolveRtlPropertiesIfNeeded(); 16540 16541 int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 : 16542 mMeasureCache.indexOfKey(key); 16543 if (cacheIndex < 0) { 16544 // measure ourselves, this should set the measured dimension flag back 16545 onMeasure(widthMeasureSpec, heightMeasureSpec); 16546 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 16547 } else { 16548 long value = mMeasureCache.valueAt(cacheIndex); 16549 // Casting a long to int drops the high 32 bits, no mask needed 16550 setMeasuredDimension((int) (value >> 32), (int) value); 16551 mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 16552 } 16553 16554 // flag not set, setMeasuredDimension() was not invoked, we raise 16555 // an exception to warn the developer 16556 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 16557 throw new IllegalStateException("onMeasure() did not set the" 16558 + " measured dimension by calling" 16559 + " setMeasuredDimension()"); 16560 } 16561 16562 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 16563 } 16564 16565 mOldWidthMeasureSpec = widthMeasureSpec; 16566 mOldHeightMeasureSpec = heightMeasureSpec; 16567 16568 mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 | 16569 (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension 16570 } 16571 16572 /** 16573 * <p> 16574 * Measure the view and its content to determine the measured width and the 16575 * measured height. This method is invoked by {@link #measure(int, int)} and 16576 * should be overriden by subclasses to provide accurate and efficient 16577 * measurement of their contents. 16578 * </p> 16579 * 16580 * <p> 16581 * <strong>CONTRACT:</strong> When overriding this method, you 16582 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 16583 * measured width and height of this view. Failure to do so will trigger an 16584 * <code>IllegalStateException</code>, thrown by 16585 * {@link #measure(int, int)}. Calling the superclass' 16586 * {@link #onMeasure(int, int)} is a valid use. 16587 * </p> 16588 * 16589 * <p> 16590 * The base class implementation of measure defaults to the background size, 16591 * unless a larger size is allowed by the MeasureSpec. Subclasses should 16592 * override {@link #onMeasure(int, int)} to provide better measurements of 16593 * their content. 16594 * </p> 16595 * 16596 * <p> 16597 * If this method is overridden, it is the subclass's responsibility to make 16598 * sure the measured height and width are at least the view's minimum height 16599 * and width ({@link #getSuggestedMinimumHeight()} and 16600 * {@link #getSuggestedMinimumWidth()}). 16601 * </p> 16602 * 16603 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 16604 * The requirements are encoded with 16605 * {@link android.view.View.MeasureSpec}. 16606 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 16607 * The requirements are encoded with 16608 * {@link android.view.View.MeasureSpec}. 16609 * 16610 * @see #getMeasuredWidth() 16611 * @see #getMeasuredHeight() 16612 * @see #setMeasuredDimension(int, int) 16613 * @see #getSuggestedMinimumHeight() 16614 * @see #getSuggestedMinimumWidth() 16615 * @see android.view.View.MeasureSpec#getMode(int) 16616 * @see android.view.View.MeasureSpec#getSize(int) 16617 */ 16618 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 16619 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 16620 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 16621 } 16622 16623 /** 16624 * <p>This method must be called by {@link #onMeasure(int, int)} to store the 16625 * measured width and measured height. Failing to do so will trigger an 16626 * exception at measurement time.</p> 16627 * 16628 * @param measuredWidth The measured width of this view. May be a complex 16629 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 16630 * {@link #MEASURED_STATE_TOO_SMALL}. 16631 * @param measuredHeight The measured height of this view. May be a complex 16632 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 16633 * {@link #MEASURED_STATE_TOO_SMALL}. 16634 */ 16635 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 16636 boolean optical = isLayoutModeOptical(this); 16637 if (optical != isLayoutModeOptical(mParent)) { 16638 Insets insets = getOpticalInsets(); 16639 int opticalWidth = insets.left + insets.right; 16640 int opticalHeight = insets.top + insets.bottom; 16641 16642 measuredWidth += optical ? opticalWidth : -opticalWidth; 16643 measuredHeight += optical ? opticalHeight : -opticalHeight; 16644 } 16645 mMeasuredWidth = measuredWidth; 16646 mMeasuredHeight = measuredHeight; 16647 16648 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 16649 } 16650 16651 /** 16652 * Merge two states as returned by {@link #getMeasuredState()}. 16653 * @param curState The current state as returned from a view or the result 16654 * of combining multiple views. 16655 * @param newState The new view state to combine. 16656 * @return Returns a new integer reflecting the combination of the two 16657 * states. 16658 */ 16659 public static int combineMeasuredStates(int curState, int newState) { 16660 return curState | newState; 16661 } 16662 16663 /** 16664 * Version of {@link #resolveSizeAndState(int, int, int)} 16665 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 16666 */ 16667 public static int resolveSize(int size, int measureSpec) { 16668 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 16669 } 16670 16671 /** 16672 * Utility to reconcile a desired size and state, with constraints imposed 16673 * by a MeasureSpec. Will take the desired size, unless a different size 16674 * is imposed by the constraints. The returned value is a compound integer, 16675 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 16676 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 16677 * size is smaller than the size the view wants to be. 16678 * 16679 * @param size How big the view wants to be 16680 * @param measureSpec Constraints imposed by the parent 16681 * @return Size information bit mask as defined by 16682 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 16683 */ 16684 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 16685 int result = size; 16686 int specMode = MeasureSpec.getMode(measureSpec); 16687 int specSize = MeasureSpec.getSize(measureSpec); 16688 switch (specMode) { 16689 case MeasureSpec.UNSPECIFIED: 16690 result = size; 16691 break; 16692 case MeasureSpec.AT_MOST: 16693 if (specSize < size) { 16694 result = specSize | MEASURED_STATE_TOO_SMALL; 16695 } else { 16696 result = size; 16697 } 16698 break; 16699 case MeasureSpec.EXACTLY: 16700 result = specSize; 16701 break; 16702 } 16703 return result | (childMeasuredState&MEASURED_STATE_MASK); 16704 } 16705 16706 /** 16707 * Utility to return a default size. Uses the supplied size if the 16708 * MeasureSpec imposed no constraints. Will get larger if allowed 16709 * by the MeasureSpec. 16710 * 16711 * @param size Default size for this view 16712 * @param measureSpec Constraints imposed by the parent 16713 * @return The size this view should be. 16714 */ 16715 public static int getDefaultSize(int size, int measureSpec) { 16716 int result = size; 16717 int specMode = MeasureSpec.getMode(measureSpec); 16718 int specSize = MeasureSpec.getSize(measureSpec); 16719 16720 switch (specMode) { 16721 case MeasureSpec.UNSPECIFIED: 16722 result = size; 16723 break; 16724 case MeasureSpec.AT_MOST: 16725 case MeasureSpec.EXACTLY: 16726 result = specSize; 16727 break; 16728 } 16729 return result; 16730 } 16731 16732 /** 16733 * Returns the suggested minimum height that the view should use. This 16734 * returns the maximum of the view's minimum height 16735 * and the background's minimum height 16736 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 16737 * <p> 16738 * When being used in {@link #onMeasure(int, int)}, the caller should still 16739 * ensure the returned height is within the requirements of the parent. 16740 * 16741 * @return The suggested minimum height of the view. 16742 */ 16743 protected int getSuggestedMinimumHeight() { 16744 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 16745 16746 } 16747 16748 /** 16749 * Returns the suggested minimum width that the view should use. This 16750 * returns the maximum of the view's minimum width) 16751 * and the background's minimum width 16752 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 16753 * <p> 16754 * When being used in {@link #onMeasure(int, int)}, the caller should still 16755 * ensure the returned width is within the requirements of the parent. 16756 * 16757 * @return The suggested minimum width of the view. 16758 */ 16759 protected int getSuggestedMinimumWidth() { 16760 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 16761 } 16762 16763 /** 16764 * Returns the minimum height of the view. 16765 * 16766 * @return the minimum height the view will try to be. 16767 * 16768 * @see #setMinimumHeight(int) 16769 * 16770 * @attr ref android.R.styleable#View_minHeight 16771 */ 16772 public int getMinimumHeight() { 16773 return mMinHeight; 16774 } 16775 16776 /** 16777 * Sets the minimum height of the view. It is not guaranteed the view will 16778 * be able to achieve this minimum height (for example, if its parent layout 16779 * constrains it with less available height). 16780 * 16781 * @param minHeight The minimum height the view will try to be. 16782 * 16783 * @see #getMinimumHeight() 16784 * 16785 * @attr ref android.R.styleable#View_minHeight 16786 */ 16787 public void setMinimumHeight(int minHeight) { 16788 mMinHeight = minHeight; 16789 requestLayout(); 16790 } 16791 16792 /** 16793 * Returns the minimum width of the view. 16794 * 16795 * @return the minimum width the view will try to be. 16796 * 16797 * @see #setMinimumWidth(int) 16798 * 16799 * @attr ref android.R.styleable#View_minWidth 16800 */ 16801 public int getMinimumWidth() { 16802 return mMinWidth; 16803 } 16804 16805 /** 16806 * Sets the minimum width of the view. It is not guaranteed the view will 16807 * be able to achieve this minimum width (for example, if its parent layout 16808 * constrains it with less available width). 16809 * 16810 * @param minWidth The minimum width the view will try to be. 16811 * 16812 * @see #getMinimumWidth() 16813 * 16814 * @attr ref android.R.styleable#View_minWidth 16815 */ 16816 public void setMinimumWidth(int minWidth) { 16817 mMinWidth = minWidth; 16818 requestLayout(); 16819 16820 } 16821 16822 /** 16823 * Get the animation currently associated with this view. 16824 * 16825 * @return The animation that is currently playing or 16826 * scheduled to play for this view. 16827 */ 16828 public Animation getAnimation() { 16829 return mCurrentAnimation; 16830 } 16831 16832 /** 16833 * Start the specified animation now. 16834 * 16835 * @param animation the animation to start now 16836 */ 16837 public void startAnimation(Animation animation) { 16838 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 16839 setAnimation(animation); 16840 invalidateParentCaches(); 16841 invalidate(true); 16842 } 16843 16844 /** 16845 * Cancels any animations for this view. 16846 */ 16847 public void clearAnimation() { 16848 if (mCurrentAnimation != null) { 16849 mCurrentAnimation.detach(); 16850 } 16851 mCurrentAnimation = null; 16852 invalidateParentIfNeeded(); 16853 } 16854 16855 /** 16856 * Sets the next animation to play for this view. 16857 * If you want the animation to play immediately, use 16858 * {@link #startAnimation(android.view.animation.Animation)} instead. 16859 * This method provides allows fine-grained 16860 * control over the start time and invalidation, but you 16861 * must make sure that 1) the animation has a start time set, and 16862 * 2) the view's parent (which controls animations on its children) 16863 * will be invalidated when the animation is supposed to 16864 * start. 16865 * 16866 * @param animation The next animation, or null. 16867 */ 16868 public void setAnimation(Animation animation) { 16869 mCurrentAnimation = animation; 16870 16871 if (animation != null) { 16872 // If the screen is off assume the animation start time is now instead of 16873 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 16874 // would cause the animation to start when the screen turns back on 16875 if (mAttachInfo != null && !mAttachInfo.mScreenOn && 16876 animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 16877 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 16878 } 16879 animation.reset(); 16880 } 16881 } 16882 16883 /** 16884 * Invoked by a parent ViewGroup to notify the start of the animation 16885 * currently associated with this view. If you override this method, 16886 * always call super.onAnimationStart(); 16887 * 16888 * @see #setAnimation(android.view.animation.Animation) 16889 * @see #getAnimation() 16890 */ 16891 protected void onAnimationStart() { 16892 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 16893 } 16894 16895 /** 16896 * Invoked by a parent ViewGroup to notify the end of the animation 16897 * currently associated with this view. If you override this method, 16898 * always call super.onAnimationEnd(); 16899 * 16900 * @see #setAnimation(android.view.animation.Animation) 16901 * @see #getAnimation() 16902 */ 16903 protected void onAnimationEnd() { 16904 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 16905 } 16906 16907 /** 16908 * Invoked if there is a Transform that involves alpha. Subclass that can 16909 * draw themselves with the specified alpha should return true, and then 16910 * respect that alpha when their onDraw() is called. If this returns false 16911 * then the view may be redirected to draw into an offscreen buffer to 16912 * fulfill the request, which will look fine, but may be slower than if the 16913 * subclass handles it internally. The default implementation returns false. 16914 * 16915 * @param alpha The alpha (0..255) to apply to the view's drawing 16916 * @return true if the view can draw with the specified alpha. 16917 */ 16918 protected boolean onSetAlpha(int alpha) { 16919 return false; 16920 } 16921 16922 /** 16923 * This is used by the RootView to perform an optimization when 16924 * the view hierarchy contains one or several SurfaceView. 16925 * SurfaceView is always considered transparent, but its children are not, 16926 * therefore all View objects remove themselves from the global transparent 16927 * region (passed as a parameter to this function). 16928 * 16929 * @param region The transparent region for this ViewAncestor (window). 16930 * 16931 * @return Returns true if the effective visibility of the view at this 16932 * point is opaque, regardless of the transparent region; returns false 16933 * if it is possible for underlying windows to be seen behind the view. 16934 * 16935 * {@hide} 16936 */ 16937 public boolean gatherTransparentRegion(Region region) { 16938 final AttachInfo attachInfo = mAttachInfo; 16939 if (region != null && attachInfo != null) { 16940 final int pflags = mPrivateFlags; 16941 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 16942 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 16943 // remove it from the transparent region. 16944 final int[] location = attachInfo.mTransparentLocation; 16945 getLocationInWindow(location); 16946 region.op(location[0], location[1], location[0] + mRight - mLeft, 16947 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 16948 } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) { 16949 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 16950 // exists, so we remove the background drawable's non-transparent 16951 // parts from this transparent region. 16952 applyDrawableToTransparentRegion(mBackground, region); 16953 } 16954 } 16955 return true; 16956 } 16957 16958 /** 16959 * Play a sound effect for this view. 16960 * 16961 * <p>The framework will play sound effects for some built in actions, such as 16962 * clicking, but you may wish to play these effects in your widget, 16963 * for instance, for internal navigation. 16964 * 16965 * <p>The sound effect will only be played if sound effects are enabled by the user, and 16966 * {@link #isSoundEffectsEnabled()} is true. 16967 * 16968 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 16969 */ 16970 public void playSoundEffect(int soundConstant) { 16971 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 16972 return; 16973 } 16974 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 16975 } 16976 16977 /** 16978 * BZZZTT!!1! 16979 * 16980 * <p>Provide haptic feedback to the user for this view. 16981 * 16982 * <p>The framework will provide haptic feedback for some built in actions, 16983 * such as long presses, but you may wish to provide feedback for your 16984 * own widget. 16985 * 16986 * <p>The feedback will only be performed if 16987 * {@link #isHapticFeedbackEnabled()} is true. 16988 * 16989 * @param feedbackConstant One of the constants defined in 16990 * {@link HapticFeedbackConstants} 16991 */ 16992 public boolean performHapticFeedback(int feedbackConstant) { 16993 return performHapticFeedback(feedbackConstant, 0); 16994 } 16995 16996 /** 16997 * BZZZTT!!1! 16998 * 16999 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 17000 * 17001 * @param feedbackConstant One of the constants defined in 17002 * {@link HapticFeedbackConstants} 17003 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 17004 */ 17005 public boolean performHapticFeedback(int feedbackConstant, int flags) { 17006 if (mAttachInfo == null) { 17007 return false; 17008 } 17009 //noinspection SimplifiableIfStatement 17010 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 17011 && !isHapticFeedbackEnabled()) { 17012 return false; 17013 } 17014 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 17015 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 17016 } 17017 17018 /** 17019 * Request that the visibility of the status bar or other screen/window 17020 * decorations be changed. 17021 * 17022 * <p>This method is used to put the over device UI into temporary modes 17023 * where the user's attention is focused more on the application content, 17024 * by dimming or hiding surrounding system affordances. This is typically 17025 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 17026 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 17027 * to be placed behind the action bar (and with these flags other system 17028 * affordances) so that smooth transitions between hiding and showing them 17029 * can be done. 17030 * 17031 * <p>Two representative examples of the use of system UI visibility is 17032 * implementing a content browsing application (like a magazine reader) 17033 * and a video playing application. 17034 * 17035 * <p>The first code shows a typical implementation of a View in a content 17036 * browsing application. In this implementation, the application goes 17037 * into a content-oriented mode by hiding the status bar and action bar, 17038 * and putting the navigation elements into lights out mode. The user can 17039 * then interact with content while in this mode. Such an application should 17040 * provide an easy way for the user to toggle out of the mode (such as to 17041 * check information in the status bar or access notifications). In the 17042 * implementation here, this is done simply by tapping on the content. 17043 * 17044 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 17045 * content} 17046 * 17047 * <p>This second code sample shows a typical implementation of a View 17048 * in a video playing application. In this situation, while the video is 17049 * playing the application would like to go into a complete full-screen mode, 17050 * to use as much of the display as possible for the video. When in this state 17051 * the user can not interact with the application; the system intercepts 17052 * touching on the screen to pop the UI out of full screen mode. See 17053 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 17054 * 17055 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 17056 * content} 17057 * 17058 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 17059 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 17060 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 17061 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 17062 * {@link #SYSTEM_UI_FLAG_TRANSPARENT_STATUS}, 17063 * and {@link #SYSTEM_UI_FLAG_TRANSPARENT_NAVIGATION}. 17064 */ 17065 public void setSystemUiVisibility(int visibility) { 17066 if (visibility != mSystemUiVisibility) { 17067 mSystemUiVisibility = visibility; 17068 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 17069 mParent.recomputeViewAttributes(this); 17070 } 17071 } 17072 } 17073 17074 /** 17075 * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested. 17076 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 17077 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 17078 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 17079 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 17080 * {@link #SYSTEM_UI_FLAG_TRANSPARENT_STATUS}, 17081 * and {@link #SYSTEM_UI_FLAG_TRANSPARENT_NAVIGATION}. 17082 */ 17083 public int getSystemUiVisibility() { 17084 return mSystemUiVisibility; 17085 } 17086 17087 /** 17088 * Returns the current system UI visibility that is currently set for 17089 * the entire window. This is the combination of the 17090 * {@link #setSystemUiVisibility(int)} values supplied by all of the 17091 * views in the window. 17092 */ 17093 public int getWindowSystemUiVisibility() { 17094 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 17095 } 17096 17097 /** 17098 * Override to find out when the window's requested system UI visibility 17099 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 17100 * This is different from the callbacks received through 17101 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 17102 * in that this is only telling you about the local request of the window, 17103 * not the actual values applied by the system. 17104 */ 17105 public void onWindowSystemUiVisibilityChanged(int visible) { 17106 } 17107 17108 /** 17109 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 17110 * the view hierarchy. 17111 */ 17112 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 17113 onWindowSystemUiVisibilityChanged(visible); 17114 } 17115 17116 /** 17117 * Set a listener to receive callbacks when the visibility of the system bar changes. 17118 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 17119 */ 17120 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 17121 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 17122 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 17123 mParent.recomputeViewAttributes(this); 17124 } 17125 } 17126 17127 /** 17128 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 17129 * the view hierarchy. 17130 */ 17131 public void dispatchSystemUiVisibilityChanged(int visibility) { 17132 ListenerInfo li = mListenerInfo; 17133 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 17134 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 17135 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 17136 } 17137 } 17138 17139 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 17140 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 17141 if (val != mSystemUiVisibility) { 17142 setSystemUiVisibility(val); 17143 return true; 17144 } 17145 return false; 17146 } 17147 17148 /** @hide */ 17149 public void setDisabledSystemUiVisibility(int flags) { 17150 if (mAttachInfo != null) { 17151 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 17152 mAttachInfo.mDisabledSystemUiVisibility = flags; 17153 if (mParent != null) { 17154 mParent.recomputeViewAttributes(this); 17155 } 17156 } 17157 } 17158 } 17159 17160 /** 17161 * Creates an image that the system displays during the drag and drop 17162 * operation. This is called a "drag shadow". The default implementation 17163 * for a DragShadowBuilder based on a View returns an image that has exactly the same 17164 * appearance as the given View. The default also positions the center of the drag shadow 17165 * directly under the touch point. If no View is provided (the constructor with no parameters 17166 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 17167 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 17168 * default is an invisible drag shadow. 17169 * <p> 17170 * You are not required to use the View you provide to the constructor as the basis of the 17171 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 17172 * anything you want as the drag shadow. 17173 * </p> 17174 * <p> 17175 * You pass a DragShadowBuilder object to the system when you start the drag. The system 17176 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 17177 * size and position of the drag shadow. It uses this data to construct a 17178 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 17179 * so that your application can draw the shadow image in the Canvas. 17180 * </p> 17181 * 17182 * <div class="special reference"> 17183 * <h3>Developer Guides</h3> 17184 * <p>For a guide to implementing drag and drop features, read the 17185 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 17186 * </div> 17187 */ 17188 public static class DragShadowBuilder { 17189 private final WeakReference<View> mView; 17190 17191 /** 17192 * Constructs a shadow image builder based on a View. By default, the resulting drag 17193 * shadow will have the same appearance and dimensions as the View, with the touch point 17194 * over the center of the View. 17195 * @param view A View. Any View in scope can be used. 17196 */ 17197 public DragShadowBuilder(View view) { 17198 mView = new WeakReference<View>(view); 17199 } 17200 17201 /** 17202 * Construct a shadow builder object with no associated View. This 17203 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 17204 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 17205 * to supply the drag shadow's dimensions and appearance without 17206 * reference to any View object. If they are not overridden, then the result is an 17207 * invisible drag shadow. 17208 */ 17209 public DragShadowBuilder() { 17210 mView = new WeakReference<View>(null); 17211 } 17212 17213 /** 17214 * Returns the View object that had been passed to the 17215 * {@link #View.DragShadowBuilder(View)} 17216 * constructor. If that View parameter was {@code null} or if the 17217 * {@link #View.DragShadowBuilder()} 17218 * constructor was used to instantiate the builder object, this method will return 17219 * null. 17220 * 17221 * @return The View object associate with this builder object. 17222 */ 17223 @SuppressWarnings({"JavadocReference"}) 17224 final public View getView() { 17225 return mView.get(); 17226 } 17227 17228 /** 17229 * Provides the metrics for the shadow image. These include the dimensions of 17230 * the shadow image, and the point within that shadow that should 17231 * be centered under the touch location while dragging. 17232 * <p> 17233 * The default implementation sets the dimensions of the shadow to be the 17234 * same as the dimensions of the View itself and centers the shadow under 17235 * the touch point. 17236 * </p> 17237 * 17238 * @param shadowSize A {@link android.graphics.Point} containing the width and height 17239 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 17240 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 17241 * image. 17242 * 17243 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 17244 * shadow image that should be underneath the touch point during the drag and drop 17245 * operation. Your application must set {@link android.graphics.Point#x} to the 17246 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 17247 */ 17248 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 17249 final View view = mView.get(); 17250 if (view != null) { 17251 shadowSize.set(view.getWidth(), view.getHeight()); 17252 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 17253 } else { 17254 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 17255 } 17256 } 17257 17258 /** 17259 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 17260 * based on the dimensions it received from the 17261 * {@link #onProvideShadowMetrics(Point, Point)} callback. 17262 * 17263 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 17264 */ 17265 public void onDrawShadow(Canvas canvas) { 17266 final View view = mView.get(); 17267 if (view != null) { 17268 view.draw(canvas); 17269 } else { 17270 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 17271 } 17272 } 17273 } 17274 17275 /** 17276 * Starts a drag and drop operation. When your application calls this method, it passes a 17277 * {@link android.view.View.DragShadowBuilder} object to the system. The 17278 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 17279 * to get metrics for the drag shadow, and then calls the object's 17280 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 17281 * <p> 17282 * Once the system has the drag shadow, it begins the drag and drop operation by sending 17283 * drag events to all the View objects in your application that are currently visible. It does 17284 * this either by calling the View object's drag listener (an implementation of 17285 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 17286 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 17287 * Both are passed a {@link android.view.DragEvent} object that has a 17288 * {@link android.view.DragEvent#getAction()} value of 17289 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 17290 * </p> 17291 * <p> 17292 * Your application can invoke startDrag() on any attached View object. The View object does not 17293 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 17294 * be related to the View the user selected for dragging. 17295 * </p> 17296 * @param data A {@link android.content.ClipData} object pointing to the data to be 17297 * transferred by the drag and drop operation. 17298 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 17299 * drag shadow. 17300 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 17301 * drop operation. This Object is put into every DragEvent object sent by the system during the 17302 * current drag. 17303 * <p> 17304 * myLocalState is a lightweight mechanism for the sending information from the dragged View 17305 * to the target Views. For example, it can contain flags that differentiate between a 17306 * a copy operation and a move operation. 17307 * </p> 17308 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 17309 * so the parameter should be set to 0. 17310 * @return {@code true} if the method completes successfully, or 17311 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 17312 * do a drag, and so no drag operation is in progress. 17313 */ 17314 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 17315 Object myLocalState, int flags) { 17316 if (ViewDebug.DEBUG_DRAG) { 17317 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 17318 } 17319 boolean okay = false; 17320 17321 Point shadowSize = new Point(); 17322 Point shadowTouchPoint = new Point(); 17323 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 17324 17325 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 17326 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 17327 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 17328 } 17329 17330 if (ViewDebug.DEBUG_DRAG) { 17331 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 17332 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 17333 } 17334 Surface surface = new Surface(); 17335 try { 17336 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 17337 flags, shadowSize.x, shadowSize.y, surface); 17338 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 17339 + " surface=" + surface); 17340 if (token != null) { 17341 Canvas canvas = surface.lockCanvas(null); 17342 try { 17343 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 17344 shadowBuilder.onDrawShadow(canvas); 17345 } finally { 17346 surface.unlockCanvasAndPost(canvas); 17347 } 17348 17349 final ViewRootImpl root = getViewRootImpl(); 17350 17351 // Cache the local state object for delivery with DragEvents 17352 root.setLocalDragState(myLocalState); 17353 17354 // repurpose 'shadowSize' for the last touch point 17355 root.getLastTouchPoint(shadowSize); 17356 17357 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 17358 shadowSize.x, shadowSize.y, 17359 shadowTouchPoint.x, shadowTouchPoint.y, data); 17360 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 17361 17362 // Off and running! Release our local surface instance; the drag 17363 // shadow surface is now managed by the system process. 17364 surface.release(); 17365 } 17366 } catch (Exception e) { 17367 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 17368 surface.destroy(); 17369 } 17370 17371 return okay; 17372 } 17373 17374 /** 17375 * Handles drag events sent by the system following a call to 17376 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 17377 *<p> 17378 * When the system calls this method, it passes a 17379 * {@link android.view.DragEvent} object. A call to 17380 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 17381 * in DragEvent. The method uses these to determine what is happening in the drag and drop 17382 * operation. 17383 * @param event The {@link android.view.DragEvent} sent by the system. 17384 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 17385 * in DragEvent, indicating the type of drag event represented by this object. 17386 * @return {@code true} if the method was successful, otherwise {@code false}. 17387 * <p> 17388 * The method should return {@code true} in response to an action type of 17389 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 17390 * operation. 17391 * </p> 17392 * <p> 17393 * The method should also return {@code true} in response to an action type of 17394 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 17395 * {@code false} if it didn't. 17396 * </p> 17397 */ 17398 public boolean onDragEvent(DragEvent event) { 17399 return false; 17400 } 17401 17402 /** 17403 * Detects if this View is enabled and has a drag event listener. 17404 * If both are true, then it calls the drag event listener with the 17405 * {@link android.view.DragEvent} it received. If the drag event listener returns 17406 * {@code true}, then dispatchDragEvent() returns {@code true}. 17407 * <p> 17408 * For all other cases, the method calls the 17409 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 17410 * method and returns its result. 17411 * </p> 17412 * <p> 17413 * This ensures that a drag event is always consumed, even if the View does not have a drag 17414 * event listener. However, if the View has a listener and the listener returns true, then 17415 * onDragEvent() is not called. 17416 * </p> 17417 */ 17418 public boolean dispatchDragEvent(DragEvent event) { 17419 ListenerInfo li = mListenerInfo; 17420 //noinspection SimplifiableIfStatement 17421 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 17422 && li.mOnDragListener.onDrag(this, event)) { 17423 return true; 17424 } 17425 return onDragEvent(event); 17426 } 17427 17428 boolean canAcceptDrag() { 17429 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 17430 } 17431 17432 /** 17433 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 17434 * it is ever exposed at all. 17435 * @hide 17436 */ 17437 public void onCloseSystemDialogs(String reason) { 17438 } 17439 17440 /** 17441 * Given a Drawable whose bounds have been set to draw into this view, 17442 * update a Region being computed for 17443 * {@link #gatherTransparentRegion(android.graphics.Region)} so 17444 * that any non-transparent parts of the Drawable are removed from the 17445 * given transparent region. 17446 * 17447 * @param dr The Drawable whose transparency is to be applied to the region. 17448 * @param region A Region holding the current transparency information, 17449 * where any parts of the region that are set are considered to be 17450 * transparent. On return, this region will be modified to have the 17451 * transparency information reduced by the corresponding parts of the 17452 * Drawable that are not transparent. 17453 * {@hide} 17454 */ 17455 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 17456 if (DBG) { 17457 Log.i("View", "Getting transparent region for: " + this); 17458 } 17459 final Region r = dr.getTransparentRegion(); 17460 final Rect db = dr.getBounds(); 17461 final AttachInfo attachInfo = mAttachInfo; 17462 if (r != null && attachInfo != null) { 17463 final int w = getRight()-getLeft(); 17464 final int h = getBottom()-getTop(); 17465 if (db.left > 0) { 17466 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 17467 r.op(0, 0, db.left, h, Region.Op.UNION); 17468 } 17469 if (db.right < w) { 17470 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 17471 r.op(db.right, 0, w, h, Region.Op.UNION); 17472 } 17473 if (db.top > 0) { 17474 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 17475 r.op(0, 0, w, db.top, Region.Op.UNION); 17476 } 17477 if (db.bottom < h) { 17478 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 17479 r.op(0, db.bottom, w, h, Region.Op.UNION); 17480 } 17481 final int[] location = attachInfo.mTransparentLocation; 17482 getLocationInWindow(location); 17483 r.translate(location[0], location[1]); 17484 region.op(r, Region.Op.INTERSECT); 17485 } else { 17486 region.op(db, Region.Op.DIFFERENCE); 17487 } 17488 } 17489 17490 private void checkForLongClick(int delayOffset) { 17491 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 17492 mHasPerformedLongPress = false; 17493 17494 if (mPendingCheckForLongPress == null) { 17495 mPendingCheckForLongPress = new CheckForLongPress(); 17496 } 17497 mPendingCheckForLongPress.rememberWindowAttachCount(); 17498 postDelayed(mPendingCheckForLongPress, 17499 ViewConfiguration.getLongPressTimeout() - delayOffset); 17500 } 17501 } 17502 17503 /** 17504 * Inflate a view from an XML resource. This convenience method wraps the {@link 17505 * LayoutInflater} class, which provides a full range of options for view inflation. 17506 * 17507 * @param context The Context object for your activity or application. 17508 * @param resource The resource ID to inflate 17509 * @param root A view group that will be the parent. Used to properly inflate the 17510 * layout_* parameters. 17511 * @see LayoutInflater 17512 */ 17513 public static View inflate(Context context, int resource, ViewGroup root) { 17514 LayoutInflater factory = LayoutInflater.from(context); 17515 return factory.inflate(resource, root); 17516 } 17517 17518 /** 17519 * Scroll the view with standard behavior for scrolling beyond the normal 17520 * content boundaries. Views that call this method should override 17521 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 17522 * results of an over-scroll operation. 17523 * 17524 * Views can use this method to handle any touch or fling-based scrolling. 17525 * 17526 * @param deltaX Change in X in pixels 17527 * @param deltaY Change in Y in pixels 17528 * @param scrollX Current X scroll value in pixels before applying deltaX 17529 * @param scrollY Current Y scroll value in pixels before applying deltaY 17530 * @param scrollRangeX Maximum content scroll range along the X axis 17531 * @param scrollRangeY Maximum content scroll range along the Y axis 17532 * @param maxOverScrollX Number of pixels to overscroll by in either direction 17533 * along the X axis. 17534 * @param maxOverScrollY Number of pixels to overscroll by in either direction 17535 * along the Y axis. 17536 * @param isTouchEvent true if this scroll operation is the result of a touch event. 17537 * @return true if scrolling was clamped to an over-scroll boundary along either 17538 * axis, false otherwise. 17539 */ 17540 @SuppressWarnings({"UnusedParameters"}) 17541 protected boolean overScrollBy(int deltaX, int deltaY, 17542 int scrollX, int scrollY, 17543 int scrollRangeX, int scrollRangeY, 17544 int maxOverScrollX, int maxOverScrollY, 17545 boolean isTouchEvent) { 17546 final int overScrollMode = mOverScrollMode; 17547 final boolean canScrollHorizontal = 17548 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 17549 final boolean canScrollVertical = 17550 computeVerticalScrollRange() > computeVerticalScrollExtent(); 17551 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 17552 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 17553 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 17554 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 17555 17556 int newScrollX = scrollX + deltaX; 17557 if (!overScrollHorizontal) { 17558 maxOverScrollX = 0; 17559 } 17560 17561 int newScrollY = scrollY + deltaY; 17562 if (!overScrollVertical) { 17563 maxOverScrollY = 0; 17564 } 17565 17566 // Clamp values if at the limits and record 17567 final int left = -maxOverScrollX; 17568 final int right = maxOverScrollX + scrollRangeX; 17569 final int top = -maxOverScrollY; 17570 final int bottom = maxOverScrollY + scrollRangeY; 17571 17572 boolean clampedX = false; 17573 if (newScrollX > right) { 17574 newScrollX = right; 17575 clampedX = true; 17576 } else if (newScrollX < left) { 17577 newScrollX = left; 17578 clampedX = true; 17579 } 17580 17581 boolean clampedY = false; 17582 if (newScrollY > bottom) { 17583 newScrollY = bottom; 17584 clampedY = true; 17585 } else if (newScrollY < top) { 17586 newScrollY = top; 17587 clampedY = true; 17588 } 17589 17590 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 17591 17592 return clampedX || clampedY; 17593 } 17594 17595 /** 17596 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 17597 * respond to the results of an over-scroll operation. 17598 * 17599 * @param scrollX New X scroll value in pixels 17600 * @param scrollY New Y scroll value in pixels 17601 * @param clampedX True if scrollX was clamped to an over-scroll boundary 17602 * @param clampedY True if scrollY was clamped to an over-scroll boundary 17603 */ 17604 protected void onOverScrolled(int scrollX, int scrollY, 17605 boolean clampedX, boolean clampedY) { 17606 // Intentionally empty. 17607 } 17608 17609 /** 17610 * Returns the over-scroll mode for this view. The result will be 17611 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 17612 * (allow over-scrolling only if the view content is larger than the container), 17613 * or {@link #OVER_SCROLL_NEVER}. 17614 * 17615 * @return This view's over-scroll mode. 17616 */ 17617 public int getOverScrollMode() { 17618 return mOverScrollMode; 17619 } 17620 17621 /** 17622 * Set the over-scroll mode for this view. Valid over-scroll modes are 17623 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 17624 * (allow over-scrolling only if the view content is larger than the container), 17625 * or {@link #OVER_SCROLL_NEVER}. 17626 * 17627 * Setting the over-scroll mode of a view will have an effect only if the 17628 * view is capable of scrolling. 17629 * 17630 * @param overScrollMode The new over-scroll mode for this view. 17631 */ 17632 public void setOverScrollMode(int overScrollMode) { 17633 if (overScrollMode != OVER_SCROLL_ALWAYS && 17634 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 17635 overScrollMode != OVER_SCROLL_NEVER) { 17636 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 17637 } 17638 mOverScrollMode = overScrollMode; 17639 } 17640 17641 /** 17642 * Gets a scale factor that determines the distance the view should scroll 17643 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 17644 * @return The vertical scroll scale factor. 17645 * @hide 17646 */ 17647 protected float getVerticalScrollFactor() { 17648 if (mVerticalScrollFactor == 0) { 17649 TypedValue outValue = new TypedValue(); 17650 if (!mContext.getTheme().resolveAttribute( 17651 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 17652 throw new IllegalStateException( 17653 "Expected theme to define listPreferredItemHeight."); 17654 } 17655 mVerticalScrollFactor = outValue.getDimension( 17656 mContext.getResources().getDisplayMetrics()); 17657 } 17658 return mVerticalScrollFactor; 17659 } 17660 17661 /** 17662 * Gets a scale factor that determines the distance the view should scroll 17663 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 17664 * @return The horizontal scroll scale factor. 17665 * @hide 17666 */ 17667 protected float getHorizontalScrollFactor() { 17668 // TODO: Should use something else. 17669 return getVerticalScrollFactor(); 17670 } 17671 17672 /** 17673 * Return the value specifying the text direction or policy that was set with 17674 * {@link #setTextDirection(int)}. 17675 * 17676 * @return the defined text direction. It can be one of: 17677 * 17678 * {@link #TEXT_DIRECTION_INHERIT}, 17679 * {@link #TEXT_DIRECTION_FIRST_STRONG} 17680 * {@link #TEXT_DIRECTION_ANY_RTL}, 17681 * {@link #TEXT_DIRECTION_LTR}, 17682 * {@link #TEXT_DIRECTION_RTL}, 17683 * {@link #TEXT_DIRECTION_LOCALE} 17684 * 17685 * @attr ref android.R.styleable#View_textDirection 17686 * 17687 * @hide 17688 */ 17689 @ViewDebug.ExportedProperty(category = "text", mapping = { 17690 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 17691 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 17692 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 17693 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 17694 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 17695 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 17696 }) 17697 public int getRawTextDirection() { 17698 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 17699 } 17700 17701 /** 17702 * Set the text direction. 17703 * 17704 * @param textDirection the direction to set. Should be one of: 17705 * 17706 * {@link #TEXT_DIRECTION_INHERIT}, 17707 * {@link #TEXT_DIRECTION_FIRST_STRONG} 17708 * {@link #TEXT_DIRECTION_ANY_RTL}, 17709 * {@link #TEXT_DIRECTION_LTR}, 17710 * {@link #TEXT_DIRECTION_RTL}, 17711 * {@link #TEXT_DIRECTION_LOCALE} 17712 * 17713 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution 17714 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will 17715 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 17716 * 17717 * @attr ref android.R.styleable#View_textDirection 17718 */ 17719 public void setTextDirection(int textDirection) { 17720 if (getRawTextDirection() != textDirection) { 17721 // Reset the current text direction and the resolved one 17722 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 17723 resetResolvedTextDirection(); 17724 // Set the new text direction 17725 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 17726 // Do resolution 17727 resolveTextDirection(); 17728 // Notify change 17729 onRtlPropertiesChanged(getLayoutDirection()); 17730 // Refresh 17731 requestLayout(); 17732 invalidate(true); 17733 } 17734 } 17735 17736 /** 17737 * Return the resolved text direction. 17738 * 17739 * @return the resolved text direction. Returns one of: 17740 * 17741 * {@link #TEXT_DIRECTION_FIRST_STRONG} 17742 * {@link #TEXT_DIRECTION_ANY_RTL}, 17743 * {@link #TEXT_DIRECTION_LTR}, 17744 * {@link #TEXT_DIRECTION_RTL}, 17745 * {@link #TEXT_DIRECTION_LOCALE} 17746 * 17747 * @attr ref android.R.styleable#View_textDirection 17748 */ 17749 @ViewDebug.ExportedProperty(category = "text", mapping = { 17750 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 17751 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 17752 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 17753 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 17754 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 17755 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 17756 }) 17757 public int getTextDirection() { 17758 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 17759 } 17760 17761 /** 17762 * Resolve the text direction. 17763 * 17764 * @return true if resolution has been done, false otherwise. 17765 * 17766 * @hide 17767 */ 17768 public boolean resolveTextDirection() { 17769 // Reset any previous text direction resolution 17770 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 17771 17772 if (hasRtlSupport()) { 17773 // Set resolved text direction flag depending on text direction flag 17774 final int textDirection = getRawTextDirection(); 17775 switch(textDirection) { 17776 case TEXT_DIRECTION_INHERIT: 17777 if (!canResolveTextDirection()) { 17778 // We cannot do the resolution if there is no parent, so use the default one 17779 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 17780 // Resolution will need to happen again later 17781 return false; 17782 } 17783 17784 // Parent has not yet resolved, so we still return the default 17785 try { 17786 if (!mParent.isTextDirectionResolved()) { 17787 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 17788 // Resolution will need to happen again later 17789 return false; 17790 } 17791 } catch (AbstractMethodError e) { 17792 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 17793 " does not fully implement ViewParent", e); 17794 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED | 17795 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 17796 return true; 17797 } 17798 17799 // Set current resolved direction to the same value as the parent's one 17800 int parentResolvedDirection; 17801 try { 17802 parentResolvedDirection = mParent.getTextDirection(); 17803 } catch (AbstractMethodError e) { 17804 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 17805 " does not fully implement ViewParent", e); 17806 parentResolvedDirection = TEXT_DIRECTION_LTR; 17807 } 17808 switch (parentResolvedDirection) { 17809 case TEXT_DIRECTION_FIRST_STRONG: 17810 case TEXT_DIRECTION_ANY_RTL: 17811 case TEXT_DIRECTION_LTR: 17812 case TEXT_DIRECTION_RTL: 17813 case TEXT_DIRECTION_LOCALE: 17814 mPrivateFlags2 |= 17815 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 17816 break; 17817 default: 17818 // Default resolved direction is "first strong" heuristic 17819 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 17820 } 17821 break; 17822 case TEXT_DIRECTION_FIRST_STRONG: 17823 case TEXT_DIRECTION_ANY_RTL: 17824 case TEXT_DIRECTION_LTR: 17825 case TEXT_DIRECTION_RTL: 17826 case TEXT_DIRECTION_LOCALE: 17827 // Resolved direction is the same as text direction 17828 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 17829 break; 17830 default: 17831 // Default resolved direction is "first strong" heuristic 17832 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 17833 } 17834 } else { 17835 // Default resolved direction is "first strong" heuristic 17836 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 17837 } 17838 17839 // Set to resolved 17840 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 17841 return true; 17842 } 17843 17844 /** 17845 * Check if text direction resolution can be done. 17846 * 17847 * @return true if text direction resolution can be done otherwise return false. 17848 */ 17849 public boolean canResolveTextDirection() { 17850 switch (getRawTextDirection()) { 17851 case TEXT_DIRECTION_INHERIT: 17852 if (mParent != null) { 17853 try { 17854 return mParent.canResolveTextDirection(); 17855 } catch (AbstractMethodError e) { 17856 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 17857 " does not fully implement ViewParent", e); 17858 } 17859 } 17860 return false; 17861 17862 default: 17863 return true; 17864 } 17865 } 17866 17867 /** 17868 * Reset resolved text direction. Text direction will be resolved during a call to 17869 * {@link #onMeasure(int, int)}. 17870 * 17871 * @hide 17872 */ 17873 public void resetResolvedTextDirection() { 17874 // Reset any previous text direction resolution 17875 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 17876 // Set to default value 17877 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 17878 } 17879 17880 /** 17881 * @return true if text direction is inherited. 17882 * 17883 * @hide 17884 */ 17885 public boolean isTextDirectionInherited() { 17886 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 17887 } 17888 17889 /** 17890 * @return true if text direction is resolved. 17891 */ 17892 public boolean isTextDirectionResolved() { 17893 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED; 17894 } 17895 17896 /** 17897 * Return the value specifying the text alignment or policy that was set with 17898 * {@link #setTextAlignment(int)}. 17899 * 17900 * @return the defined text alignment. It can be one of: 17901 * 17902 * {@link #TEXT_ALIGNMENT_INHERIT}, 17903 * {@link #TEXT_ALIGNMENT_GRAVITY}, 17904 * {@link #TEXT_ALIGNMENT_CENTER}, 17905 * {@link #TEXT_ALIGNMENT_TEXT_START}, 17906 * {@link #TEXT_ALIGNMENT_TEXT_END}, 17907 * {@link #TEXT_ALIGNMENT_VIEW_START}, 17908 * {@link #TEXT_ALIGNMENT_VIEW_END} 17909 * 17910 * @attr ref android.R.styleable#View_textAlignment 17911 * 17912 * @hide 17913 */ 17914 @ViewDebug.ExportedProperty(category = "text", mapping = { 17915 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 17916 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 17917 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 17918 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 17919 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 17920 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 17921 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 17922 }) 17923 @TextAlignment 17924 public int getRawTextAlignment() { 17925 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 17926 } 17927 17928 /** 17929 * Set the text alignment. 17930 * 17931 * @param textAlignment The text alignment to set. Should be one of 17932 * 17933 * {@link #TEXT_ALIGNMENT_INHERIT}, 17934 * {@link #TEXT_ALIGNMENT_GRAVITY}, 17935 * {@link #TEXT_ALIGNMENT_CENTER}, 17936 * {@link #TEXT_ALIGNMENT_TEXT_START}, 17937 * {@link #TEXT_ALIGNMENT_TEXT_END}, 17938 * {@link #TEXT_ALIGNMENT_VIEW_START}, 17939 * {@link #TEXT_ALIGNMENT_VIEW_END} 17940 * 17941 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution 17942 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 17943 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}. 17944 * 17945 * @attr ref android.R.styleable#View_textAlignment 17946 */ 17947 public void setTextAlignment(@TextAlignment int textAlignment) { 17948 if (textAlignment != getRawTextAlignment()) { 17949 // Reset the current and resolved text alignment 17950 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 17951 resetResolvedTextAlignment(); 17952 // Set the new text alignment 17953 mPrivateFlags2 |= 17954 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 17955 // Do resolution 17956 resolveTextAlignment(); 17957 // Notify change 17958 onRtlPropertiesChanged(getLayoutDirection()); 17959 // Refresh 17960 requestLayout(); 17961 invalidate(true); 17962 } 17963 } 17964 17965 /** 17966 * Return the resolved text alignment. 17967 * 17968 * @return the resolved text alignment. Returns one of: 17969 * 17970 * {@link #TEXT_ALIGNMENT_GRAVITY}, 17971 * {@link #TEXT_ALIGNMENT_CENTER}, 17972 * {@link #TEXT_ALIGNMENT_TEXT_START}, 17973 * {@link #TEXT_ALIGNMENT_TEXT_END}, 17974 * {@link #TEXT_ALIGNMENT_VIEW_START}, 17975 * {@link #TEXT_ALIGNMENT_VIEW_END} 17976 * 17977 * @attr ref android.R.styleable#View_textAlignment 17978 */ 17979 @ViewDebug.ExportedProperty(category = "text", mapping = { 17980 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 17981 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 17982 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 17983 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 17984 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 17985 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 17986 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 17987 }) 17988 @TextAlignment 17989 public int getTextAlignment() { 17990 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> 17991 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 17992 } 17993 17994 /** 17995 * Resolve the text alignment. 17996 * 17997 * @return true if resolution has been done, false otherwise. 17998 * 17999 * @hide 18000 */ 18001 public boolean resolveTextAlignment() { 18002 // Reset any previous text alignment resolution 18003 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 18004 18005 if (hasRtlSupport()) { 18006 // Set resolved text alignment flag depending on text alignment flag 18007 final int textAlignment = getRawTextAlignment(); 18008 switch (textAlignment) { 18009 case TEXT_ALIGNMENT_INHERIT: 18010 // Check if we can resolve the text alignment 18011 if (!canResolveTextAlignment()) { 18012 // We cannot do the resolution if there is no parent so use the default 18013 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18014 // Resolution will need to happen again later 18015 return false; 18016 } 18017 18018 // Parent has not yet resolved, so we still return the default 18019 try { 18020 if (!mParent.isTextAlignmentResolved()) { 18021 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18022 // Resolution will need to happen again later 18023 return false; 18024 } 18025 } catch (AbstractMethodError e) { 18026 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18027 " does not fully implement ViewParent", e); 18028 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED | 18029 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18030 return true; 18031 } 18032 18033 int parentResolvedTextAlignment; 18034 try { 18035 parentResolvedTextAlignment = mParent.getTextAlignment(); 18036 } catch (AbstractMethodError e) { 18037 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18038 " does not fully implement ViewParent", e); 18039 parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY; 18040 } 18041 switch (parentResolvedTextAlignment) { 18042 case TEXT_ALIGNMENT_GRAVITY: 18043 case TEXT_ALIGNMENT_TEXT_START: 18044 case TEXT_ALIGNMENT_TEXT_END: 18045 case TEXT_ALIGNMENT_CENTER: 18046 case TEXT_ALIGNMENT_VIEW_START: 18047 case TEXT_ALIGNMENT_VIEW_END: 18048 // Resolved text alignment is the same as the parent resolved 18049 // text alignment 18050 mPrivateFlags2 |= 18051 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 18052 break; 18053 default: 18054 // Use default resolved text alignment 18055 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18056 } 18057 break; 18058 case TEXT_ALIGNMENT_GRAVITY: 18059 case TEXT_ALIGNMENT_TEXT_START: 18060 case TEXT_ALIGNMENT_TEXT_END: 18061 case TEXT_ALIGNMENT_CENTER: 18062 case TEXT_ALIGNMENT_VIEW_START: 18063 case TEXT_ALIGNMENT_VIEW_END: 18064 // Resolved text alignment is the same as text alignment 18065 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 18066 break; 18067 default: 18068 // Use default resolved text alignment 18069 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18070 } 18071 } else { 18072 // Use default resolved text alignment 18073 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18074 } 18075 18076 // Set the resolved 18077 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 18078 return true; 18079 } 18080 18081 /** 18082 * Check if text alignment resolution can be done. 18083 * 18084 * @return true if text alignment resolution can be done otherwise return false. 18085 */ 18086 public boolean canResolveTextAlignment() { 18087 switch (getRawTextAlignment()) { 18088 case TEXT_DIRECTION_INHERIT: 18089 if (mParent != null) { 18090 try { 18091 return mParent.canResolveTextAlignment(); 18092 } catch (AbstractMethodError e) { 18093 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18094 " does not fully implement ViewParent", e); 18095 } 18096 } 18097 return false; 18098 18099 default: 18100 return true; 18101 } 18102 } 18103 18104 /** 18105 * Reset resolved text alignment. Text alignment will be resolved during a call to 18106 * {@link #onMeasure(int, int)}. 18107 * 18108 * @hide 18109 */ 18110 public void resetResolvedTextAlignment() { 18111 // Reset any previous text alignment resolution 18112 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 18113 // Set to default 18114 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18115 } 18116 18117 /** 18118 * @return true if text alignment is inherited. 18119 * 18120 * @hide 18121 */ 18122 public boolean isTextAlignmentInherited() { 18123 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 18124 } 18125 18126 /** 18127 * @return true if text alignment is resolved. 18128 */ 18129 public boolean isTextAlignmentResolved() { 18130 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED; 18131 } 18132 18133 /** 18134 * Generate a value suitable for use in {@link #setId(int)}. 18135 * This value will not collide with ID values generated at build time by aapt for R.id. 18136 * 18137 * @return a generated ID value 18138 */ 18139 public static int generateViewId() { 18140 for (;;) { 18141 final int result = sNextGeneratedId.get(); 18142 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 18143 int newValue = result + 1; 18144 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 18145 if (sNextGeneratedId.compareAndSet(result, newValue)) { 18146 return result; 18147 } 18148 } 18149 } 18150 18151 // 18152 // Properties 18153 // 18154 /** 18155 * A Property wrapper around the <code>alpha</code> functionality handled by the 18156 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 18157 */ 18158 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 18159 @Override 18160 public void setValue(View object, float value) { 18161 object.setAlpha(value); 18162 } 18163 18164 @Override 18165 public Float get(View object) { 18166 return object.getAlpha(); 18167 } 18168 }; 18169 18170 /** 18171 * A Property wrapper around the <code>translationX</code> functionality handled by the 18172 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 18173 */ 18174 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 18175 @Override 18176 public void setValue(View object, float value) { 18177 object.setTranslationX(value); 18178 } 18179 18180 @Override 18181 public Float get(View object) { 18182 return object.getTranslationX(); 18183 } 18184 }; 18185 18186 /** 18187 * A Property wrapper around the <code>translationY</code> functionality handled by the 18188 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 18189 */ 18190 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 18191 @Override 18192 public void setValue(View object, float value) { 18193 object.setTranslationY(value); 18194 } 18195 18196 @Override 18197 public Float get(View object) { 18198 return object.getTranslationY(); 18199 } 18200 }; 18201 18202 /** 18203 * A Property wrapper around the <code>x</code> functionality handled by the 18204 * {@link View#setX(float)} and {@link View#getX()} methods. 18205 */ 18206 public static final Property<View, Float> X = new FloatProperty<View>("x") { 18207 @Override 18208 public void setValue(View object, float value) { 18209 object.setX(value); 18210 } 18211 18212 @Override 18213 public Float get(View object) { 18214 return object.getX(); 18215 } 18216 }; 18217 18218 /** 18219 * A Property wrapper around the <code>y</code> functionality handled by the 18220 * {@link View#setY(float)} and {@link View#getY()} methods. 18221 */ 18222 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 18223 @Override 18224 public void setValue(View object, float value) { 18225 object.setY(value); 18226 } 18227 18228 @Override 18229 public Float get(View object) { 18230 return object.getY(); 18231 } 18232 }; 18233 18234 /** 18235 * A Property wrapper around the <code>rotation</code> functionality handled by the 18236 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 18237 */ 18238 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 18239 @Override 18240 public void setValue(View object, float value) { 18241 object.setRotation(value); 18242 } 18243 18244 @Override 18245 public Float get(View object) { 18246 return object.getRotation(); 18247 } 18248 }; 18249 18250 /** 18251 * A Property wrapper around the <code>rotationX</code> functionality handled by the 18252 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 18253 */ 18254 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 18255 @Override 18256 public void setValue(View object, float value) { 18257 object.setRotationX(value); 18258 } 18259 18260 @Override 18261 public Float get(View object) { 18262 return object.getRotationX(); 18263 } 18264 }; 18265 18266 /** 18267 * A Property wrapper around the <code>rotationY</code> functionality handled by the 18268 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 18269 */ 18270 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 18271 @Override 18272 public void setValue(View object, float value) { 18273 object.setRotationY(value); 18274 } 18275 18276 @Override 18277 public Float get(View object) { 18278 return object.getRotationY(); 18279 } 18280 }; 18281 18282 /** 18283 * A Property wrapper around the <code>scaleX</code> functionality handled by the 18284 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 18285 */ 18286 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 18287 @Override 18288 public void setValue(View object, float value) { 18289 object.setScaleX(value); 18290 } 18291 18292 @Override 18293 public Float get(View object) { 18294 return object.getScaleX(); 18295 } 18296 }; 18297 18298 /** 18299 * A Property wrapper around the <code>scaleY</code> functionality handled by the 18300 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 18301 */ 18302 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 18303 @Override 18304 public void setValue(View object, float value) { 18305 object.setScaleY(value); 18306 } 18307 18308 @Override 18309 public Float get(View object) { 18310 return object.getScaleY(); 18311 } 18312 }; 18313 18314 /** 18315 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 18316 * Each MeasureSpec represents a requirement for either the width or the height. 18317 * A MeasureSpec is comprised of a size and a mode. There are three possible 18318 * modes: 18319 * <dl> 18320 * <dt>UNSPECIFIED</dt> 18321 * <dd> 18322 * The parent has not imposed any constraint on the child. It can be whatever size 18323 * it wants. 18324 * </dd> 18325 * 18326 * <dt>EXACTLY</dt> 18327 * <dd> 18328 * The parent has determined an exact size for the child. The child is going to be 18329 * given those bounds regardless of how big it wants to be. 18330 * </dd> 18331 * 18332 * <dt>AT_MOST</dt> 18333 * <dd> 18334 * The child can be as large as it wants up to the specified size. 18335 * </dd> 18336 * </dl> 18337 * 18338 * MeasureSpecs are implemented as ints to reduce object allocation. This class 18339 * is provided to pack and unpack the <size, mode> tuple into the int. 18340 */ 18341 public static class MeasureSpec { 18342 private static final int MODE_SHIFT = 30; 18343 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 18344 18345 /** 18346 * Measure specification mode: The parent has not imposed any constraint 18347 * on the child. It can be whatever size it wants. 18348 */ 18349 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 18350 18351 /** 18352 * Measure specification mode: The parent has determined an exact size 18353 * for the child. The child is going to be given those bounds regardless 18354 * of how big it wants to be. 18355 */ 18356 public static final int EXACTLY = 1 << MODE_SHIFT; 18357 18358 /** 18359 * Measure specification mode: The child can be as large as it wants up 18360 * to the specified size. 18361 */ 18362 public static final int AT_MOST = 2 << MODE_SHIFT; 18363 18364 /** 18365 * Creates a measure specification based on the supplied size and mode. 18366 * 18367 * The mode must always be one of the following: 18368 * <ul> 18369 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 18370 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 18371 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 18372 * </ul> 18373 * 18374 * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's 18375 * implementation was such that the order of arguments did not matter 18376 * and overflow in either value could impact the resulting MeasureSpec. 18377 * {@link android.widget.RelativeLayout} was affected by this bug. 18378 * Apps targeting API levels greater than 17 will get the fixed, more strict 18379 * behavior.</p> 18380 * 18381 * @param size the size of the measure specification 18382 * @param mode the mode of the measure specification 18383 * @return the measure specification based on size and mode 18384 */ 18385 public static int makeMeasureSpec(int size, int mode) { 18386 if (sUseBrokenMakeMeasureSpec) { 18387 return size + mode; 18388 } else { 18389 return (size & ~MODE_MASK) | (mode & MODE_MASK); 18390 } 18391 } 18392 18393 /** 18394 * Extracts the mode from the supplied measure specification. 18395 * 18396 * @param measureSpec the measure specification to extract the mode from 18397 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 18398 * {@link android.view.View.MeasureSpec#AT_MOST} or 18399 * {@link android.view.View.MeasureSpec#EXACTLY} 18400 */ 18401 public static int getMode(int measureSpec) { 18402 return (measureSpec & MODE_MASK); 18403 } 18404 18405 /** 18406 * Extracts the size from the supplied measure specification. 18407 * 18408 * @param measureSpec the measure specification to extract the size from 18409 * @return the size in pixels defined in the supplied measure specification 18410 */ 18411 public static int getSize(int measureSpec) { 18412 return (measureSpec & ~MODE_MASK); 18413 } 18414 18415 static int adjust(int measureSpec, int delta) { 18416 return makeMeasureSpec(getSize(measureSpec + delta), getMode(measureSpec)); 18417 } 18418 18419 /** 18420 * Returns a String representation of the specified measure 18421 * specification. 18422 * 18423 * @param measureSpec the measure specification to convert to a String 18424 * @return a String with the following format: "MeasureSpec: MODE SIZE" 18425 */ 18426 public static String toString(int measureSpec) { 18427 int mode = getMode(measureSpec); 18428 int size = getSize(measureSpec); 18429 18430 StringBuilder sb = new StringBuilder("MeasureSpec: "); 18431 18432 if (mode == UNSPECIFIED) 18433 sb.append("UNSPECIFIED "); 18434 else if (mode == EXACTLY) 18435 sb.append("EXACTLY "); 18436 else if (mode == AT_MOST) 18437 sb.append("AT_MOST "); 18438 else 18439 sb.append(mode).append(" "); 18440 18441 sb.append(size); 18442 return sb.toString(); 18443 } 18444 } 18445 18446 class CheckForLongPress implements Runnable { 18447 18448 private int mOriginalWindowAttachCount; 18449 18450 public void run() { 18451 if (isPressed() && (mParent != null) 18452 && mOriginalWindowAttachCount == mWindowAttachCount) { 18453 if (performLongClick()) { 18454 mHasPerformedLongPress = true; 18455 } 18456 } 18457 } 18458 18459 public void rememberWindowAttachCount() { 18460 mOriginalWindowAttachCount = mWindowAttachCount; 18461 } 18462 } 18463 18464 private final class CheckForTap implements Runnable { 18465 public void run() { 18466 mPrivateFlags &= ~PFLAG_PREPRESSED; 18467 setPressed(true); 18468 checkForLongClick(ViewConfiguration.getTapTimeout()); 18469 } 18470 } 18471 18472 private final class PerformClick implements Runnable { 18473 public void run() { 18474 performClick(); 18475 } 18476 } 18477 18478 /** @hide */ 18479 public void hackTurnOffWindowResizeAnim(boolean off) { 18480 mAttachInfo.mTurnOffWindowResizeAnim = off; 18481 } 18482 18483 /** 18484 * This method returns a ViewPropertyAnimator object, which can be used to animate 18485 * specific properties on this View. 18486 * 18487 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 18488 */ 18489 public ViewPropertyAnimator animate() { 18490 if (mAnimator == null) { 18491 mAnimator = new ViewPropertyAnimator(this); 18492 } 18493 return mAnimator; 18494 } 18495 18496 /** 18497 * Interface definition for a callback to be invoked when a hardware key event is 18498 * dispatched to this view. The callback will be invoked before the key event is 18499 * given to the view. This is only useful for hardware keyboards; a software input 18500 * method has no obligation to trigger this listener. 18501 */ 18502 public interface OnKeyListener { 18503 /** 18504 * Called when a hardware key is dispatched to a view. This allows listeners to 18505 * get a chance to respond before the target view. 18506 * <p>Key presses in software keyboards will generally NOT trigger this method, 18507 * although some may elect to do so in some situations. Do not assume a 18508 * software input method has to be key-based; even if it is, it may use key presses 18509 * in a different way than you expect, so there is no way to reliably catch soft 18510 * input key presses. 18511 * 18512 * @param v The view the key has been dispatched to. 18513 * @param keyCode The code for the physical key that was pressed 18514 * @param event The KeyEvent object containing full information about 18515 * the event. 18516 * @return True if the listener has consumed the event, false otherwise. 18517 */ 18518 boolean onKey(View v, int keyCode, KeyEvent event); 18519 } 18520 18521 /** 18522 * Interface definition for a callback to be invoked when a touch event is 18523 * dispatched to this view. The callback will be invoked before the touch 18524 * event is given to the view. 18525 */ 18526 public interface OnTouchListener { 18527 /** 18528 * Called when a touch event is dispatched to a view. This allows listeners to 18529 * get a chance to respond before the target view. 18530 * 18531 * @param v The view the touch event has been dispatched to. 18532 * @param event The MotionEvent object containing full information about 18533 * the event. 18534 * @return True if the listener has consumed the event, false otherwise. 18535 */ 18536 boolean onTouch(View v, MotionEvent event); 18537 } 18538 18539 /** 18540 * Interface definition for a callback to be invoked when a hover event is 18541 * dispatched to this view. The callback will be invoked before the hover 18542 * event is given to the view. 18543 */ 18544 public interface OnHoverListener { 18545 /** 18546 * Called when a hover event is dispatched to a view. This allows listeners to 18547 * get a chance to respond before the target view. 18548 * 18549 * @param v The view the hover event has been dispatched to. 18550 * @param event The MotionEvent object containing full information about 18551 * the event. 18552 * @return True if the listener has consumed the event, false otherwise. 18553 */ 18554 boolean onHover(View v, MotionEvent event); 18555 } 18556 18557 /** 18558 * Interface definition for a callback to be invoked when a generic motion event is 18559 * dispatched to this view. The callback will be invoked before the generic motion 18560 * event is given to the view. 18561 */ 18562 public interface OnGenericMotionListener { 18563 /** 18564 * Called when a generic motion event is dispatched to a view. This allows listeners to 18565 * get a chance to respond before the target view. 18566 * 18567 * @param v The view the generic motion event has been dispatched to. 18568 * @param event The MotionEvent object containing full information about 18569 * the event. 18570 * @return True if the listener has consumed the event, false otherwise. 18571 */ 18572 boolean onGenericMotion(View v, MotionEvent event); 18573 } 18574 18575 /** 18576 * Interface definition for a callback to be invoked when a view has been clicked and held. 18577 */ 18578 public interface OnLongClickListener { 18579 /** 18580 * Called when a view has been clicked and held. 18581 * 18582 * @param v The view that was clicked and held. 18583 * 18584 * @return true if the callback consumed the long click, false otherwise. 18585 */ 18586 boolean onLongClick(View v); 18587 } 18588 18589 /** 18590 * Interface definition for a callback to be invoked when a drag is being dispatched 18591 * to this view. The callback will be invoked before the hosting view's own 18592 * onDrag(event) method. If the listener wants to fall back to the hosting view's 18593 * onDrag(event) behavior, it should return 'false' from this callback. 18594 * 18595 * <div class="special reference"> 18596 * <h3>Developer Guides</h3> 18597 * <p>For a guide to implementing drag and drop features, read the 18598 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 18599 * </div> 18600 */ 18601 public interface OnDragListener { 18602 /** 18603 * Called when a drag event is dispatched to a view. This allows listeners 18604 * to get a chance to override base View behavior. 18605 * 18606 * @param v The View that received the drag event. 18607 * @param event The {@link android.view.DragEvent} object for the drag event. 18608 * @return {@code true} if the drag event was handled successfully, or {@code false} 18609 * if the drag event was not handled. Note that {@code false} will trigger the View 18610 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 18611 */ 18612 boolean onDrag(View v, DragEvent event); 18613 } 18614 18615 /** 18616 * Interface definition for a callback to be invoked when the focus state of 18617 * a view changed. 18618 */ 18619 public interface OnFocusChangeListener { 18620 /** 18621 * Called when the focus state of a view has changed. 18622 * 18623 * @param v The view whose state has changed. 18624 * @param hasFocus The new focus state of v. 18625 */ 18626 void onFocusChange(View v, boolean hasFocus); 18627 } 18628 18629 /** 18630 * Interface definition for a callback to be invoked when a view is clicked. 18631 */ 18632 public interface OnClickListener { 18633 /** 18634 * Called when a view has been clicked. 18635 * 18636 * @param v The view that was clicked. 18637 */ 18638 void onClick(View v); 18639 } 18640 18641 /** 18642 * Interface definition for a callback to be invoked when the context menu 18643 * for this view is being built. 18644 */ 18645 public interface OnCreateContextMenuListener { 18646 /** 18647 * Called when the context menu for this view is being built. It is not 18648 * safe to hold onto the menu after this method returns. 18649 * 18650 * @param menu The context menu that is being built 18651 * @param v The view for which the context menu is being built 18652 * @param menuInfo Extra information about the item for which the 18653 * context menu should be shown. This information will vary 18654 * depending on the class of v. 18655 */ 18656 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 18657 } 18658 18659 /** 18660 * Interface definition for a callback to be invoked when the status bar changes 18661 * visibility. This reports <strong>global</strong> changes to the system UI 18662 * state, not what the application is requesting. 18663 * 18664 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 18665 */ 18666 public interface OnSystemUiVisibilityChangeListener { 18667 /** 18668 * Called when the status bar changes visibility because of a call to 18669 * {@link View#setSystemUiVisibility(int)}. 18670 * 18671 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 18672 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 18673 * This tells you the <strong>global</strong> state of these UI visibility 18674 * flags, not what your app is currently applying. 18675 */ 18676 public void onSystemUiVisibilityChange(int visibility); 18677 } 18678 18679 /** 18680 * Interface definition for a callback to be invoked when this view is attached 18681 * or detached from its window. 18682 */ 18683 public interface OnAttachStateChangeListener { 18684 /** 18685 * Called when the view is attached to a window. 18686 * @param v The view that was attached 18687 */ 18688 public void onViewAttachedToWindow(View v); 18689 /** 18690 * Called when the view is detached from a window. 18691 * @param v The view that was detached 18692 */ 18693 public void onViewDetachedFromWindow(View v); 18694 } 18695 18696 private final class UnsetPressedState implements Runnable { 18697 public void run() { 18698 setPressed(false); 18699 } 18700 } 18701 18702 /** 18703 * Base class for derived classes that want to save and restore their own 18704 * state in {@link android.view.View#onSaveInstanceState()}. 18705 */ 18706 public static class BaseSavedState extends AbsSavedState { 18707 /** 18708 * Constructor used when reading from a parcel. Reads the state of the superclass. 18709 * 18710 * @param source 18711 */ 18712 public BaseSavedState(Parcel source) { 18713 super(source); 18714 } 18715 18716 /** 18717 * Constructor called by derived classes when creating their SavedState objects 18718 * 18719 * @param superState The state of the superclass of this view 18720 */ 18721 public BaseSavedState(Parcelable superState) { 18722 super(superState); 18723 } 18724 18725 public static final Parcelable.Creator<BaseSavedState> CREATOR = 18726 new Parcelable.Creator<BaseSavedState>() { 18727 public BaseSavedState createFromParcel(Parcel in) { 18728 return new BaseSavedState(in); 18729 } 18730 18731 public BaseSavedState[] newArray(int size) { 18732 return new BaseSavedState[size]; 18733 } 18734 }; 18735 } 18736 18737 /** 18738 * A set of information given to a view when it is attached to its parent 18739 * window. 18740 */ 18741 static class AttachInfo { 18742 interface Callbacks { 18743 void playSoundEffect(int effectId); 18744 boolean performHapticFeedback(int effectId, boolean always); 18745 } 18746 18747 /** 18748 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 18749 * to a Handler. This class contains the target (View) to invalidate and 18750 * the coordinates of the dirty rectangle. 18751 * 18752 * For performance purposes, this class also implements a pool of up to 18753 * POOL_LIMIT objects that get reused. This reduces memory allocations 18754 * whenever possible. 18755 */ 18756 static class InvalidateInfo { 18757 private static final int POOL_LIMIT = 10; 18758 18759 private static final SynchronizedPool<InvalidateInfo> sPool = 18760 new SynchronizedPool<InvalidateInfo>(POOL_LIMIT); 18761 18762 View target; 18763 18764 int left; 18765 int top; 18766 int right; 18767 int bottom; 18768 18769 public static InvalidateInfo obtain() { 18770 InvalidateInfo instance = sPool.acquire(); 18771 return (instance != null) ? instance : new InvalidateInfo(); 18772 } 18773 18774 public void recycle() { 18775 target = null; 18776 sPool.release(this); 18777 } 18778 } 18779 18780 final IWindowSession mSession; 18781 18782 final IWindow mWindow; 18783 18784 final IBinder mWindowToken; 18785 18786 final Display mDisplay; 18787 18788 final Callbacks mRootCallbacks; 18789 18790 HardwareCanvas mHardwareCanvas; 18791 18792 IWindowId mIWindowId; 18793 WindowId mWindowId; 18794 18795 /** 18796 * The top view of the hierarchy. 18797 */ 18798 View mRootView; 18799 18800 IBinder mPanelParentWindowToken; 18801 Surface mSurface; 18802 18803 boolean mHardwareAccelerated; 18804 boolean mHardwareAccelerationRequested; 18805 HardwareRenderer mHardwareRenderer; 18806 18807 boolean mScreenOn; 18808 18809 /** 18810 * Scale factor used by the compatibility mode 18811 */ 18812 float mApplicationScale; 18813 18814 /** 18815 * Indicates whether the application is in compatibility mode 18816 */ 18817 boolean mScalingRequired; 18818 18819 /** 18820 * If set, ViewRootImpl doesn't use its lame animation for when the window resizes. 18821 */ 18822 boolean mTurnOffWindowResizeAnim; 18823 18824 /** 18825 * Left position of this view's window 18826 */ 18827 int mWindowLeft; 18828 18829 /** 18830 * Top position of this view's window 18831 */ 18832 int mWindowTop; 18833 18834 /** 18835 * Indicates whether views need to use 32-bit drawing caches 18836 */ 18837 boolean mUse32BitDrawingCache; 18838 18839 /** 18840 * For windows that are full-screen but using insets to layout inside 18841 * of the screen areas, these are the current insets to appear inside 18842 * the overscan area of the display. 18843 */ 18844 final Rect mOverscanInsets = new Rect(); 18845 18846 /** 18847 * For windows that are full-screen but using insets to layout inside 18848 * of the screen decorations, these are the current insets for the 18849 * content of the window. 18850 */ 18851 final Rect mContentInsets = new Rect(); 18852 18853 /** 18854 * For windows that are full-screen but using insets to layout inside 18855 * of the screen decorations, these are the current insets for the 18856 * actual visible parts of the window. 18857 */ 18858 final Rect mVisibleInsets = new Rect(); 18859 18860 /** 18861 * The internal insets given by this window. This value is 18862 * supplied by the client (through 18863 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 18864 * be given to the window manager when changed to be used in laying 18865 * out windows behind it. 18866 */ 18867 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 18868 = new ViewTreeObserver.InternalInsetsInfo(); 18869 18870 /** 18871 * Set to true when mGivenInternalInsets is non-empty. 18872 */ 18873 boolean mHasNonEmptyGivenInternalInsets; 18874 18875 /** 18876 * All views in the window's hierarchy that serve as scroll containers, 18877 * used to determine if the window can be resized or must be panned 18878 * to adjust for a soft input area. 18879 */ 18880 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 18881 18882 final KeyEvent.DispatcherState mKeyDispatchState 18883 = new KeyEvent.DispatcherState(); 18884 18885 /** 18886 * Indicates whether the view's window currently has the focus. 18887 */ 18888 boolean mHasWindowFocus; 18889 18890 /** 18891 * The current visibility of the window. 18892 */ 18893 int mWindowVisibility; 18894 18895 /** 18896 * Indicates the time at which drawing started to occur. 18897 */ 18898 long mDrawingTime; 18899 18900 /** 18901 * Indicates whether or not ignoring the DIRTY_MASK flags. 18902 */ 18903 boolean mIgnoreDirtyState; 18904 18905 /** 18906 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 18907 * to avoid clearing that flag prematurely. 18908 */ 18909 boolean mSetIgnoreDirtyState = false; 18910 18911 /** 18912 * Indicates whether the view's window is currently in touch mode. 18913 */ 18914 boolean mInTouchMode; 18915 18916 /** 18917 * Indicates that ViewAncestor should trigger a global layout change 18918 * the next time it performs a traversal 18919 */ 18920 boolean mRecomputeGlobalAttributes; 18921 18922 /** 18923 * Always report new attributes at next traversal. 18924 */ 18925 boolean mForceReportNewAttributes; 18926 18927 /** 18928 * Set during a traveral if any views want to keep the screen on. 18929 */ 18930 boolean mKeepScreenOn; 18931 18932 /** 18933 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 18934 */ 18935 int mSystemUiVisibility; 18936 18937 /** 18938 * Hack to force certain system UI visibility flags to be cleared. 18939 */ 18940 int mDisabledSystemUiVisibility; 18941 18942 /** 18943 * Last global system UI visibility reported by the window manager. 18944 */ 18945 int mGlobalSystemUiVisibility; 18946 18947 /** 18948 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 18949 * attached. 18950 */ 18951 boolean mHasSystemUiListeners; 18952 18953 /** 18954 * Set if the window has requested to extend into the overscan region 18955 * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN. 18956 */ 18957 boolean mOverscanRequested; 18958 18959 /** 18960 * Set if the visibility of any views has changed. 18961 */ 18962 boolean mViewVisibilityChanged; 18963 18964 /** 18965 * Set to true if a view has been scrolled. 18966 */ 18967 boolean mViewScrollChanged; 18968 18969 /** 18970 * Global to the view hierarchy used as a temporary for dealing with 18971 * x/y points in the transparent region computations. 18972 */ 18973 final int[] mTransparentLocation = new int[2]; 18974 18975 /** 18976 * Global to the view hierarchy used as a temporary for dealing with 18977 * x/y points in the ViewGroup.invalidateChild implementation. 18978 */ 18979 final int[] mInvalidateChildLocation = new int[2]; 18980 18981 18982 /** 18983 * Global to the view hierarchy used as a temporary for dealing with 18984 * x/y location when view is transformed. 18985 */ 18986 final float[] mTmpTransformLocation = new float[2]; 18987 18988 /** 18989 * The view tree observer used to dispatch global events like 18990 * layout, pre-draw, touch mode change, etc. 18991 */ 18992 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 18993 18994 /** 18995 * A Canvas used by the view hierarchy to perform bitmap caching. 18996 */ 18997 Canvas mCanvas; 18998 18999 /** 19000 * The view root impl. 19001 */ 19002 final ViewRootImpl mViewRootImpl; 19003 19004 /** 19005 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 19006 * handler can be used to pump events in the UI events queue. 19007 */ 19008 final Handler mHandler; 19009 19010 /** 19011 * Temporary for use in computing invalidate rectangles while 19012 * calling up the hierarchy. 19013 */ 19014 final Rect mTmpInvalRect = new Rect(); 19015 19016 /** 19017 * Temporary for use in computing hit areas with transformed views 19018 */ 19019 final RectF mTmpTransformRect = new RectF(); 19020 19021 /** 19022 * Temporary for use in transforming invalidation rect 19023 */ 19024 final Matrix mTmpMatrix = new Matrix(); 19025 19026 /** 19027 * Temporary for use in transforming invalidation rect 19028 */ 19029 final Transformation mTmpTransformation = new Transformation(); 19030 19031 /** 19032 * Temporary list for use in collecting focusable descendents of a view. 19033 */ 19034 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 19035 19036 /** 19037 * The id of the window for accessibility purposes. 19038 */ 19039 int mAccessibilityWindowId = View.NO_ID; 19040 19041 /** 19042 * Flags related to accessibility processing. 19043 * 19044 * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 19045 * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS 19046 */ 19047 int mAccessibilityFetchFlags; 19048 19049 /** 19050 * The drawable for highlighting accessibility focus. 19051 */ 19052 Drawable mAccessibilityFocusDrawable; 19053 19054 /** 19055 * Show where the margins, bounds and layout bounds are for each view. 19056 */ 19057 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 19058 19059 /** 19060 * Point used to compute visible regions. 19061 */ 19062 final Point mPoint = new Point(); 19063 19064 /** 19065 * Used to track which View originated a requestLayout() call, used when 19066 * requestLayout() is called during layout. 19067 */ 19068 View mViewRequestingLayout; 19069 19070 /** 19071 * Creates a new set of attachment information with the specified 19072 * events handler and thread. 19073 * 19074 * @param handler the events handler the view must use 19075 */ 19076 AttachInfo(IWindowSession session, IWindow window, Display display, 19077 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) { 19078 mSession = session; 19079 mWindow = window; 19080 mWindowToken = window.asBinder(); 19081 mDisplay = display; 19082 mViewRootImpl = viewRootImpl; 19083 mHandler = handler; 19084 mRootCallbacks = effectPlayer; 19085 } 19086 } 19087 19088 /** 19089 * <p>ScrollabilityCache holds various fields used by a View when scrolling 19090 * is supported. This avoids keeping too many unused fields in most 19091 * instances of View.</p> 19092 */ 19093 private static class ScrollabilityCache implements Runnable { 19094 19095 /** 19096 * Scrollbars are not visible 19097 */ 19098 public static final int OFF = 0; 19099 19100 /** 19101 * Scrollbars are visible 19102 */ 19103 public static final int ON = 1; 19104 19105 /** 19106 * Scrollbars are fading away 19107 */ 19108 public static final int FADING = 2; 19109 19110 public boolean fadeScrollBars; 19111 19112 public int fadingEdgeLength; 19113 public int scrollBarDefaultDelayBeforeFade; 19114 public int scrollBarFadeDuration; 19115 19116 public int scrollBarSize; 19117 public ScrollBarDrawable scrollBar; 19118 public float[] interpolatorValues; 19119 public View host; 19120 19121 public final Paint paint; 19122 public final Matrix matrix; 19123 public Shader shader; 19124 19125 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 19126 19127 private static final float[] OPAQUE = { 255 }; 19128 private static final float[] TRANSPARENT = { 0.0f }; 19129 19130 /** 19131 * When fading should start. This time moves into the future every time 19132 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 19133 */ 19134 public long fadeStartTime; 19135 19136 19137 /** 19138 * The current state of the scrollbars: ON, OFF, or FADING 19139 */ 19140 public int state = OFF; 19141 19142 private int mLastColor; 19143 19144 public ScrollabilityCache(ViewConfiguration configuration, View host) { 19145 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 19146 scrollBarSize = configuration.getScaledScrollBarSize(); 19147 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 19148 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 19149 19150 paint = new Paint(); 19151 matrix = new Matrix(); 19152 // use use a height of 1, and then wack the matrix each time we 19153 // actually use it. 19154 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 19155 paint.setShader(shader); 19156 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 19157 19158 this.host = host; 19159 } 19160 19161 public void setFadeColor(int color) { 19162 if (color != mLastColor) { 19163 mLastColor = color; 19164 19165 if (color != 0) { 19166 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 19167 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 19168 paint.setShader(shader); 19169 // Restore the default transfer mode (src_over) 19170 paint.setXfermode(null); 19171 } else { 19172 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 19173 paint.setShader(shader); 19174 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 19175 } 19176 } 19177 } 19178 19179 public void run() { 19180 long now = AnimationUtils.currentAnimationTimeMillis(); 19181 if (now >= fadeStartTime) { 19182 19183 // the animation fades the scrollbars out by changing 19184 // the opacity (alpha) from fully opaque to fully 19185 // transparent 19186 int nextFrame = (int) now; 19187 int framesCount = 0; 19188 19189 Interpolator interpolator = scrollBarInterpolator; 19190 19191 // Start opaque 19192 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 19193 19194 // End transparent 19195 nextFrame += scrollBarFadeDuration; 19196 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 19197 19198 state = FADING; 19199 19200 // Kick off the fade animation 19201 host.invalidate(true); 19202 } 19203 } 19204 } 19205 19206 /** 19207 * Resuable callback for sending 19208 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 19209 */ 19210 private class SendViewScrolledAccessibilityEvent implements Runnable { 19211 public volatile boolean mIsPending; 19212 19213 public void run() { 19214 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 19215 mIsPending = false; 19216 } 19217 } 19218 19219 /** 19220 * <p> 19221 * This class represents a delegate that can be registered in a {@link View} 19222 * to enhance accessibility support via composition rather via inheritance. 19223 * It is specifically targeted to widget developers that extend basic View 19224 * classes i.e. classes in package android.view, that would like their 19225 * applications to be backwards compatible. 19226 * </p> 19227 * <div class="special reference"> 19228 * <h3>Developer Guides</h3> 19229 * <p>For more information about making applications accessible, read the 19230 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 19231 * developer guide.</p> 19232 * </div> 19233 * <p> 19234 * A scenario in which a developer would like to use an accessibility delegate 19235 * is overriding a method introduced in a later API version then the minimal API 19236 * version supported by the application. For example, the method 19237 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 19238 * in API version 4 when the accessibility APIs were first introduced. If a 19239 * developer would like his application to run on API version 4 devices (assuming 19240 * all other APIs used by the application are version 4 or lower) and take advantage 19241 * of this method, instead of overriding the method which would break the application's 19242 * backwards compatibility, he can override the corresponding method in this 19243 * delegate and register the delegate in the target View if the API version of 19244 * the system is high enough i.e. the API version is same or higher to the API 19245 * version that introduced 19246 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 19247 * </p> 19248 * <p> 19249 * Here is an example implementation: 19250 * </p> 19251 * <code><pre><p> 19252 * if (Build.VERSION.SDK_INT >= 14) { 19253 * // If the API version is equal of higher than the version in 19254 * // which onInitializeAccessibilityNodeInfo was introduced we 19255 * // register a delegate with a customized implementation. 19256 * View view = findViewById(R.id.view_id); 19257 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 19258 * public void onInitializeAccessibilityNodeInfo(View host, 19259 * AccessibilityNodeInfo info) { 19260 * // Let the default implementation populate the info. 19261 * super.onInitializeAccessibilityNodeInfo(host, info); 19262 * // Set some other information. 19263 * info.setEnabled(host.isEnabled()); 19264 * } 19265 * }); 19266 * } 19267 * </code></pre></p> 19268 * <p> 19269 * This delegate contains methods that correspond to the accessibility methods 19270 * in View. If a delegate has been specified the implementation in View hands 19271 * off handling to the corresponding method in this delegate. The default 19272 * implementation the delegate methods behaves exactly as the corresponding 19273 * method in View for the case of no accessibility delegate been set. Hence, 19274 * to customize the behavior of a View method, clients can override only the 19275 * corresponding delegate method without altering the behavior of the rest 19276 * accessibility related methods of the host view. 19277 * </p> 19278 */ 19279 public static class AccessibilityDelegate { 19280 19281 /** 19282 * Sends an accessibility event of the given type. If accessibility is not 19283 * enabled this method has no effect. 19284 * <p> 19285 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 19286 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 19287 * been set. 19288 * </p> 19289 * 19290 * @param host The View hosting the delegate. 19291 * @param eventType The type of the event to send. 19292 * 19293 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 19294 */ 19295 public void sendAccessibilityEvent(View host, int eventType) { 19296 host.sendAccessibilityEventInternal(eventType); 19297 } 19298 19299 /** 19300 * Performs the specified accessibility action on the view. For 19301 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 19302 * <p> 19303 * The default implementation behaves as 19304 * {@link View#performAccessibilityAction(int, Bundle) 19305 * View#performAccessibilityAction(int, Bundle)} for the case of 19306 * no accessibility delegate been set. 19307 * </p> 19308 * 19309 * @param action The action to perform. 19310 * @return Whether the action was performed. 19311 * 19312 * @see View#performAccessibilityAction(int, Bundle) 19313 * View#performAccessibilityAction(int, Bundle) 19314 */ 19315 public boolean performAccessibilityAction(View host, int action, Bundle args) { 19316 return host.performAccessibilityActionInternal(action, args); 19317 } 19318 19319 /** 19320 * Sends an accessibility event. This method behaves exactly as 19321 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 19322 * empty {@link AccessibilityEvent} and does not perform a check whether 19323 * accessibility is enabled. 19324 * <p> 19325 * The default implementation behaves as 19326 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 19327 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 19328 * the case of no accessibility delegate been set. 19329 * </p> 19330 * 19331 * @param host The View hosting the delegate. 19332 * @param event The event to send. 19333 * 19334 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 19335 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 19336 */ 19337 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 19338 host.sendAccessibilityEventUncheckedInternal(event); 19339 } 19340 19341 /** 19342 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 19343 * to its children for adding their text content to the event. 19344 * <p> 19345 * The default implementation behaves as 19346 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 19347 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 19348 * the case of no accessibility delegate been set. 19349 * </p> 19350 * 19351 * @param host The View hosting the delegate. 19352 * @param event The event. 19353 * @return True if the event population was completed. 19354 * 19355 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 19356 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 19357 */ 19358 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 19359 return host.dispatchPopulateAccessibilityEventInternal(event); 19360 } 19361 19362 /** 19363 * Gives a chance to the host View to populate the accessibility event with its 19364 * text content. 19365 * <p> 19366 * The default implementation behaves as 19367 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 19368 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 19369 * the case of no accessibility delegate been set. 19370 * </p> 19371 * 19372 * @param host The View hosting the delegate. 19373 * @param event The accessibility event which to populate. 19374 * 19375 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 19376 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 19377 */ 19378 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 19379 host.onPopulateAccessibilityEventInternal(event); 19380 } 19381 19382 /** 19383 * Initializes an {@link AccessibilityEvent} with information about the 19384 * the host View which is the event source. 19385 * <p> 19386 * The default implementation behaves as 19387 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 19388 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 19389 * the case of no accessibility delegate been set. 19390 * </p> 19391 * 19392 * @param host The View hosting the delegate. 19393 * @param event The event to initialize. 19394 * 19395 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 19396 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 19397 */ 19398 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 19399 host.onInitializeAccessibilityEventInternal(event); 19400 } 19401 19402 /** 19403 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 19404 * <p> 19405 * The default implementation behaves as 19406 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 19407 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 19408 * the case of no accessibility delegate been set. 19409 * </p> 19410 * 19411 * @param host The View hosting the delegate. 19412 * @param info The instance to initialize. 19413 * 19414 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 19415 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 19416 */ 19417 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 19418 host.onInitializeAccessibilityNodeInfoInternal(info); 19419 } 19420 19421 /** 19422 * Called when a child of the host View has requested sending an 19423 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 19424 * to augment the event. 19425 * <p> 19426 * The default implementation behaves as 19427 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 19428 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 19429 * the case of no accessibility delegate been set. 19430 * </p> 19431 * 19432 * @param host The View hosting the delegate. 19433 * @param child The child which requests sending the event. 19434 * @param event The event to be sent. 19435 * @return True if the event should be sent 19436 * 19437 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 19438 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 19439 */ 19440 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 19441 AccessibilityEvent event) { 19442 return host.onRequestSendAccessibilityEventInternal(child, event); 19443 } 19444 19445 /** 19446 * Gets the provider for managing a virtual view hierarchy rooted at this View 19447 * and reported to {@link android.accessibilityservice.AccessibilityService}s 19448 * that explore the window content. 19449 * <p> 19450 * The default implementation behaves as 19451 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 19452 * the case of no accessibility delegate been set. 19453 * </p> 19454 * 19455 * @return The provider. 19456 * 19457 * @see AccessibilityNodeProvider 19458 */ 19459 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 19460 return null; 19461 } 19462 19463 /** 19464 * Returns an {@link AccessibilityNodeInfo} representing the host view from the 19465 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 19466 * This method is responsible for obtaining an accessibility node info from a 19467 * pool of reusable instances and calling 19468 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host 19469 * view to initialize the former. 19470 * <p> 19471 * <strong>Note:</strong> The client is responsible for recycling the obtained 19472 * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object 19473 * creation. 19474 * </p> 19475 * <p> 19476 * The default implementation behaves as 19477 * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for 19478 * the case of no accessibility delegate been set. 19479 * </p> 19480 * @return A populated {@link AccessibilityNodeInfo}. 19481 * 19482 * @see AccessibilityNodeInfo 19483 * 19484 * @hide 19485 */ 19486 public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) { 19487 return host.createAccessibilityNodeInfoInternal(); 19488 } 19489 } 19490 19491 private class MatchIdPredicate implements Predicate<View> { 19492 public int mId; 19493 19494 @Override 19495 public boolean apply(View view) { 19496 return (view.mID == mId); 19497 } 19498 } 19499 19500 private class MatchLabelForPredicate implements Predicate<View> { 19501 private int mLabeledId; 19502 19503 @Override 19504 public boolean apply(View view) { 19505 return (view.mLabelForId == mLabeledId); 19506 } 19507 } 19508 19509 private class SendViewStateChangedAccessibilityEvent implements Runnable { 19510 private int mChangeTypes = 0; 19511 private boolean mPosted; 19512 private boolean mPostedWithDelay; 19513 private long mLastEventTimeMillis; 19514 19515 @Override 19516 public void run() { 19517 mPosted = false; 19518 mPostedWithDelay = false; 19519 mLastEventTimeMillis = SystemClock.uptimeMillis(); 19520 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 19521 final AccessibilityEvent event = AccessibilityEvent.obtain(); 19522 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 19523 event.setContentChangeTypes(mChangeTypes); 19524 sendAccessibilityEventUnchecked(event); 19525 } 19526 mChangeTypes = 0; 19527 } 19528 19529 public void runOrPost(int changeType) { 19530 mChangeTypes |= changeType; 19531 19532 // If this is a live region or the child of a live region, collect 19533 // all events from this frame and send them on the next frame. 19534 if (inLiveRegion()) { 19535 // If we're already posted with a delay, remove that. 19536 if (mPostedWithDelay) { 19537 removeCallbacks(this); 19538 mPostedWithDelay = false; 19539 } 19540 // Only post if we're not already posted. 19541 if (!mPosted) { 19542 post(this); 19543 mPosted = true; 19544 } 19545 return; 19546 } 19547 19548 if (mPosted) { 19549 return; 19550 } 19551 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 19552 final long minEventIntevalMillis = 19553 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 19554 if (timeSinceLastMillis >= minEventIntevalMillis) { 19555 removeCallbacks(this); 19556 run(); 19557 } else { 19558 postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 19559 mPosted = true; 19560 mPostedWithDelay = true; 19561 } 19562 } 19563 } 19564 19565 private boolean inLiveRegion() { 19566 if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) { 19567 return true; 19568 } 19569 19570 ViewParent parent = getParent(); 19571 while (parent instanceof View) { 19572 if (((View) parent).getAccessibilityLiveRegion() 19573 != View.ACCESSIBILITY_LIVE_REGION_NONE) { 19574 return true; 19575 } 19576 parent = parent.getParent(); 19577 } 19578 19579 return false; 19580 } 19581 19582 /** 19583 * Dump all private flags in readable format, useful for documentation and 19584 * sanity checking. 19585 */ 19586 private static void dumpFlags() { 19587 final HashMap<String, String> found = Maps.newHashMap(); 19588 try { 19589 for (Field field : View.class.getDeclaredFields()) { 19590 final int modifiers = field.getModifiers(); 19591 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 19592 if (field.getType().equals(int.class)) { 19593 final int value = field.getInt(null); 19594 dumpFlag(found, field.getName(), value); 19595 } else if (field.getType().equals(int[].class)) { 19596 final int[] values = (int[]) field.get(null); 19597 for (int i = 0; i < values.length; i++) { 19598 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 19599 } 19600 } 19601 } 19602 } 19603 } catch (IllegalAccessException e) { 19604 throw new RuntimeException(e); 19605 } 19606 19607 final ArrayList<String> keys = Lists.newArrayList(); 19608 keys.addAll(found.keySet()); 19609 Collections.sort(keys); 19610 for (String key : keys) { 19611 Log.d(VIEW_LOG_TAG, found.get(key)); 19612 } 19613 } 19614 19615 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 19616 // Sort flags by prefix, then by bits, always keeping unique keys 19617 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 19618 final int prefix = name.indexOf('_'); 19619 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 19620 final String output = bits + " " + name; 19621 found.put(key, output); 19622 } 19623} 19624