View.java revision 743922e9dfe295d4cc837eee1646272aa88da135
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.animation.AnimatorInflater; 20import android.animation.RevealAnimator; 21import android.animation.StateListAnimator; 22import android.animation.ValueAnimator; 23import android.annotation.IntDef; 24import android.annotation.NonNull; 25import android.annotation.Nullable; 26import android.content.ClipData; 27import android.content.Context; 28import android.content.res.Configuration; 29import android.content.res.Resources; 30import android.content.res.TypedArray; 31import android.graphics.Bitmap; 32import android.graphics.Canvas; 33import android.graphics.Insets; 34import android.graphics.Interpolator; 35import android.graphics.LinearGradient; 36import android.graphics.Matrix; 37import android.graphics.Outline; 38import android.graphics.Paint; 39import android.graphics.PixelFormat; 40import android.graphics.Point; 41import android.graphics.PorterDuff; 42import android.graphics.PorterDuffXfermode; 43import android.graphics.Rect; 44import android.graphics.RectF; 45import android.graphics.Region; 46import android.graphics.Shader; 47import android.graphics.drawable.ColorDrawable; 48import android.graphics.drawable.Drawable; 49import android.hardware.display.DisplayManagerGlobal; 50import android.os.Bundle; 51import android.os.Handler; 52import android.os.IBinder; 53import android.os.Parcel; 54import android.os.Parcelable; 55import android.os.RemoteException; 56import android.os.SystemClock; 57import android.os.SystemProperties; 58import android.text.TextUtils; 59import android.util.AttributeSet; 60import android.util.FloatProperty; 61import android.util.LayoutDirection; 62import android.util.Log; 63import android.util.LongSparseLongArray; 64import android.util.Pools.SynchronizedPool; 65import android.util.Property; 66import android.util.SparseArray; 67import android.util.SuperNotCalledException; 68import android.util.TypedValue; 69import android.view.ContextMenu.ContextMenuInfo; 70import android.view.AccessibilityIterators.TextSegmentIterator; 71import android.view.AccessibilityIterators.CharacterTextSegmentIterator; 72import android.view.AccessibilityIterators.WordTextSegmentIterator; 73import android.view.AccessibilityIterators.ParagraphTextSegmentIterator; 74import android.view.accessibility.AccessibilityEvent; 75import android.view.accessibility.AccessibilityEventSource; 76import android.view.accessibility.AccessibilityManager; 77import android.view.accessibility.AccessibilityNodeInfo; 78import android.view.accessibility.AccessibilityNodeProvider; 79import android.view.animation.Animation; 80import android.view.animation.AnimationUtils; 81import android.view.animation.Transformation; 82import android.view.inputmethod.EditorInfo; 83import android.view.inputmethod.InputConnection; 84import android.view.inputmethod.InputMethodManager; 85import android.widget.ScrollBarDrawable; 86 87import static android.os.Build.VERSION_CODES.*; 88import static java.lang.Math.max; 89 90import com.android.internal.R; 91import com.android.internal.util.Predicate; 92import com.android.internal.view.menu.MenuBuilder; 93import com.google.android.collect.Lists; 94import com.google.android.collect.Maps; 95 96import java.lang.annotation.Retention; 97import java.lang.annotation.RetentionPolicy; 98import java.lang.ref.WeakReference; 99import java.lang.reflect.Field; 100import java.lang.reflect.InvocationTargetException; 101import java.lang.reflect.Method; 102import java.lang.reflect.Modifier; 103import java.util.ArrayList; 104import java.util.Arrays; 105import java.util.Collections; 106import java.util.HashMap; 107import java.util.List; 108import java.util.Locale; 109import java.util.Map; 110import java.util.concurrent.CopyOnWriteArrayList; 111import java.util.concurrent.atomic.AtomicInteger; 112 113/** 114 * <p> 115 * This class represents the basic building block for user interface components. A View 116 * occupies a rectangular area on the screen and is responsible for drawing and 117 * event handling. View is the base class for <em>widgets</em>, which are 118 * used to create interactive UI components (buttons, text fields, etc.). The 119 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 120 * are invisible containers that hold other Views (or other ViewGroups) and define 121 * their layout properties. 122 * </p> 123 * 124 * <div class="special reference"> 125 * <h3>Developer Guides</h3> 126 * <p>For information about using this class to develop your application's user interface, 127 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide. 128 * </div> 129 * 130 * <a name="Using"></a> 131 * <h3>Using Views</h3> 132 * <p> 133 * All of the views in a window are arranged in a single tree. You can add views 134 * either from code or by specifying a tree of views in one or more XML layout 135 * files. There are many specialized subclasses of views that act as controls or 136 * are capable of displaying text, images, or other content. 137 * </p> 138 * <p> 139 * Once you have created a tree of views, there are typically a few types of 140 * common operations you may wish to perform: 141 * <ul> 142 * <li><strong>Set properties:</strong> for example setting the text of a 143 * {@link android.widget.TextView}. The available properties and the methods 144 * that set them will vary among the different subclasses of views. Note that 145 * properties that are known at build time can be set in the XML layout 146 * files.</li> 147 * <li><strong>Set focus:</strong> The framework will handled moving focus in 148 * response to user input. To force focus to a specific view, call 149 * {@link #requestFocus}.</li> 150 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 151 * that will be notified when something interesting happens to the view. For 152 * example, all views will let you set a listener to be notified when the view 153 * gains or loses focus. You can register such a listener using 154 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 155 * Other view subclasses offer more specialized listeners. For example, a Button 156 * exposes a listener to notify clients when the button is clicked.</li> 157 * <li><strong>Set visibility:</strong> You can hide or show views using 158 * {@link #setVisibility(int)}.</li> 159 * </ul> 160 * </p> 161 * <p><em> 162 * Note: The Android framework is responsible for measuring, laying out and 163 * drawing views. You should not call methods that perform these actions on 164 * views yourself unless you are actually implementing a 165 * {@link android.view.ViewGroup}. 166 * </em></p> 167 * 168 * <a name="Lifecycle"></a> 169 * <h3>Implementing a Custom View</h3> 170 * 171 * <p> 172 * To implement a custom view, you will usually begin by providing overrides for 173 * some of the standard methods that the framework calls on all views. You do 174 * not need to override all of these methods. In fact, you can start by just 175 * overriding {@link #onDraw(android.graphics.Canvas)}. 176 * <table border="2" width="85%" align="center" cellpadding="5"> 177 * <thead> 178 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 179 * </thead> 180 * 181 * <tbody> 182 * <tr> 183 * <td rowspan="2">Creation</td> 184 * <td>Constructors</td> 185 * <td>There is a form of the constructor that are called when the view 186 * is created from code and a form that is called when the view is 187 * inflated from a layout file. The second form should parse and apply 188 * any attributes defined in the layout file. 189 * </td> 190 * </tr> 191 * <tr> 192 * <td><code>{@link #onFinishInflate()}</code></td> 193 * <td>Called after a view and all of its children has been inflated 194 * from XML.</td> 195 * </tr> 196 * 197 * <tr> 198 * <td rowspan="3">Layout</td> 199 * <td><code>{@link #onMeasure(int, int)}</code></td> 200 * <td>Called to determine the size requirements for this view and all 201 * of its children. 202 * </td> 203 * </tr> 204 * <tr> 205 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 206 * <td>Called when this view should assign a size and position to all 207 * of its children. 208 * </td> 209 * </tr> 210 * <tr> 211 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 212 * <td>Called when the size of this view has changed. 213 * </td> 214 * </tr> 215 * 216 * <tr> 217 * <td>Drawing</td> 218 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 219 * <td>Called when the view should render its content. 220 * </td> 221 * </tr> 222 * 223 * <tr> 224 * <td rowspan="4">Event processing</td> 225 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 226 * <td>Called when a new hardware key event occurs. 227 * </td> 228 * </tr> 229 * <tr> 230 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 231 * <td>Called when a hardware key up event occurs. 232 * </td> 233 * </tr> 234 * <tr> 235 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 236 * <td>Called when a trackball motion event occurs. 237 * </td> 238 * </tr> 239 * <tr> 240 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 241 * <td>Called when a touch screen motion event occurs. 242 * </td> 243 * </tr> 244 * 245 * <tr> 246 * <td rowspan="2">Focus</td> 247 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 248 * <td>Called when the view gains or loses focus. 249 * </td> 250 * </tr> 251 * 252 * <tr> 253 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 254 * <td>Called when the window containing the view gains or loses focus. 255 * </td> 256 * </tr> 257 * 258 * <tr> 259 * <td rowspan="3">Attaching</td> 260 * <td><code>{@link #onAttachedToWindow()}</code></td> 261 * <td>Called when the view is attached to a window. 262 * </td> 263 * </tr> 264 * 265 * <tr> 266 * <td><code>{@link #onDetachedFromWindow}</code></td> 267 * <td>Called when the view is detached from its window. 268 * </td> 269 * </tr> 270 * 271 * <tr> 272 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 273 * <td>Called when the visibility of the window containing the view 274 * has changed. 275 * </td> 276 * </tr> 277 * </tbody> 278 * 279 * </table> 280 * </p> 281 * 282 * <a name="IDs"></a> 283 * <h3>IDs</h3> 284 * Views may have an integer id associated with them. These ids are typically 285 * assigned in the layout XML files, and are used to find specific views within 286 * the view tree. A common pattern is to: 287 * <ul> 288 * <li>Define a Button in the layout file and assign it a unique ID. 289 * <pre> 290 * <Button 291 * android:id="@+id/my_button" 292 * android:layout_width="wrap_content" 293 * android:layout_height="wrap_content" 294 * android:text="@string/my_button_text"/> 295 * </pre></li> 296 * <li>From the onCreate method of an Activity, find the Button 297 * <pre class="prettyprint"> 298 * Button myButton = (Button) findViewById(R.id.my_button); 299 * </pre></li> 300 * </ul> 301 * <p> 302 * View IDs need not be unique throughout the tree, but it is good practice to 303 * ensure that they are at least unique within the part of the tree you are 304 * searching. 305 * </p> 306 * 307 * <a name="Position"></a> 308 * <h3>Position</h3> 309 * <p> 310 * The geometry of a view is that of a rectangle. A view has a location, 311 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 312 * two dimensions, expressed as a width and a height. The unit for location 313 * and dimensions is the pixel. 314 * </p> 315 * 316 * <p> 317 * It is possible to retrieve the location of a view by invoking the methods 318 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 319 * coordinate of the rectangle representing the view. The latter returns the 320 * top, or Y, coordinate of the rectangle representing the view. These methods 321 * both return the location of the view relative to its parent. For instance, 322 * when getLeft() returns 20, that means the view is located 20 pixels to the 323 * right of the left edge of its direct parent. 324 * </p> 325 * 326 * <p> 327 * In addition, several convenience methods are offered to avoid unnecessary 328 * computations, namely {@link #getRight()} and {@link #getBottom()}. 329 * These methods return the coordinates of the right and bottom edges of the 330 * rectangle representing the view. For instance, calling {@link #getRight()} 331 * is similar to the following computation: <code>getLeft() + getWidth()</code> 332 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 333 * </p> 334 * 335 * <a name="SizePaddingMargins"></a> 336 * <h3>Size, padding and margins</h3> 337 * <p> 338 * The size of a view is expressed with a width and a height. A view actually 339 * possess two pairs of width and height values. 340 * </p> 341 * 342 * <p> 343 * The first pair is known as <em>measured width</em> and 344 * <em>measured height</em>. These dimensions define how big a view wants to be 345 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 346 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 347 * and {@link #getMeasuredHeight()}. 348 * </p> 349 * 350 * <p> 351 * The second pair is simply known as <em>width</em> and <em>height</em>, or 352 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 353 * dimensions define the actual size of the view on screen, at drawing time and 354 * after layout. These values may, but do not have to, be different from the 355 * measured width and height. The width and height can be obtained by calling 356 * {@link #getWidth()} and {@link #getHeight()}. 357 * </p> 358 * 359 * <p> 360 * To measure its dimensions, a view takes into account its padding. The padding 361 * is expressed in pixels for the left, top, right and bottom parts of the view. 362 * Padding can be used to offset the content of the view by a specific amount of 363 * pixels. For instance, a left padding of 2 will push the view's content by 364 * 2 pixels to the right of the left edge. Padding can be set using the 365 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)} 366 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 367 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()}, 368 * {@link #getPaddingEnd()}. 369 * </p> 370 * 371 * <p> 372 * Even though a view can define a padding, it does not provide any support for 373 * margins. However, view groups provide such a support. Refer to 374 * {@link android.view.ViewGroup} and 375 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 376 * </p> 377 * 378 * <a name="Layout"></a> 379 * <h3>Layout</h3> 380 * <p> 381 * Layout is a two pass process: a measure pass and a layout pass. The measuring 382 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 383 * of the view tree. Each view pushes dimension specifications down the tree 384 * during the recursion. At the end of the measure pass, every view has stored 385 * its measurements. The second pass happens in 386 * {@link #layout(int,int,int,int)} and is also top-down. During 387 * this pass each parent is responsible for positioning all of its children 388 * using the sizes computed in the measure pass. 389 * </p> 390 * 391 * <p> 392 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 393 * {@link #getMeasuredHeight()} values must be set, along with those for all of 394 * that view's descendants. A view's measured width and measured height values 395 * must respect the constraints imposed by the view's parents. This guarantees 396 * that at the end of the measure pass, all parents accept all of their 397 * children's measurements. A parent view may call measure() more than once on 398 * its children. For example, the parent may measure each child once with 399 * unspecified dimensions to find out how big they want to be, then call 400 * measure() on them again with actual numbers if the sum of all the children's 401 * unconstrained sizes is too big or too small. 402 * </p> 403 * 404 * <p> 405 * The measure pass uses two classes to communicate dimensions. The 406 * {@link MeasureSpec} class is used by views to tell their parents how they 407 * want to be measured and positioned. The base LayoutParams class just 408 * describes how big the view wants to be for both width and height. For each 409 * dimension, it can specify one of: 410 * <ul> 411 * <li> an exact number 412 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 413 * (minus padding) 414 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 415 * enclose its content (plus padding). 416 * </ul> 417 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 418 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 419 * an X and Y value. 420 * </p> 421 * 422 * <p> 423 * MeasureSpecs are used to push requirements down the tree from parent to 424 * child. A MeasureSpec can be in one of three modes: 425 * <ul> 426 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 427 * of a child view. For example, a LinearLayout may call measure() on its child 428 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 429 * tall the child view wants to be given a width of 240 pixels. 430 * <li>EXACTLY: This is used by the parent to impose an exact size on the 431 * child. The child must use this size, and guarantee that all of its 432 * descendants will fit within this size. 433 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 434 * child. The child must gurantee that it and all of its descendants will fit 435 * within this size. 436 * </ul> 437 * </p> 438 * 439 * <p> 440 * To intiate a layout, call {@link #requestLayout}. This method is typically 441 * called by a view on itself when it believes that is can no longer fit within 442 * its current bounds. 443 * </p> 444 * 445 * <a name="Drawing"></a> 446 * <h3>Drawing</h3> 447 * <p> 448 * Drawing is handled by walking the tree and rendering each view that 449 * intersects the invalid region. Because the tree is traversed in-order, 450 * this means that parents will draw before (i.e., behind) their children, with 451 * siblings drawn in the order they appear in the tree. 452 * If you set a background drawable for a View, then the View will draw it for you 453 * before calling back to its <code>onDraw()</code> method. 454 * </p> 455 * 456 * <p> 457 * Note that the framework will not draw views that are not in the invalid region. 458 * </p> 459 * 460 * <p> 461 * To force a view to draw, call {@link #invalidate()}. 462 * </p> 463 * 464 * <a name="EventHandlingThreading"></a> 465 * <h3>Event Handling and Threading</h3> 466 * <p> 467 * The basic cycle of a view is as follows: 468 * <ol> 469 * <li>An event comes in and is dispatched to the appropriate view. The view 470 * handles the event and notifies any listeners.</li> 471 * <li>If in the course of processing the event, the view's bounds may need 472 * to be changed, the view will call {@link #requestLayout()}.</li> 473 * <li>Similarly, if in the course of processing the event the view's appearance 474 * may need to be changed, the view will call {@link #invalidate()}.</li> 475 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 476 * the framework will take care of measuring, laying out, and drawing the tree 477 * as appropriate.</li> 478 * </ol> 479 * </p> 480 * 481 * <p><em>Note: The entire view tree is single threaded. You must always be on 482 * the UI thread when calling any method on any view.</em> 483 * If you are doing work on other threads and want to update the state of a view 484 * from that thread, you should use a {@link Handler}. 485 * </p> 486 * 487 * <a name="FocusHandling"></a> 488 * <h3>Focus Handling</h3> 489 * <p> 490 * The framework will handle routine focus movement in response to user input. 491 * This includes changing the focus as views are removed or hidden, or as new 492 * views become available. Views indicate their willingness to take focus 493 * through the {@link #isFocusable} method. To change whether a view can take 494 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 495 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 496 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 497 * </p> 498 * <p> 499 * Focus movement is based on an algorithm which finds the nearest neighbor in a 500 * given direction. In rare cases, the default algorithm may not match the 501 * intended behavior of the developer. In these situations, you can provide 502 * explicit overrides by using these XML attributes in the layout file: 503 * <pre> 504 * nextFocusDown 505 * nextFocusLeft 506 * nextFocusRight 507 * nextFocusUp 508 * </pre> 509 * </p> 510 * 511 * 512 * <p> 513 * To get a particular view to take focus, call {@link #requestFocus()}. 514 * </p> 515 * 516 * <a name="TouchMode"></a> 517 * <h3>Touch Mode</h3> 518 * <p> 519 * When a user is navigating a user interface via directional keys such as a D-pad, it is 520 * necessary to give focus to actionable items such as buttons so the user can see 521 * what will take input. If the device has touch capabilities, however, and the user 522 * begins interacting with the interface by touching it, it is no longer necessary to 523 * always highlight, or give focus to, a particular view. This motivates a mode 524 * for interaction named 'touch mode'. 525 * </p> 526 * <p> 527 * For a touch capable device, once the user touches the screen, the device 528 * will enter touch mode. From this point onward, only views for which 529 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 530 * Other views that are touchable, like buttons, will not take focus when touched; they will 531 * only fire the on click listeners. 532 * </p> 533 * <p> 534 * Any time a user hits a directional key, such as a D-pad direction, the view device will 535 * exit touch mode, and find a view to take focus, so that the user may resume interacting 536 * with the user interface without touching the screen again. 537 * </p> 538 * <p> 539 * The touch mode state is maintained across {@link android.app.Activity}s. Call 540 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 541 * </p> 542 * 543 * <a name="Scrolling"></a> 544 * <h3>Scrolling</h3> 545 * <p> 546 * The framework provides basic support for views that wish to internally 547 * scroll their content. This includes keeping track of the X and Y scroll 548 * offset as well as mechanisms for drawing scrollbars. See 549 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 550 * {@link #awakenScrollBars()} for more details. 551 * </p> 552 * 553 * <a name="Tags"></a> 554 * <h3>Tags</h3> 555 * <p> 556 * Unlike IDs, tags are not used to identify views. Tags are essentially an 557 * extra piece of information that can be associated with a view. They are most 558 * often used as a convenience to store data related to views in the views 559 * themselves rather than by putting them in a separate structure. 560 * </p> 561 * 562 * <a name="Properties"></a> 563 * <h3>Properties</h3> 564 * <p> 565 * The View class exposes an {@link #ALPHA} property, as well as several transform-related 566 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are 567 * available both in the {@link Property} form as well as in similarly-named setter/getter 568 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can 569 * be used to set persistent state associated with these rendering-related properties on the view. 570 * The properties and methods can also be used in conjunction with 571 * {@link android.animation.Animator Animator}-based animations, described more in the 572 * <a href="#Animation">Animation</a> section. 573 * </p> 574 * 575 * <a name="Animation"></a> 576 * <h3>Animation</h3> 577 * <p> 578 * Starting with Android 3.0, the preferred way of animating views is to use the 579 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based 580 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and 581 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0 582 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only 583 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class 584 * makes animating these View properties particularly easy and efficient. 585 * </p> 586 * <p> 587 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered. 588 * You can attach an {@link Animation} object to a view using 589 * {@link #setAnimation(Animation)} or 590 * {@link #startAnimation(Animation)}. The animation can alter the scale, 591 * rotation, translation and alpha of a view over time. If the animation is 592 * attached to a view that has children, the animation will affect the entire 593 * subtree rooted by that node. When an animation is started, the framework will 594 * take care of redrawing the appropriate views until the animation completes. 595 * </p> 596 * 597 * <a name="Security"></a> 598 * <h3>Security</h3> 599 * <p> 600 * Sometimes it is essential that an application be able to verify that an action 601 * is being performed with the full knowledge and consent of the user, such as 602 * granting a permission request, making a purchase or clicking on an advertisement. 603 * Unfortunately, a malicious application could try to spoof the user into 604 * performing these actions, unaware, by concealing the intended purpose of the view. 605 * As a remedy, the framework offers a touch filtering mechanism that can be used to 606 * improve the security of views that provide access to sensitive functionality. 607 * </p><p> 608 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 609 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 610 * will discard touches that are received whenever the view's window is obscured by 611 * another visible window. As a result, the view will not receive touches whenever a 612 * toast, dialog or other window appears above the view's window. 613 * </p><p> 614 * For more fine-grained control over security, consider overriding the 615 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 616 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 617 * </p> 618 * 619 * @attr ref android.R.styleable#View_alpha 620 * @attr ref android.R.styleable#View_background 621 * @attr ref android.R.styleable#View_clickable 622 * @attr ref android.R.styleable#View_contentDescription 623 * @attr ref android.R.styleable#View_drawingCacheQuality 624 * @attr ref android.R.styleable#View_duplicateParentState 625 * @attr ref android.R.styleable#View_id 626 * @attr ref android.R.styleable#View_requiresFadingEdge 627 * @attr ref android.R.styleable#View_fadeScrollbars 628 * @attr ref android.R.styleable#View_fadingEdgeLength 629 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 630 * @attr ref android.R.styleable#View_fitsSystemWindows 631 * @attr ref android.R.styleable#View_isScrollContainer 632 * @attr ref android.R.styleable#View_focusable 633 * @attr ref android.R.styleable#View_focusableInTouchMode 634 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 635 * @attr ref android.R.styleable#View_keepScreenOn 636 * @attr ref android.R.styleable#View_layerType 637 * @attr ref android.R.styleable#View_layoutDirection 638 * @attr ref android.R.styleable#View_longClickable 639 * @attr ref android.R.styleable#View_minHeight 640 * @attr ref android.R.styleable#View_minWidth 641 * @attr ref android.R.styleable#View_nextFocusDown 642 * @attr ref android.R.styleable#View_nextFocusLeft 643 * @attr ref android.R.styleable#View_nextFocusRight 644 * @attr ref android.R.styleable#View_nextFocusUp 645 * @attr ref android.R.styleable#View_onClick 646 * @attr ref android.R.styleable#View_padding 647 * @attr ref android.R.styleable#View_paddingBottom 648 * @attr ref android.R.styleable#View_paddingLeft 649 * @attr ref android.R.styleable#View_paddingRight 650 * @attr ref android.R.styleable#View_paddingTop 651 * @attr ref android.R.styleable#View_paddingStart 652 * @attr ref android.R.styleable#View_paddingEnd 653 * @attr ref android.R.styleable#View_saveEnabled 654 * @attr ref android.R.styleable#View_rotation 655 * @attr ref android.R.styleable#View_rotationX 656 * @attr ref android.R.styleable#View_rotationY 657 * @attr ref android.R.styleable#View_scaleX 658 * @attr ref android.R.styleable#View_scaleY 659 * @attr ref android.R.styleable#View_scrollX 660 * @attr ref android.R.styleable#View_scrollY 661 * @attr ref android.R.styleable#View_scrollbarSize 662 * @attr ref android.R.styleable#View_scrollbarStyle 663 * @attr ref android.R.styleable#View_scrollbars 664 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 665 * @attr ref android.R.styleable#View_scrollbarFadeDuration 666 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 667 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 668 * @attr ref android.R.styleable#View_scrollbarThumbVertical 669 * @attr ref android.R.styleable#View_scrollbarTrackVertical 670 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 671 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 672 * @attr ref android.R.styleable#View_stateListAnimator 673 * @attr ref android.R.styleable#View_viewName 674 * @attr ref android.R.styleable#View_soundEffectsEnabled 675 * @attr ref android.R.styleable#View_tag 676 * @attr ref android.R.styleable#View_textAlignment 677 * @attr ref android.R.styleable#View_textDirection 678 * @attr ref android.R.styleable#View_transformPivotX 679 * @attr ref android.R.styleable#View_transformPivotY 680 * @attr ref android.R.styleable#View_translationX 681 * @attr ref android.R.styleable#View_translationY 682 * @attr ref android.R.styleable#View_translationZ 683 * @attr ref android.R.styleable#View_visibility 684 * 685 * @see android.view.ViewGroup 686 */ 687public class View implements Drawable.Callback, KeyEvent.Callback, 688 AccessibilityEventSource { 689 private static final boolean DBG = false; 690 691 /** 692 * The logging tag used by this class with android.util.Log. 693 */ 694 protected static final String VIEW_LOG_TAG = "View"; 695 696 /** 697 * When set to true, apps will draw debugging information about their layouts. 698 * 699 * @hide 700 */ 701 public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout"; 702 703 /** 704 * Used to mark a View that has no ID. 705 */ 706 public static final int NO_ID = -1; 707 708 /** 709 * Signals that compatibility booleans have been initialized according to 710 * target SDK versions. 711 */ 712 private static boolean sCompatibilityDone = false; 713 714 /** 715 * Use the old (broken) way of building MeasureSpecs. 716 */ 717 private static boolean sUseBrokenMakeMeasureSpec = false; 718 719 /** 720 * Ignore any optimizations using the measure cache. 721 */ 722 private static boolean sIgnoreMeasureCache = false; 723 724 /** 725 * Ignore the clipBounds of this view for the children. 726 */ 727 static boolean sIgnoreClipBoundsForChildren = false; 728 729 /** 730 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 731 * calling setFlags. 732 */ 733 private static final int NOT_FOCUSABLE = 0x00000000; 734 735 /** 736 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 737 * setFlags. 738 */ 739 private static final int FOCUSABLE = 0x00000001; 740 741 /** 742 * Mask for use with setFlags indicating bits used for focus. 743 */ 744 private static final int FOCUSABLE_MASK = 0x00000001; 745 746 /** 747 * This view will adjust its padding to fit sytem windows (e.g. status bar) 748 */ 749 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 750 751 /** @hide */ 752 @IntDef({VISIBLE, INVISIBLE, GONE}) 753 @Retention(RetentionPolicy.SOURCE) 754 public @interface Visibility {} 755 756 /** 757 * This view is visible. 758 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 759 * android:visibility}. 760 */ 761 public static final int VISIBLE = 0x00000000; 762 763 /** 764 * This view is invisible, but it still takes up space for layout purposes. 765 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 766 * android:visibility}. 767 */ 768 public static final int INVISIBLE = 0x00000004; 769 770 /** 771 * This view is invisible, and it doesn't take any space for layout 772 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 773 * android:visibility}. 774 */ 775 public static final int GONE = 0x00000008; 776 777 /** 778 * Mask for use with setFlags indicating bits used for visibility. 779 * {@hide} 780 */ 781 static final int VISIBILITY_MASK = 0x0000000C; 782 783 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 784 785 /** 786 * This view is enabled. Interpretation varies by subclass. 787 * Use with ENABLED_MASK when calling setFlags. 788 * {@hide} 789 */ 790 static final int ENABLED = 0x00000000; 791 792 /** 793 * This view is disabled. Interpretation varies by subclass. 794 * Use with ENABLED_MASK when calling setFlags. 795 * {@hide} 796 */ 797 static final int DISABLED = 0x00000020; 798 799 /** 800 * Mask for use with setFlags indicating bits used for indicating whether 801 * this view is enabled 802 * {@hide} 803 */ 804 static final int ENABLED_MASK = 0x00000020; 805 806 /** 807 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 808 * called and further optimizations will be performed. It is okay to have 809 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 810 * {@hide} 811 */ 812 static final int WILL_NOT_DRAW = 0x00000080; 813 814 /** 815 * Mask for use with setFlags indicating bits used for indicating whether 816 * this view is will draw 817 * {@hide} 818 */ 819 static final int DRAW_MASK = 0x00000080; 820 821 /** 822 * <p>This view doesn't show scrollbars.</p> 823 * {@hide} 824 */ 825 static final int SCROLLBARS_NONE = 0x00000000; 826 827 /** 828 * <p>This view shows horizontal scrollbars.</p> 829 * {@hide} 830 */ 831 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 832 833 /** 834 * <p>This view shows vertical scrollbars.</p> 835 * {@hide} 836 */ 837 static final int SCROLLBARS_VERTICAL = 0x00000200; 838 839 /** 840 * <p>Mask for use with setFlags indicating bits used for indicating which 841 * scrollbars are enabled.</p> 842 * {@hide} 843 */ 844 static final int SCROLLBARS_MASK = 0x00000300; 845 846 /** 847 * Indicates that the view should filter touches when its window is obscured. 848 * Refer to the class comments for more information about this security feature. 849 * {@hide} 850 */ 851 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 852 853 /** 854 * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate 855 * that they are optional and should be skipped if the window has 856 * requested system UI flags that ignore those insets for layout. 857 */ 858 static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800; 859 860 /** 861 * <p>This view doesn't show fading edges.</p> 862 * {@hide} 863 */ 864 static final int FADING_EDGE_NONE = 0x00000000; 865 866 /** 867 * <p>This view shows horizontal fading edges.</p> 868 * {@hide} 869 */ 870 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 871 872 /** 873 * <p>This view shows vertical fading edges.</p> 874 * {@hide} 875 */ 876 static final int FADING_EDGE_VERTICAL = 0x00002000; 877 878 /** 879 * <p>Mask for use with setFlags indicating bits used for indicating which 880 * fading edges are enabled.</p> 881 * {@hide} 882 */ 883 static final int FADING_EDGE_MASK = 0x00003000; 884 885 /** 886 * <p>Indicates this view can be clicked. When clickable, a View reacts 887 * to clicks by notifying the OnClickListener.<p> 888 * {@hide} 889 */ 890 static final int CLICKABLE = 0x00004000; 891 892 /** 893 * <p>Indicates this view is caching its drawing into a bitmap.</p> 894 * {@hide} 895 */ 896 static final int DRAWING_CACHE_ENABLED = 0x00008000; 897 898 /** 899 * <p>Indicates that no icicle should be saved for this view.<p> 900 * {@hide} 901 */ 902 static final int SAVE_DISABLED = 0x000010000; 903 904 /** 905 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 906 * property.</p> 907 * {@hide} 908 */ 909 static final int SAVE_DISABLED_MASK = 0x000010000; 910 911 /** 912 * <p>Indicates that no drawing cache should ever be created for this view.<p> 913 * {@hide} 914 */ 915 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 916 917 /** 918 * <p>Indicates this view can take / keep focus when int touch mode.</p> 919 * {@hide} 920 */ 921 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 922 923 /** @hide */ 924 @Retention(RetentionPolicy.SOURCE) 925 @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO}) 926 public @interface DrawingCacheQuality {} 927 928 /** 929 * <p>Enables low quality mode for the drawing cache.</p> 930 */ 931 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 932 933 /** 934 * <p>Enables high quality mode for the drawing cache.</p> 935 */ 936 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 937 938 /** 939 * <p>Enables automatic quality mode for the drawing cache.</p> 940 */ 941 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 942 943 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 944 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 945 }; 946 947 /** 948 * <p>Mask for use with setFlags indicating bits used for the cache 949 * quality property.</p> 950 * {@hide} 951 */ 952 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 953 954 /** 955 * <p> 956 * Indicates this view can be long clicked. When long clickable, a View 957 * reacts to long clicks by notifying the OnLongClickListener or showing a 958 * context menu. 959 * </p> 960 * {@hide} 961 */ 962 static final int LONG_CLICKABLE = 0x00200000; 963 964 /** 965 * <p>Indicates that this view gets its drawable states from its direct parent 966 * and ignores its original internal states.</p> 967 * 968 * @hide 969 */ 970 static final int DUPLICATE_PARENT_STATE = 0x00400000; 971 972 /** @hide */ 973 @IntDef({ 974 SCROLLBARS_INSIDE_OVERLAY, 975 SCROLLBARS_INSIDE_INSET, 976 SCROLLBARS_OUTSIDE_OVERLAY, 977 SCROLLBARS_OUTSIDE_INSET 978 }) 979 @Retention(RetentionPolicy.SOURCE) 980 public @interface ScrollBarStyle {} 981 982 /** 983 * The scrollbar style to display the scrollbars inside the content area, 984 * without increasing the padding. The scrollbars will be overlaid with 985 * translucency on the view's content. 986 */ 987 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 988 989 /** 990 * The scrollbar style to display the scrollbars inside the padded area, 991 * increasing the padding of the view. The scrollbars will not overlap the 992 * content area of the view. 993 */ 994 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 995 996 /** 997 * The scrollbar style to display the scrollbars at the edge of the view, 998 * without increasing the padding. The scrollbars will be overlaid with 999 * translucency. 1000 */ 1001 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 1002 1003 /** 1004 * The scrollbar style to display the scrollbars at the edge of the view, 1005 * increasing the padding of the view. The scrollbars will only overlap the 1006 * background, if any. 1007 */ 1008 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 1009 1010 /** 1011 * Mask to check if the scrollbar style is overlay or inset. 1012 * {@hide} 1013 */ 1014 static final int SCROLLBARS_INSET_MASK = 0x01000000; 1015 1016 /** 1017 * Mask to check if the scrollbar style is inside or outside. 1018 * {@hide} 1019 */ 1020 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 1021 1022 /** 1023 * Mask for scrollbar style. 1024 * {@hide} 1025 */ 1026 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 1027 1028 /** 1029 * View flag indicating that the screen should remain on while the 1030 * window containing this view is visible to the user. This effectively 1031 * takes care of automatically setting the WindowManager's 1032 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 1033 */ 1034 public static final int KEEP_SCREEN_ON = 0x04000000; 1035 1036 /** 1037 * View flag indicating whether this view should have sound effects enabled 1038 * for events such as clicking and touching. 1039 */ 1040 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 1041 1042 /** 1043 * View flag indicating whether this view should have haptic feedback 1044 * enabled for events such as long presses. 1045 */ 1046 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 1047 1048 /** 1049 * <p>Indicates that the view hierarchy should stop saving state when 1050 * it reaches this view. If state saving is initiated immediately at 1051 * the view, it will be allowed. 1052 * {@hide} 1053 */ 1054 static final int PARENT_SAVE_DISABLED = 0x20000000; 1055 1056 /** 1057 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 1058 * {@hide} 1059 */ 1060 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 1061 1062 /** @hide */ 1063 @IntDef(flag = true, 1064 value = { 1065 FOCUSABLES_ALL, 1066 FOCUSABLES_TOUCH_MODE 1067 }) 1068 @Retention(RetentionPolicy.SOURCE) 1069 public @interface FocusableMode {} 1070 1071 /** 1072 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1073 * should add all focusable Views regardless if they are focusable in touch mode. 1074 */ 1075 public static final int FOCUSABLES_ALL = 0x00000000; 1076 1077 /** 1078 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1079 * should add only Views focusable in touch mode. 1080 */ 1081 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1082 1083 /** @hide */ 1084 @IntDef({ 1085 FOCUS_BACKWARD, 1086 FOCUS_FORWARD, 1087 FOCUS_LEFT, 1088 FOCUS_UP, 1089 FOCUS_RIGHT, 1090 FOCUS_DOWN 1091 }) 1092 @Retention(RetentionPolicy.SOURCE) 1093 public @interface FocusDirection {} 1094 1095 /** @hide */ 1096 @IntDef({ 1097 FOCUS_LEFT, 1098 FOCUS_UP, 1099 FOCUS_RIGHT, 1100 FOCUS_DOWN 1101 }) 1102 @Retention(RetentionPolicy.SOURCE) 1103 public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward 1104 1105 /** 1106 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1107 * item. 1108 */ 1109 public static final int FOCUS_BACKWARD = 0x00000001; 1110 1111 /** 1112 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1113 * item. 1114 */ 1115 public static final int FOCUS_FORWARD = 0x00000002; 1116 1117 /** 1118 * Use with {@link #focusSearch(int)}. Move focus to the left. 1119 */ 1120 public static final int FOCUS_LEFT = 0x00000011; 1121 1122 /** 1123 * Use with {@link #focusSearch(int)}. Move focus up. 1124 */ 1125 public static final int FOCUS_UP = 0x00000021; 1126 1127 /** 1128 * Use with {@link #focusSearch(int)}. Move focus to the right. 1129 */ 1130 public static final int FOCUS_RIGHT = 0x00000042; 1131 1132 /** 1133 * Use with {@link #focusSearch(int)}. Move focus down. 1134 */ 1135 public static final int FOCUS_DOWN = 0x00000082; 1136 1137 /** 1138 * Bits of {@link #getMeasuredWidthAndState()} and 1139 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1140 */ 1141 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1142 1143 /** 1144 * Bits of {@link #getMeasuredWidthAndState()} and 1145 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1146 */ 1147 public static final int MEASURED_STATE_MASK = 0xff000000; 1148 1149 /** 1150 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1151 * for functions that combine both width and height into a single int, 1152 * such as {@link #getMeasuredState()} and the childState argument of 1153 * {@link #resolveSizeAndState(int, int, int)}. 1154 */ 1155 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1156 1157 /** 1158 * Bit of {@link #getMeasuredWidthAndState()} and 1159 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1160 * is smaller that the space the view would like to have. 1161 */ 1162 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1163 1164 /** 1165 * Base View state sets 1166 */ 1167 // Singles 1168 /** 1169 * Indicates the view has no states set. States are used with 1170 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1171 * view depending on its state. 1172 * 1173 * @see android.graphics.drawable.Drawable 1174 * @see #getDrawableState() 1175 */ 1176 protected static final int[] EMPTY_STATE_SET; 1177 /** 1178 * Indicates the view is enabled. States are used with 1179 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1180 * view depending on its state. 1181 * 1182 * @see android.graphics.drawable.Drawable 1183 * @see #getDrawableState() 1184 */ 1185 protected static final int[] ENABLED_STATE_SET; 1186 /** 1187 * Indicates the view is focused. States are used with 1188 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1189 * view depending on its state. 1190 * 1191 * @see android.graphics.drawable.Drawable 1192 * @see #getDrawableState() 1193 */ 1194 protected static final int[] FOCUSED_STATE_SET; 1195 /** 1196 * Indicates the view is selected. States are used with 1197 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1198 * view depending on its state. 1199 * 1200 * @see android.graphics.drawable.Drawable 1201 * @see #getDrawableState() 1202 */ 1203 protected static final int[] SELECTED_STATE_SET; 1204 /** 1205 * Indicates the view is pressed. States are used with 1206 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1207 * view depending on its state. 1208 * 1209 * @see android.graphics.drawable.Drawable 1210 * @see #getDrawableState() 1211 */ 1212 protected static final int[] PRESSED_STATE_SET; 1213 /** 1214 * Indicates the view's window has focus. States are used with 1215 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1216 * view depending on its state. 1217 * 1218 * @see android.graphics.drawable.Drawable 1219 * @see #getDrawableState() 1220 */ 1221 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1222 // Doubles 1223 /** 1224 * Indicates the view is enabled and has the focus. 1225 * 1226 * @see #ENABLED_STATE_SET 1227 * @see #FOCUSED_STATE_SET 1228 */ 1229 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1230 /** 1231 * Indicates the view is enabled and selected. 1232 * 1233 * @see #ENABLED_STATE_SET 1234 * @see #SELECTED_STATE_SET 1235 */ 1236 protected static final int[] ENABLED_SELECTED_STATE_SET; 1237 /** 1238 * Indicates the view is enabled and that its window has focus. 1239 * 1240 * @see #ENABLED_STATE_SET 1241 * @see #WINDOW_FOCUSED_STATE_SET 1242 */ 1243 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1244 /** 1245 * Indicates the view is focused and selected. 1246 * 1247 * @see #FOCUSED_STATE_SET 1248 * @see #SELECTED_STATE_SET 1249 */ 1250 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1251 /** 1252 * Indicates the view has the focus and that its window has the focus. 1253 * 1254 * @see #FOCUSED_STATE_SET 1255 * @see #WINDOW_FOCUSED_STATE_SET 1256 */ 1257 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1258 /** 1259 * Indicates the view is selected and that its window has the focus. 1260 * 1261 * @see #SELECTED_STATE_SET 1262 * @see #WINDOW_FOCUSED_STATE_SET 1263 */ 1264 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1265 // Triples 1266 /** 1267 * Indicates the view is enabled, focused and selected. 1268 * 1269 * @see #ENABLED_STATE_SET 1270 * @see #FOCUSED_STATE_SET 1271 * @see #SELECTED_STATE_SET 1272 */ 1273 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1274 /** 1275 * Indicates the view is enabled, focused and its window has the focus. 1276 * 1277 * @see #ENABLED_STATE_SET 1278 * @see #FOCUSED_STATE_SET 1279 * @see #WINDOW_FOCUSED_STATE_SET 1280 */ 1281 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1282 /** 1283 * Indicates the view is enabled, selected and its window has the focus. 1284 * 1285 * @see #ENABLED_STATE_SET 1286 * @see #SELECTED_STATE_SET 1287 * @see #WINDOW_FOCUSED_STATE_SET 1288 */ 1289 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1290 /** 1291 * Indicates the view is focused, selected and its window has the focus. 1292 * 1293 * @see #FOCUSED_STATE_SET 1294 * @see #SELECTED_STATE_SET 1295 * @see #WINDOW_FOCUSED_STATE_SET 1296 */ 1297 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1298 /** 1299 * Indicates the view is enabled, focused, selected and its window 1300 * has the focus. 1301 * 1302 * @see #ENABLED_STATE_SET 1303 * @see #FOCUSED_STATE_SET 1304 * @see #SELECTED_STATE_SET 1305 * @see #WINDOW_FOCUSED_STATE_SET 1306 */ 1307 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1308 /** 1309 * Indicates the view is pressed and its window has the focus. 1310 * 1311 * @see #PRESSED_STATE_SET 1312 * @see #WINDOW_FOCUSED_STATE_SET 1313 */ 1314 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1315 /** 1316 * Indicates the view is pressed and selected. 1317 * 1318 * @see #PRESSED_STATE_SET 1319 * @see #SELECTED_STATE_SET 1320 */ 1321 protected static final int[] PRESSED_SELECTED_STATE_SET; 1322 /** 1323 * Indicates the view is pressed, selected and its window has the focus. 1324 * 1325 * @see #PRESSED_STATE_SET 1326 * @see #SELECTED_STATE_SET 1327 * @see #WINDOW_FOCUSED_STATE_SET 1328 */ 1329 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1330 /** 1331 * Indicates the view is pressed and focused. 1332 * 1333 * @see #PRESSED_STATE_SET 1334 * @see #FOCUSED_STATE_SET 1335 */ 1336 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1337 /** 1338 * Indicates the view is pressed, focused and its window has the focus. 1339 * 1340 * @see #PRESSED_STATE_SET 1341 * @see #FOCUSED_STATE_SET 1342 * @see #WINDOW_FOCUSED_STATE_SET 1343 */ 1344 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1345 /** 1346 * Indicates the view is pressed, focused and selected. 1347 * 1348 * @see #PRESSED_STATE_SET 1349 * @see #SELECTED_STATE_SET 1350 * @see #FOCUSED_STATE_SET 1351 */ 1352 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1353 /** 1354 * Indicates the view is pressed, focused, selected and its window has the focus. 1355 * 1356 * @see #PRESSED_STATE_SET 1357 * @see #FOCUSED_STATE_SET 1358 * @see #SELECTED_STATE_SET 1359 * @see #WINDOW_FOCUSED_STATE_SET 1360 */ 1361 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1362 /** 1363 * Indicates the view is pressed and enabled. 1364 * 1365 * @see #PRESSED_STATE_SET 1366 * @see #ENABLED_STATE_SET 1367 */ 1368 protected static final int[] PRESSED_ENABLED_STATE_SET; 1369 /** 1370 * Indicates the view is pressed, enabled and its window has the focus. 1371 * 1372 * @see #PRESSED_STATE_SET 1373 * @see #ENABLED_STATE_SET 1374 * @see #WINDOW_FOCUSED_STATE_SET 1375 */ 1376 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1377 /** 1378 * Indicates the view is pressed, enabled and selected. 1379 * 1380 * @see #PRESSED_STATE_SET 1381 * @see #ENABLED_STATE_SET 1382 * @see #SELECTED_STATE_SET 1383 */ 1384 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1385 /** 1386 * Indicates the view is pressed, enabled, selected and its window has the 1387 * focus. 1388 * 1389 * @see #PRESSED_STATE_SET 1390 * @see #ENABLED_STATE_SET 1391 * @see #SELECTED_STATE_SET 1392 * @see #WINDOW_FOCUSED_STATE_SET 1393 */ 1394 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1395 /** 1396 * Indicates the view is pressed, enabled and focused. 1397 * 1398 * @see #PRESSED_STATE_SET 1399 * @see #ENABLED_STATE_SET 1400 * @see #FOCUSED_STATE_SET 1401 */ 1402 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1403 /** 1404 * Indicates the view is pressed, enabled, focused and its window has the 1405 * focus. 1406 * 1407 * @see #PRESSED_STATE_SET 1408 * @see #ENABLED_STATE_SET 1409 * @see #FOCUSED_STATE_SET 1410 * @see #WINDOW_FOCUSED_STATE_SET 1411 */ 1412 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1413 /** 1414 * Indicates the view is pressed, enabled, focused and selected. 1415 * 1416 * @see #PRESSED_STATE_SET 1417 * @see #ENABLED_STATE_SET 1418 * @see #SELECTED_STATE_SET 1419 * @see #FOCUSED_STATE_SET 1420 */ 1421 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1422 /** 1423 * Indicates the view is pressed, enabled, focused, selected and its window 1424 * has the focus. 1425 * 1426 * @see #PRESSED_STATE_SET 1427 * @see #ENABLED_STATE_SET 1428 * @see #SELECTED_STATE_SET 1429 * @see #FOCUSED_STATE_SET 1430 * @see #WINDOW_FOCUSED_STATE_SET 1431 */ 1432 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1433 1434 /** 1435 * The order here is very important to {@link #getDrawableState()} 1436 */ 1437 private static final int[][] VIEW_STATE_SETS; 1438 1439 static final int VIEW_STATE_WINDOW_FOCUSED = 1; 1440 static final int VIEW_STATE_SELECTED = 1 << 1; 1441 static final int VIEW_STATE_FOCUSED = 1 << 2; 1442 static final int VIEW_STATE_ENABLED = 1 << 3; 1443 static final int VIEW_STATE_PRESSED = 1 << 4; 1444 static final int VIEW_STATE_ACTIVATED = 1 << 5; 1445 static final int VIEW_STATE_ACCELERATED = 1 << 6; 1446 static final int VIEW_STATE_HOVERED = 1 << 7; 1447 static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8; 1448 static final int VIEW_STATE_DRAG_HOVERED = 1 << 9; 1449 1450 static final int[] VIEW_STATE_IDS = new int[] { 1451 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED, 1452 R.attr.state_selected, VIEW_STATE_SELECTED, 1453 R.attr.state_focused, VIEW_STATE_FOCUSED, 1454 R.attr.state_enabled, VIEW_STATE_ENABLED, 1455 R.attr.state_pressed, VIEW_STATE_PRESSED, 1456 R.attr.state_activated, VIEW_STATE_ACTIVATED, 1457 R.attr.state_accelerated, VIEW_STATE_ACCELERATED, 1458 R.attr.state_hovered, VIEW_STATE_HOVERED, 1459 R.attr.state_drag_can_accept, VIEW_STATE_DRAG_CAN_ACCEPT, 1460 R.attr.state_drag_hovered, VIEW_STATE_DRAG_HOVERED 1461 }; 1462 1463 static { 1464 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) { 1465 throw new IllegalStateException( 1466 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array"); 1467 } 1468 int[] orderedIds = new int[VIEW_STATE_IDS.length]; 1469 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) { 1470 int viewState = R.styleable.ViewDrawableStates[i]; 1471 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) { 1472 if (VIEW_STATE_IDS[j] == viewState) { 1473 orderedIds[i * 2] = viewState; 1474 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1]; 1475 } 1476 } 1477 } 1478 final int NUM_BITS = VIEW_STATE_IDS.length / 2; 1479 VIEW_STATE_SETS = new int[1 << NUM_BITS][]; 1480 for (int i = 0; i < VIEW_STATE_SETS.length; i++) { 1481 int numBits = Integer.bitCount(i); 1482 int[] set = new int[numBits]; 1483 int pos = 0; 1484 for (int j = 0; j < orderedIds.length; j += 2) { 1485 if ((i & orderedIds[j+1]) != 0) { 1486 set[pos++] = orderedIds[j]; 1487 } 1488 } 1489 VIEW_STATE_SETS[i] = set; 1490 } 1491 1492 EMPTY_STATE_SET = VIEW_STATE_SETS[0]; 1493 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED]; 1494 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED]; 1495 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1496 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED]; 1497 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED]; 1498 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1499 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED]; 1500 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1501 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED]; 1502 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1503 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1504 | VIEW_STATE_FOCUSED]; 1505 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED]; 1506 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1507 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED]; 1508 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1509 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED]; 1510 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1511 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1512 | VIEW_STATE_ENABLED]; 1513 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1514 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED]; 1515 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1516 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1517 | VIEW_STATE_ENABLED]; 1518 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1519 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1520 | VIEW_STATE_ENABLED]; 1521 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1522 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1523 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED]; 1524 1525 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED]; 1526 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1527 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED]; 1528 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1529 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED]; 1530 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1531 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1532 | VIEW_STATE_PRESSED]; 1533 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1534 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1535 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1536 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1537 | VIEW_STATE_PRESSED]; 1538 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1539 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1540 | VIEW_STATE_PRESSED]; 1541 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1542 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1543 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1544 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[ 1545 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1546 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1547 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED 1548 | VIEW_STATE_PRESSED]; 1549 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1550 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED 1551 | VIEW_STATE_PRESSED]; 1552 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1553 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1554 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1555 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1556 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED 1557 | VIEW_STATE_PRESSED]; 1558 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1559 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1560 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1561 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1562 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1563 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1564 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1565 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1566 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED 1567 | VIEW_STATE_PRESSED]; 1568 } 1569 1570 /** 1571 * Accessibility event types that are dispatched for text population. 1572 */ 1573 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 1574 AccessibilityEvent.TYPE_VIEW_CLICKED 1575 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 1576 | AccessibilityEvent.TYPE_VIEW_SELECTED 1577 | AccessibilityEvent.TYPE_VIEW_FOCUSED 1578 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 1579 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 1580 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 1581 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 1582 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED 1583 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED 1584 | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY; 1585 1586 /** 1587 * Temporary Rect currently for use in setBackground(). This will probably 1588 * be extended in the future to hold our own class with more than just 1589 * a Rect. :) 1590 */ 1591 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1592 1593 /** 1594 * Map used to store views' tags. 1595 */ 1596 private SparseArray<Object> mKeyedTags; 1597 1598 /** 1599 * The next available accessibility id. 1600 */ 1601 private static int sNextAccessibilityViewId; 1602 1603 /** 1604 * The animation currently associated with this view. 1605 * @hide 1606 */ 1607 protected Animation mCurrentAnimation = null; 1608 1609 /** 1610 * Width as measured during measure pass. 1611 * {@hide} 1612 */ 1613 @ViewDebug.ExportedProperty(category = "measurement") 1614 int mMeasuredWidth; 1615 1616 /** 1617 * Height as measured during measure pass. 1618 * {@hide} 1619 */ 1620 @ViewDebug.ExportedProperty(category = "measurement") 1621 int mMeasuredHeight; 1622 1623 /** 1624 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1625 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1626 * its display list. This flag, used only when hw accelerated, allows us to clear the 1627 * flag while retaining this information until it's needed (at getDisplayList() time and 1628 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1629 * 1630 * {@hide} 1631 */ 1632 boolean mRecreateDisplayList = false; 1633 1634 /** 1635 * The view's identifier. 1636 * {@hide} 1637 * 1638 * @see #setId(int) 1639 * @see #getId() 1640 */ 1641 @ViewDebug.ExportedProperty(resolveId = true) 1642 int mID = NO_ID; 1643 1644 /** 1645 * The stable ID of this view for accessibility purposes. 1646 */ 1647 int mAccessibilityViewId = NO_ID; 1648 1649 private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 1650 1651 SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent; 1652 1653 /** 1654 * The view's tag. 1655 * {@hide} 1656 * 1657 * @see #setTag(Object) 1658 * @see #getTag() 1659 */ 1660 protected Object mTag = null; 1661 1662 // for mPrivateFlags: 1663 /** {@hide} */ 1664 static final int PFLAG_WANTS_FOCUS = 0x00000001; 1665 /** {@hide} */ 1666 static final int PFLAG_FOCUSED = 0x00000002; 1667 /** {@hide} */ 1668 static final int PFLAG_SELECTED = 0x00000004; 1669 /** {@hide} */ 1670 static final int PFLAG_IS_ROOT_NAMESPACE = 0x00000008; 1671 /** {@hide} */ 1672 static final int PFLAG_HAS_BOUNDS = 0x00000010; 1673 /** {@hide} */ 1674 static final int PFLAG_DRAWN = 0x00000020; 1675 /** 1676 * When this flag is set, this view is running an animation on behalf of its 1677 * children and should therefore not cancel invalidate requests, even if they 1678 * lie outside of this view's bounds. 1679 * 1680 * {@hide} 1681 */ 1682 static final int PFLAG_DRAW_ANIMATION = 0x00000040; 1683 /** {@hide} */ 1684 static final int PFLAG_SKIP_DRAW = 0x00000080; 1685 /** {@hide} */ 1686 static final int PFLAG_ONLY_DRAWS_BACKGROUND = 0x00000100; 1687 /** {@hide} */ 1688 static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1689 /** {@hide} */ 1690 static final int PFLAG_DRAWABLE_STATE_DIRTY = 0x00000400; 1691 /** {@hide} */ 1692 static final int PFLAG_MEASURED_DIMENSION_SET = 0x00000800; 1693 /** {@hide} */ 1694 static final int PFLAG_FORCE_LAYOUT = 0x00001000; 1695 /** {@hide} */ 1696 static final int PFLAG_LAYOUT_REQUIRED = 0x00002000; 1697 1698 private static final int PFLAG_PRESSED = 0x00004000; 1699 1700 /** {@hide} */ 1701 static final int PFLAG_DRAWING_CACHE_VALID = 0x00008000; 1702 /** 1703 * Flag used to indicate that this view should be drawn once more (and only once 1704 * more) after its animation has completed. 1705 * {@hide} 1706 */ 1707 static final int PFLAG_ANIMATION_STARTED = 0x00010000; 1708 1709 private static final int PFLAG_SAVE_STATE_CALLED = 0x00020000; 1710 1711 /** 1712 * Indicates that the View returned true when onSetAlpha() was called and that 1713 * the alpha must be restored. 1714 * {@hide} 1715 */ 1716 static final int PFLAG_ALPHA_SET = 0x00040000; 1717 1718 /** 1719 * Set by {@link #setScrollContainer(boolean)}. 1720 */ 1721 static final int PFLAG_SCROLL_CONTAINER = 0x00080000; 1722 1723 /** 1724 * Set by {@link #setScrollContainer(boolean)}. 1725 */ 1726 static final int PFLAG_SCROLL_CONTAINER_ADDED = 0x00100000; 1727 1728 /** 1729 * View flag indicating whether this view was invalidated (fully or partially.) 1730 * 1731 * @hide 1732 */ 1733 static final int PFLAG_DIRTY = 0x00200000; 1734 1735 /** 1736 * View flag indicating whether this view was invalidated by an opaque 1737 * invalidate request. 1738 * 1739 * @hide 1740 */ 1741 static final int PFLAG_DIRTY_OPAQUE = 0x00400000; 1742 1743 /** 1744 * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}. 1745 * 1746 * @hide 1747 */ 1748 static final int PFLAG_DIRTY_MASK = 0x00600000; 1749 1750 /** 1751 * Indicates whether the background is opaque. 1752 * 1753 * @hide 1754 */ 1755 static final int PFLAG_OPAQUE_BACKGROUND = 0x00800000; 1756 1757 /** 1758 * Indicates whether the scrollbars are opaque. 1759 * 1760 * @hide 1761 */ 1762 static final int PFLAG_OPAQUE_SCROLLBARS = 0x01000000; 1763 1764 /** 1765 * Indicates whether the view is opaque. 1766 * 1767 * @hide 1768 */ 1769 static final int PFLAG_OPAQUE_MASK = 0x01800000; 1770 1771 /** 1772 * Indicates a prepressed state; 1773 * the short time between ACTION_DOWN and recognizing 1774 * a 'real' press. Prepressed is used to recognize quick taps 1775 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1776 * 1777 * @hide 1778 */ 1779 private static final int PFLAG_PREPRESSED = 0x02000000; 1780 1781 /** 1782 * Indicates whether the view is temporarily detached. 1783 * 1784 * @hide 1785 */ 1786 static final int PFLAG_CANCEL_NEXT_UP_EVENT = 0x04000000; 1787 1788 /** 1789 * Indicates that we should awaken scroll bars once attached 1790 * 1791 * @hide 1792 */ 1793 private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1794 1795 /** 1796 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1797 * @hide 1798 */ 1799 private static final int PFLAG_HOVERED = 0x10000000; 1800 1801 /** 1802 * no longer needed, should be reused 1803 */ 1804 private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000; 1805 1806 /** {@hide} */ 1807 static final int PFLAG_ACTIVATED = 0x40000000; 1808 1809 /** 1810 * Indicates that this view was specifically invalidated, not just dirtied because some 1811 * child view was invalidated. The flag is used to determine when we need to recreate 1812 * a view's display list (as opposed to just returning a reference to its existing 1813 * display list). 1814 * 1815 * @hide 1816 */ 1817 static final int PFLAG_INVALIDATED = 0x80000000; 1818 1819 /** 1820 * Masks for mPrivateFlags2, as generated by dumpFlags(): 1821 * 1822 * |-------|-------|-------|-------| 1823 * 1 PFLAG2_DRAG_CAN_ACCEPT 1824 * 1 PFLAG2_DRAG_HOVERED 1825 * 11 PFLAG2_LAYOUT_DIRECTION_MASK 1826 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL 1827 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED 1828 * 11 PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK 1829 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[1] 1830 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[2] 1831 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[3] 1832 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[4] 1833 * 1 1 PFLAG2_TEXT_DIRECTION_FLAGS[5] 1834 * 111 PFLAG2_TEXT_DIRECTION_MASK 1835 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED 1836 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT 1837 * 111 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK 1838 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[1] 1839 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[2] 1840 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[3] 1841 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[4] 1842 * 1 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[5] 1843 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[6] 1844 * 111 PFLAG2_TEXT_ALIGNMENT_MASK 1845 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED 1846 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT 1847 * 111 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK 1848 * 111 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK 1849 * 11 PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK 1850 * 1 PFLAG2_ACCESSIBILITY_FOCUSED 1851 * 1 PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED 1852 * 1 PFLAG2_VIEW_QUICK_REJECTED 1853 * 1 PFLAG2_PADDING_RESOLVED 1854 * 1 PFLAG2_DRAWABLE_RESOLVED 1855 * 1 PFLAG2_HAS_TRANSIENT_STATE 1856 * |-------|-------|-------|-------| 1857 */ 1858 1859 /** 1860 * Indicates that this view has reported that it can accept the current drag's content. 1861 * Cleared when the drag operation concludes. 1862 * @hide 1863 */ 1864 static final int PFLAG2_DRAG_CAN_ACCEPT = 0x00000001; 1865 1866 /** 1867 * Indicates that this view is currently directly under the drag location in a 1868 * drag-and-drop operation involving content that it can accept. Cleared when 1869 * the drag exits the view, or when the drag operation concludes. 1870 * @hide 1871 */ 1872 static final int PFLAG2_DRAG_HOVERED = 0x00000002; 1873 1874 /** @hide */ 1875 @IntDef({ 1876 LAYOUT_DIRECTION_LTR, 1877 LAYOUT_DIRECTION_RTL, 1878 LAYOUT_DIRECTION_INHERIT, 1879 LAYOUT_DIRECTION_LOCALE 1880 }) 1881 @Retention(RetentionPolicy.SOURCE) 1882 // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection 1883 public @interface LayoutDir {} 1884 1885 /** @hide */ 1886 @IntDef({ 1887 LAYOUT_DIRECTION_LTR, 1888 LAYOUT_DIRECTION_RTL 1889 }) 1890 @Retention(RetentionPolicy.SOURCE) 1891 public @interface ResolvedLayoutDir {} 1892 1893 /** 1894 * Horizontal layout direction of this view is from Left to Right. 1895 * Use with {@link #setLayoutDirection}. 1896 */ 1897 public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR; 1898 1899 /** 1900 * Horizontal layout direction of this view is from Right to Left. 1901 * Use with {@link #setLayoutDirection}. 1902 */ 1903 public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL; 1904 1905 /** 1906 * Horizontal layout direction of this view is inherited from its parent. 1907 * Use with {@link #setLayoutDirection}. 1908 */ 1909 public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT; 1910 1911 /** 1912 * Horizontal layout direction of this view is from deduced from the default language 1913 * script for the locale. Use with {@link #setLayoutDirection}. 1914 */ 1915 public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE; 1916 1917 /** 1918 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1919 * @hide 1920 */ 1921 static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2; 1922 1923 /** 1924 * Mask for use with private flags indicating bits used for horizontal layout direction. 1925 * @hide 1926 */ 1927 static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1928 1929 /** 1930 * Indicates whether the view horizontal layout direction has been resolved and drawn to the 1931 * right-to-left direction. 1932 * @hide 1933 */ 1934 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1935 1936 /** 1937 * Indicates whether the view horizontal layout direction has been resolved. 1938 * @hide 1939 */ 1940 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1941 1942 /** 1943 * Mask for use with private flags indicating bits used for resolved horizontal layout direction. 1944 * @hide 1945 */ 1946 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C 1947 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1948 1949 /* 1950 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct 1951 * flag value. 1952 * @hide 1953 */ 1954 private static final int[] LAYOUT_DIRECTION_FLAGS = { 1955 LAYOUT_DIRECTION_LTR, 1956 LAYOUT_DIRECTION_RTL, 1957 LAYOUT_DIRECTION_INHERIT, 1958 LAYOUT_DIRECTION_LOCALE 1959 }; 1960 1961 /** 1962 * Default horizontal layout direction. 1963 */ 1964 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 1965 1966 /** 1967 * Default horizontal layout direction. 1968 * @hide 1969 */ 1970 static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR; 1971 1972 /** 1973 * Text direction is inherited thru {@link ViewGroup} 1974 */ 1975 public static final int TEXT_DIRECTION_INHERIT = 0; 1976 1977 /** 1978 * Text direction is using "first strong algorithm". The first strong directional character 1979 * determines the paragraph direction. If there is no strong directional character, the 1980 * paragraph direction is the view's resolved layout direction. 1981 */ 1982 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 1983 1984 /** 1985 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 1986 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 1987 * If there are neither, the paragraph direction is the view's resolved layout direction. 1988 */ 1989 public static final int TEXT_DIRECTION_ANY_RTL = 2; 1990 1991 /** 1992 * Text direction is forced to LTR. 1993 */ 1994 public static final int TEXT_DIRECTION_LTR = 3; 1995 1996 /** 1997 * Text direction is forced to RTL. 1998 */ 1999 public static final int TEXT_DIRECTION_RTL = 4; 2000 2001 /** 2002 * Text direction is coming from the system Locale. 2003 */ 2004 public static final int TEXT_DIRECTION_LOCALE = 5; 2005 2006 /** 2007 * Default text direction is inherited 2008 */ 2009 private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT; 2010 2011 /** 2012 * Default resolved text direction 2013 * @hide 2014 */ 2015 static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG; 2016 2017 /** 2018 * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED) 2019 * @hide 2020 */ 2021 static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6; 2022 2023 /** 2024 * Mask for use with private flags indicating bits used for text direction. 2025 * @hide 2026 */ 2027 static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007 2028 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2029 2030 /** 2031 * Array of text direction flags for mapping attribute "textDirection" to correct 2032 * flag value. 2033 * @hide 2034 */ 2035 private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = { 2036 TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2037 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2038 TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2039 TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2040 TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2041 TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT 2042 }; 2043 2044 /** 2045 * Indicates whether the view text direction has been resolved. 2046 * @hide 2047 */ 2048 static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008 2049 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2050 2051 /** 2052 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2053 * @hide 2054 */ 2055 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10; 2056 2057 /** 2058 * Mask for use with private flags indicating bits used for resolved text direction. 2059 * @hide 2060 */ 2061 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 2062 << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2063 2064 /** 2065 * Indicates whether the view text direction has been resolved to the "first strong" heuristic. 2066 * @hide 2067 */ 2068 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT = 2069 TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2070 2071 /** @hide */ 2072 @IntDef({ 2073 TEXT_ALIGNMENT_INHERIT, 2074 TEXT_ALIGNMENT_GRAVITY, 2075 TEXT_ALIGNMENT_CENTER, 2076 TEXT_ALIGNMENT_TEXT_START, 2077 TEXT_ALIGNMENT_TEXT_END, 2078 TEXT_ALIGNMENT_VIEW_START, 2079 TEXT_ALIGNMENT_VIEW_END 2080 }) 2081 @Retention(RetentionPolicy.SOURCE) 2082 public @interface TextAlignment {} 2083 2084 /** 2085 * Default text alignment. The text alignment of this View is inherited from its parent. 2086 * Use with {@link #setTextAlignment(int)} 2087 */ 2088 public static final int TEXT_ALIGNMENT_INHERIT = 0; 2089 2090 /** 2091 * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL, 2092 * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction. 2093 * 2094 * Use with {@link #setTextAlignment(int)} 2095 */ 2096 public static final int TEXT_ALIGNMENT_GRAVITY = 1; 2097 2098 /** 2099 * Align to the start of the paragraph, e.g. ALIGN_NORMAL. 2100 * 2101 * Use with {@link #setTextAlignment(int)} 2102 */ 2103 public static final int TEXT_ALIGNMENT_TEXT_START = 2; 2104 2105 /** 2106 * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE. 2107 * 2108 * Use with {@link #setTextAlignment(int)} 2109 */ 2110 public static final int TEXT_ALIGNMENT_TEXT_END = 3; 2111 2112 /** 2113 * Center the paragraph, e.g. ALIGN_CENTER. 2114 * 2115 * Use with {@link #setTextAlignment(int)} 2116 */ 2117 public static final int TEXT_ALIGNMENT_CENTER = 4; 2118 2119 /** 2120 * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved 2121 * layoutDirection is LTR, and ALIGN_RIGHT otherwise. 2122 * 2123 * Use with {@link #setTextAlignment(int)} 2124 */ 2125 public static final int TEXT_ALIGNMENT_VIEW_START = 5; 2126 2127 /** 2128 * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved 2129 * layoutDirection is LTR, and ALIGN_LEFT otherwise. 2130 * 2131 * Use with {@link #setTextAlignment(int)} 2132 */ 2133 public static final int TEXT_ALIGNMENT_VIEW_END = 6; 2134 2135 /** 2136 * Default text alignment is inherited 2137 */ 2138 private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2139 2140 /** 2141 * Default resolved text alignment 2142 * @hide 2143 */ 2144 static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2145 2146 /** 2147 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2148 * @hide 2149 */ 2150 static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13; 2151 2152 /** 2153 * Mask for use with private flags indicating bits used for text alignment. 2154 * @hide 2155 */ 2156 static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2157 2158 /** 2159 * Array of text direction flags for mapping attribute "textAlignment" to correct 2160 * flag value. 2161 * @hide 2162 */ 2163 private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = { 2164 TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2165 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2166 TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2167 TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2168 TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2169 TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2170 TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 2171 }; 2172 2173 /** 2174 * Indicates whether the view text alignment has been resolved. 2175 * @hide 2176 */ 2177 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2178 2179 /** 2180 * Bit shift to get the resolved text alignment. 2181 * @hide 2182 */ 2183 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17; 2184 2185 /** 2186 * Mask for use with private flags indicating bits used for text alignment. 2187 * @hide 2188 */ 2189 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 2190 << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2191 2192 /** 2193 * Indicates whether if the view text alignment has been resolved to gravity 2194 */ 2195 private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT = 2196 TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2197 2198 // Accessiblity constants for mPrivateFlags2 2199 2200 /** 2201 * Shift for the bits in {@link #mPrivateFlags2} related to the 2202 * "importantForAccessibility" attribute. 2203 */ 2204 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20; 2205 2206 /** 2207 * Automatically determine whether a view is important for accessibility. 2208 */ 2209 public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000; 2210 2211 /** 2212 * The view is important for accessibility. 2213 */ 2214 public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001; 2215 2216 /** 2217 * The view is not important for accessibility. 2218 */ 2219 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002; 2220 2221 /** 2222 * The view is not important for accessibility, nor are any of its 2223 * descendant views. 2224 */ 2225 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004; 2226 2227 /** 2228 * The default whether the view is important for accessibility. 2229 */ 2230 static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO; 2231 2232 /** 2233 * Mask for obtainig the bits which specify how to determine 2234 * whether a view is important for accessibility. 2235 */ 2236 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO 2237 | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO 2238 | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) 2239 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2240 2241 /** 2242 * Shift for the bits in {@link #mPrivateFlags2} related to the 2243 * "accessibilityLiveRegion" attribute. 2244 */ 2245 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23; 2246 2247 /** 2248 * Live region mode specifying that accessibility services should not 2249 * automatically announce changes to this view. This is the default live 2250 * region mode for most views. 2251 * <p> 2252 * Use with {@link #setAccessibilityLiveRegion(int)}. 2253 */ 2254 public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000; 2255 2256 /** 2257 * Live region mode specifying that accessibility services should announce 2258 * changes to this view. 2259 * <p> 2260 * Use with {@link #setAccessibilityLiveRegion(int)}. 2261 */ 2262 public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001; 2263 2264 /** 2265 * Live region mode specifying that accessibility services should interrupt 2266 * ongoing speech to immediately announce changes to this view. 2267 * <p> 2268 * Use with {@link #setAccessibilityLiveRegion(int)}. 2269 */ 2270 public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002; 2271 2272 /** 2273 * The default whether the view is important for accessibility. 2274 */ 2275 static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE; 2276 2277 /** 2278 * Mask for obtaining the bits which specify a view's accessibility live 2279 * region mode. 2280 */ 2281 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE 2282 | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE) 2283 << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 2284 2285 /** 2286 * Flag indicating whether a view has accessibility focus. 2287 */ 2288 static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000; 2289 2290 /** 2291 * Flag whether the accessibility state of the subtree rooted at this view changed. 2292 */ 2293 static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000; 2294 2295 /** 2296 * Flag indicating whether a view failed the quickReject() check in draw(). This condition 2297 * is used to check whether later changes to the view's transform should invalidate the 2298 * view to force the quickReject test to run again. 2299 */ 2300 static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000; 2301 2302 /** 2303 * Flag indicating that start/end padding has been resolved into left/right padding 2304 * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()} 2305 * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved 2306 * during measurement. In some special cases this is required such as when an adapter-based 2307 * view measures prospective children without attaching them to a window. 2308 */ 2309 static final int PFLAG2_PADDING_RESOLVED = 0x20000000; 2310 2311 /** 2312 * Flag indicating that the start/end drawables has been resolved into left/right ones. 2313 */ 2314 static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000; 2315 2316 /** 2317 * Indicates that the view is tracking some sort of transient state 2318 * that the app should not need to be aware of, but that the framework 2319 * should take special care to preserve. 2320 */ 2321 static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000; 2322 2323 /** 2324 * Group of bits indicating that RTL properties resolution is done. 2325 */ 2326 static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED | 2327 PFLAG2_TEXT_DIRECTION_RESOLVED | 2328 PFLAG2_TEXT_ALIGNMENT_RESOLVED | 2329 PFLAG2_PADDING_RESOLVED | 2330 PFLAG2_DRAWABLE_RESOLVED; 2331 2332 // There are a couple of flags left in mPrivateFlags2 2333 2334 /* End of masks for mPrivateFlags2 */ 2335 2336 /** 2337 * Masks for mPrivateFlags3, as generated by dumpFlags(): 2338 * 2339 * |-------|-------|-------|-------| 2340 * 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM 2341 * 1 PFLAG3_VIEW_IS_ANIMATING_ALPHA 2342 * 1 PFLAG3_IS_LAID_OUT 2343 * 1 PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT 2344 * 1 PFLAG3_CALLED_SUPER 2345 * |-------|-------|-------|-------| 2346 */ 2347 2348 /** 2349 * Flag indicating that view has a transform animation set on it. This is used to track whether 2350 * an animation is cleared between successive frames, in order to tell the associated 2351 * DisplayList to clear its animation matrix. 2352 */ 2353 static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1; 2354 2355 /** 2356 * Flag indicating that view has an alpha animation set on it. This is used to track whether an 2357 * animation is cleared between successive frames, in order to tell the associated 2358 * DisplayList to restore its alpha value. 2359 */ 2360 static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2; 2361 2362 /** 2363 * Flag indicating that the view has been through at least one layout since it 2364 * was last attached to a window. 2365 */ 2366 static final int PFLAG3_IS_LAID_OUT = 0x4; 2367 2368 /** 2369 * Flag indicating that a call to measure() was skipped and should be done 2370 * instead when layout() is invoked. 2371 */ 2372 static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8; 2373 2374 /** 2375 * Flag indicating that an overridden method correctly called down to 2376 * the superclass implementation as required by the API spec. 2377 */ 2378 static final int PFLAG3_CALLED_SUPER = 0x10; 2379 2380 /** 2381 * Flag indicating that a view's outline has been specifically defined. 2382 */ 2383 static final int PFLAG3_OUTLINE_DEFINED = 0x20; 2384 2385 /** 2386 * Flag indicating that we're in the process of applying window insets. 2387 */ 2388 static final int PFLAG3_APPLYING_INSETS = 0x40; 2389 2390 /** 2391 * Flag indicating that we're in the process of fitting system windows using the old method. 2392 */ 2393 static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x80; 2394 2395 /** 2396 * Flag indicating that nested scrolling is enabled for this view. 2397 * The view will optionally cooperate with views up its parent chain to allow for 2398 * integrated nested scrolling along the same axis. 2399 */ 2400 static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x200; 2401 2402 /* End of masks for mPrivateFlags3 */ 2403 2404 static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED; 2405 2406 /** 2407 * Always allow a user to over-scroll this view, provided it is a 2408 * view that can scroll. 2409 * 2410 * @see #getOverScrollMode() 2411 * @see #setOverScrollMode(int) 2412 */ 2413 public static final int OVER_SCROLL_ALWAYS = 0; 2414 2415 /** 2416 * Allow a user to over-scroll this view only if the content is large 2417 * enough to meaningfully scroll, provided it is a view that can scroll. 2418 * 2419 * @see #getOverScrollMode() 2420 * @see #setOverScrollMode(int) 2421 */ 2422 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 2423 2424 /** 2425 * Never allow a user to over-scroll this view. 2426 * 2427 * @see #getOverScrollMode() 2428 * @see #setOverScrollMode(int) 2429 */ 2430 public static final int OVER_SCROLL_NEVER = 2; 2431 2432 /** 2433 * Special constant for {@link #setSystemUiVisibility(int)}: View has 2434 * requested the system UI (status bar) to be visible (the default). 2435 * 2436 * @see #setSystemUiVisibility(int) 2437 */ 2438 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 2439 2440 /** 2441 * Flag for {@link #setSystemUiVisibility(int)}: View has requested the 2442 * system UI to enter an unobtrusive "low profile" mode. 2443 * 2444 * <p>This is for use in games, book readers, video players, or any other 2445 * "immersive" application where the usual system chrome is deemed too distracting. 2446 * 2447 * <p>In low profile mode, the status bar and/or navigation icons may dim. 2448 * 2449 * @see #setSystemUiVisibility(int) 2450 */ 2451 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 2452 2453 /** 2454 * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the 2455 * system navigation be temporarily hidden. 2456 * 2457 * <p>This is an even less obtrusive state than that called for by 2458 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 2459 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 2460 * those to disappear. This is useful (in conjunction with the 2461 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 2462 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 2463 * window flags) for displaying content using every last pixel on the display. 2464 * 2465 * <p>There is a limitation: because navigation controls are so important, the least user 2466 * interaction will cause them to reappear immediately. When this happens, both 2467 * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically, 2468 * so that both elements reappear at the same time. 2469 * 2470 * @see #setSystemUiVisibility(int) 2471 */ 2472 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 2473 2474 /** 2475 * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go 2476 * into the normal fullscreen mode so that its content can take over the screen 2477 * while still allowing the user to interact with the application. 2478 * 2479 * <p>This has the same visual effect as 2480 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN 2481 * WindowManager.LayoutParams.FLAG_FULLSCREEN}, 2482 * meaning that non-critical screen decorations (such as the status bar) will be 2483 * hidden while the user is in the View's window, focusing the experience on 2484 * that content. Unlike the window flag, if you are using ActionBar in 2485 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2486 * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also 2487 * hide the action bar. 2488 * 2489 * <p>This approach to going fullscreen is best used over the window flag when 2490 * it is a transient state -- that is, the application does this at certain 2491 * points in its user interaction where it wants to allow the user to focus 2492 * on content, but not as a continuous state. For situations where the application 2493 * would like to simply stay full screen the entire time (such as a game that 2494 * wants to take over the screen), the 2495 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag} 2496 * is usually a better approach. The state set here will be removed by the system 2497 * in various situations (such as the user moving to another application) like 2498 * the other system UI states. 2499 * 2500 * <p>When using this flag, the application should provide some easy facility 2501 * for the user to go out of it. A common example would be in an e-book 2502 * reader, where tapping on the screen brings back whatever screen and UI 2503 * decorations that had been hidden while the user was immersed in reading 2504 * the book. 2505 * 2506 * @see #setSystemUiVisibility(int) 2507 */ 2508 public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004; 2509 2510 /** 2511 * Flag for {@link #setSystemUiVisibility(int)}: When using other layout 2512 * flags, we would like a stable view of the content insets given to 2513 * {@link #fitSystemWindows(Rect)}. This means that the insets seen there 2514 * will always represent the worst case that the application can expect 2515 * as a continuous state. In the stock Android UI this is the space for 2516 * the system bar, nav bar, and status bar, but not more transient elements 2517 * such as an input method. 2518 * 2519 * The stable layout your UI sees is based on the system UI modes you can 2520 * switch to. That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 2521 * then you will get a stable layout for changes of the 2522 * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify 2523 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and 2524 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition 2525 * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} 2526 * with a stable layout. (Note that you should avoid using 2527 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.) 2528 * 2529 * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN} 2530 * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}), 2531 * then a hidden status bar will be considered a "stable" state for purposes 2532 * here. This allows your UI to continually hide the status bar, while still 2533 * using the system UI flags to hide the action bar while still retaining 2534 * a stable layout. Note that changing the window fullscreen flag will never 2535 * provide a stable layout for a clean transition. 2536 * 2537 * <p>If you are using ActionBar in 2538 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2539 * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the 2540 * insets it adds to those given to the application. 2541 */ 2542 public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100; 2543 2544 /** 2545 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2546 * to be layed out as if it has requested 2547 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't. This 2548 * allows it to avoid artifacts when switching in and out of that mode, at 2549 * the expense that some of its user interface may be covered by screen 2550 * decorations when they are shown. You can perform layout of your inner 2551 * UI elements to account for the navigation system UI through the 2552 * {@link #fitSystemWindows(Rect)} method. 2553 */ 2554 public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200; 2555 2556 /** 2557 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2558 * to be layed out as if it has requested 2559 * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't. This 2560 * allows it to avoid artifacts when switching in and out of that mode, at 2561 * the expense that some of its user interface may be covered by screen 2562 * decorations when they are shown. You can perform layout of your inner 2563 * UI elements to account for non-fullscreen system UI through the 2564 * {@link #fitSystemWindows(Rect)} method. 2565 */ 2566 public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400; 2567 2568 /** 2569 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2570 * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. If this flag is 2571 * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any 2572 * user interaction. 2573 * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only 2574 * has an effect when used in combination with that flag.</p> 2575 */ 2576 public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800; 2577 2578 /** 2579 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2580 * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation 2581 * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. Use this flag to create an immersive 2582 * experience while also hiding the system bars. If this flag is not set, 2583 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user 2584 * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system 2585 * if the user swipes from the top of the screen. 2586 * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with 2587 * system gestures, such as swiping from the top of the screen. These transient system bars 2588 * will overlay app’s content, may have some degree of transparency, and will automatically 2589 * hide after a short timeout. 2590 * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and 2591 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination 2592 * with one or both of those flags.</p> 2593 */ 2594 public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000; 2595 2596 /** 2597 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 2598 */ 2599 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 2600 2601 /** 2602 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 2603 */ 2604 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 2605 2606 /** 2607 * @hide 2608 * 2609 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2610 * out of the public fields to keep the undefined bits out of the developer's way. 2611 * 2612 * Flag to make the status bar not expandable. Unless you also 2613 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 2614 */ 2615 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 2616 2617 /** 2618 * @hide 2619 * 2620 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2621 * out of the public fields to keep the undefined bits out of the developer's way. 2622 * 2623 * Flag to hide notification icons and scrolling ticker text. 2624 */ 2625 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 2626 2627 /** 2628 * @hide 2629 * 2630 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2631 * out of the public fields to keep the undefined bits out of the developer's way. 2632 * 2633 * Flag to disable incoming notification alerts. This will not block 2634 * icons, but it will block sound, vibrating and other visual or aural notifications. 2635 */ 2636 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 2637 2638 /** 2639 * @hide 2640 * 2641 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2642 * out of the public fields to keep the undefined bits out of the developer's way. 2643 * 2644 * Flag to hide only the scrolling ticker. Note that 2645 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 2646 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 2647 */ 2648 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 2649 2650 /** 2651 * @hide 2652 * 2653 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2654 * out of the public fields to keep the undefined bits out of the developer's way. 2655 * 2656 * Flag to hide the center system info area. 2657 */ 2658 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 2659 2660 /** 2661 * @hide 2662 * 2663 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2664 * out of the public fields to keep the undefined bits out of the developer's way. 2665 * 2666 * Flag to hide only the home button. Don't use this 2667 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2668 */ 2669 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 2670 2671 /** 2672 * @hide 2673 * 2674 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2675 * out of the public fields to keep the undefined bits out of the developer's way. 2676 * 2677 * Flag to hide only the back button. Don't use this 2678 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2679 */ 2680 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 2681 2682 /** 2683 * @hide 2684 * 2685 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2686 * out of the public fields to keep the undefined bits out of the developer's way. 2687 * 2688 * Flag to hide only the clock. You might use this if your activity has 2689 * its own clock making the status bar's clock redundant. 2690 */ 2691 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 2692 2693 /** 2694 * @hide 2695 * 2696 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2697 * out of the public fields to keep the undefined bits out of the developer's way. 2698 * 2699 * Flag to hide only the recent apps button. Don't use this 2700 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2701 */ 2702 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 2703 2704 /** 2705 * @hide 2706 * 2707 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2708 * out of the public fields to keep the undefined bits out of the developer's way. 2709 * 2710 * Flag to disable the global search gesture. Don't use this 2711 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2712 */ 2713 public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000; 2714 2715 /** 2716 * @hide 2717 * 2718 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2719 * out of the public fields to keep the undefined bits out of the developer's way. 2720 * 2721 * Flag to specify that the status bar is displayed in transient mode. 2722 */ 2723 public static final int STATUS_BAR_TRANSIENT = 0x04000000; 2724 2725 /** 2726 * @hide 2727 * 2728 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2729 * out of the public fields to keep the undefined bits out of the developer's way. 2730 * 2731 * Flag to specify that the navigation bar is displayed in transient mode. 2732 */ 2733 public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000; 2734 2735 /** 2736 * @hide 2737 * 2738 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2739 * out of the public fields to keep the undefined bits out of the developer's way. 2740 * 2741 * Flag to specify that the hidden status bar would like to be shown. 2742 */ 2743 public static final int STATUS_BAR_UNHIDE = 0x10000000; 2744 2745 /** 2746 * @hide 2747 * 2748 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2749 * out of the public fields to keep the undefined bits out of the developer's way. 2750 * 2751 * Flag to specify that the hidden navigation bar would like to be shown. 2752 */ 2753 public static final int NAVIGATION_BAR_UNHIDE = 0x20000000; 2754 2755 /** 2756 * @hide 2757 * 2758 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2759 * out of the public fields to keep the undefined bits out of the developer's way. 2760 * 2761 * Flag to specify that the status bar is displayed in translucent mode. 2762 */ 2763 public static final int STATUS_BAR_TRANSLUCENT = 0x40000000; 2764 2765 /** 2766 * @hide 2767 * 2768 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2769 * out of the public fields to keep the undefined bits out of the developer's way. 2770 * 2771 * Flag to specify that the navigation bar is displayed in translucent mode. 2772 */ 2773 public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000; 2774 2775 /** 2776 * @hide 2777 * 2778 * Makes system ui transparent. 2779 */ 2780 public static final int SYSTEM_UI_TRANSPARENT = 0x00008000; 2781 2782 /** 2783 * @hide 2784 */ 2785 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00007FFF; 2786 2787 /** 2788 * These are the system UI flags that can be cleared by events outside 2789 * of an application. Currently this is just the ability to tap on the 2790 * screen while hiding the navigation bar to have it return. 2791 * @hide 2792 */ 2793 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 2794 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 2795 | SYSTEM_UI_FLAG_FULLSCREEN; 2796 2797 /** 2798 * Flags that can impact the layout in relation to system UI. 2799 */ 2800 public static final int SYSTEM_UI_LAYOUT_FLAGS = 2801 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 2802 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 2803 2804 /** @hide */ 2805 @IntDef(flag = true, 2806 value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION }) 2807 @Retention(RetentionPolicy.SOURCE) 2808 public @interface FindViewFlags {} 2809 2810 /** 2811 * Find views that render the specified text. 2812 * 2813 * @see #findViewsWithText(ArrayList, CharSequence, int) 2814 */ 2815 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 2816 2817 /** 2818 * Find find views that contain the specified content description. 2819 * 2820 * @see #findViewsWithText(ArrayList, CharSequence, int) 2821 */ 2822 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 2823 2824 /** 2825 * Find views that contain {@link AccessibilityNodeProvider}. Such 2826 * a View is a root of virtual view hierarchy and may contain the searched 2827 * text. If this flag is set Views with providers are automatically 2828 * added and it is a responsibility of the client to call the APIs of 2829 * the provider to determine whether the virtual tree rooted at this View 2830 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 2831 * representing the virtual views with this text. 2832 * 2833 * @see #findViewsWithText(ArrayList, CharSequence, int) 2834 * 2835 * @hide 2836 */ 2837 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 2838 2839 /** 2840 * The undefined cursor position. 2841 * 2842 * @hide 2843 */ 2844 public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1; 2845 2846 /** 2847 * Indicates that the screen has changed state and is now off. 2848 * 2849 * @see #onScreenStateChanged(int) 2850 */ 2851 public static final int SCREEN_STATE_OFF = 0x0; 2852 2853 /** 2854 * Indicates that the screen has changed state and is now on. 2855 * 2856 * @see #onScreenStateChanged(int) 2857 */ 2858 public static final int SCREEN_STATE_ON = 0x1; 2859 2860 /** 2861 * Indicates no axis of view scrolling. 2862 */ 2863 public static final int SCROLL_AXIS_NONE = 0; 2864 2865 /** 2866 * Indicates scrolling along the horizontal axis. 2867 */ 2868 public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0; 2869 2870 /** 2871 * Indicates scrolling along the vertical axis. 2872 */ 2873 public static final int SCROLL_AXIS_VERTICAL = 1 << 1; 2874 2875 /** 2876 * Controls the over-scroll mode for this view. 2877 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 2878 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 2879 * and {@link #OVER_SCROLL_NEVER}. 2880 */ 2881 private int mOverScrollMode; 2882 2883 /** 2884 * The parent this view is attached to. 2885 * {@hide} 2886 * 2887 * @see #getParent() 2888 */ 2889 protected ViewParent mParent; 2890 2891 /** 2892 * {@hide} 2893 */ 2894 AttachInfo mAttachInfo; 2895 2896 /** 2897 * {@hide} 2898 */ 2899 @ViewDebug.ExportedProperty(flagMapping = { 2900 @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT, 2901 name = "FORCE_LAYOUT"), 2902 @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED, 2903 name = "LAYOUT_REQUIRED"), 2904 @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID, 2905 name = "DRAWING_CACHE_INVALID", outputIf = false), 2906 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true), 2907 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false), 2908 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 2909 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY") 2910 }) 2911 int mPrivateFlags; 2912 int mPrivateFlags2; 2913 int mPrivateFlags3; 2914 2915 /** 2916 * This view's request for the visibility of the status bar. 2917 * @hide 2918 */ 2919 @ViewDebug.ExportedProperty(flagMapping = { 2920 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 2921 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 2922 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 2923 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2924 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2925 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 2926 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 2927 equals = SYSTEM_UI_FLAG_VISIBLE, 2928 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 2929 }) 2930 int mSystemUiVisibility; 2931 2932 /** 2933 * Reference count for transient state. 2934 * @see #setHasTransientState(boolean) 2935 */ 2936 int mTransientStateCount = 0; 2937 2938 /** 2939 * Count of how many windows this view has been attached to. 2940 */ 2941 int mWindowAttachCount; 2942 2943 /** 2944 * The layout parameters associated with this view and used by the parent 2945 * {@link android.view.ViewGroup} to determine how this view should be 2946 * laid out. 2947 * {@hide} 2948 */ 2949 protected ViewGroup.LayoutParams mLayoutParams; 2950 2951 /** 2952 * The view flags hold various views states. 2953 * {@hide} 2954 */ 2955 @ViewDebug.ExportedProperty 2956 int mViewFlags; 2957 2958 static class TransformationInfo { 2959 /** 2960 * The transform matrix for the View. This transform is calculated internally 2961 * based on the translation, rotation, and scale properties. 2962 * 2963 * Do *not* use this variable directly; instead call getMatrix(), which will 2964 * load the value from the View's RenderNode. 2965 */ 2966 private final Matrix mMatrix = new Matrix(); 2967 2968 /** 2969 * The inverse transform matrix for the View. This transform is calculated 2970 * internally based on the translation, rotation, and scale properties. 2971 * 2972 * Do *not* use this variable directly; instead call getInverseMatrix(), 2973 * which will load the value from the View's RenderNode. 2974 */ 2975 private Matrix mInverseMatrix; 2976 2977 /** 2978 * The opacity of the View. This is a value from 0 to 1, where 0 means 2979 * completely transparent and 1 means completely opaque. 2980 */ 2981 @ViewDebug.ExportedProperty 2982 float mAlpha = 1f; 2983 2984 /** 2985 * The opacity of the view as manipulated by the Fade transition. This is a hidden 2986 * property only used by transitions, which is composited with the other alpha 2987 * values to calculate the final visual alpha value. 2988 */ 2989 float mTransitionAlpha = 1f; 2990 } 2991 2992 TransformationInfo mTransformationInfo; 2993 2994 /** 2995 * Current clip bounds. to which all drawing of this view are constrained. 2996 */ 2997 Rect mClipBounds = null; 2998 2999 private boolean mLastIsOpaque; 3000 3001 /** 3002 * The distance in pixels from the left edge of this view's parent 3003 * to the left edge of this view. 3004 * {@hide} 3005 */ 3006 @ViewDebug.ExportedProperty(category = "layout") 3007 protected int mLeft; 3008 /** 3009 * The distance in pixels from the left edge of this view's parent 3010 * to the right edge of this view. 3011 * {@hide} 3012 */ 3013 @ViewDebug.ExportedProperty(category = "layout") 3014 protected int mRight; 3015 /** 3016 * The distance in pixels from the top edge of this view's parent 3017 * to the top edge of this view. 3018 * {@hide} 3019 */ 3020 @ViewDebug.ExportedProperty(category = "layout") 3021 protected int mTop; 3022 /** 3023 * The distance in pixels from the top edge of this view's parent 3024 * to the bottom edge of this view. 3025 * {@hide} 3026 */ 3027 @ViewDebug.ExportedProperty(category = "layout") 3028 protected int mBottom; 3029 3030 /** 3031 * The offset, in pixels, by which the content of this view is scrolled 3032 * horizontally. 3033 * {@hide} 3034 */ 3035 @ViewDebug.ExportedProperty(category = "scrolling") 3036 protected int mScrollX; 3037 /** 3038 * The offset, in pixels, by which the content of this view is scrolled 3039 * vertically. 3040 * {@hide} 3041 */ 3042 @ViewDebug.ExportedProperty(category = "scrolling") 3043 protected int mScrollY; 3044 3045 /** 3046 * The left padding in pixels, that is the distance in pixels between the 3047 * left edge of this view and the left edge of its content. 3048 * {@hide} 3049 */ 3050 @ViewDebug.ExportedProperty(category = "padding") 3051 protected int mPaddingLeft = 0; 3052 /** 3053 * The right padding in pixels, that is the distance in pixels between the 3054 * right edge of this view and the right edge of its content. 3055 * {@hide} 3056 */ 3057 @ViewDebug.ExportedProperty(category = "padding") 3058 protected int mPaddingRight = 0; 3059 /** 3060 * The top padding in pixels, that is the distance in pixels between the 3061 * top edge of this view and the top edge of its content. 3062 * {@hide} 3063 */ 3064 @ViewDebug.ExportedProperty(category = "padding") 3065 protected int mPaddingTop; 3066 /** 3067 * The bottom padding in pixels, that is the distance in pixels between the 3068 * bottom edge of this view and the bottom edge of its content. 3069 * {@hide} 3070 */ 3071 @ViewDebug.ExportedProperty(category = "padding") 3072 protected int mPaddingBottom; 3073 3074 /** 3075 * The layout insets in pixels, that is the distance in pixels between the 3076 * visible edges of this view its bounds. 3077 */ 3078 private Insets mLayoutInsets; 3079 3080 /** 3081 * Briefly describes the view and is primarily used for accessibility support. 3082 */ 3083 private CharSequence mContentDescription; 3084 3085 /** 3086 * Specifies the id of a view for which this view serves as a label for 3087 * accessibility purposes. 3088 */ 3089 private int mLabelForId = View.NO_ID; 3090 3091 /** 3092 * Predicate for matching labeled view id with its label for 3093 * accessibility purposes. 3094 */ 3095 private MatchLabelForPredicate mMatchLabelForPredicate; 3096 3097 /** 3098 * Predicate for matching a view by its id. 3099 */ 3100 private MatchIdPredicate mMatchIdPredicate; 3101 3102 /** 3103 * Cache the paddingRight set by the user to append to the scrollbar's size. 3104 * 3105 * @hide 3106 */ 3107 @ViewDebug.ExportedProperty(category = "padding") 3108 protected int mUserPaddingRight; 3109 3110 /** 3111 * Cache the paddingBottom set by the user to append to the scrollbar's size. 3112 * 3113 * @hide 3114 */ 3115 @ViewDebug.ExportedProperty(category = "padding") 3116 protected int mUserPaddingBottom; 3117 3118 /** 3119 * Cache the paddingLeft set by the user to append to the scrollbar's size. 3120 * 3121 * @hide 3122 */ 3123 @ViewDebug.ExportedProperty(category = "padding") 3124 protected int mUserPaddingLeft; 3125 3126 /** 3127 * Cache the paddingStart set by the user to append to the scrollbar's size. 3128 * 3129 */ 3130 @ViewDebug.ExportedProperty(category = "padding") 3131 int mUserPaddingStart; 3132 3133 /** 3134 * Cache the paddingEnd set by the user to append to the scrollbar's size. 3135 * 3136 */ 3137 @ViewDebug.ExportedProperty(category = "padding") 3138 int mUserPaddingEnd; 3139 3140 /** 3141 * Cache initial left padding. 3142 * 3143 * @hide 3144 */ 3145 int mUserPaddingLeftInitial; 3146 3147 /** 3148 * Cache initial right padding. 3149 * 3150 * @hide 3151 */ 3152 int mUserPaddingRightInitial; 3153 3154 /** 3155 * Default undefined padding 3156 */ 3157 private static final int UNDEFINED_PADDING = Integer.MIN_VALUE; 3158 3159 /** 3160 * Cache if a left padding has been defined 3161 */ 3162 private boolean mLeftPaddingDefined = false; 3163 3164 /** 3165 * Cache if a right padding has been defined 3166 */ 3167 private boolean mRightPaddingDefined = false; 3168 3169 /** 3170 * @hide 3171 */ 3172 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 3173 /** 3174 * @hide 3175 */ 3176 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 3177 3178 private LongSparseLongArray mMeasureCache; 3179 3180 @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_") 3181 private Drawable mBackground; 3182 3183 /** 3184 * Display list used for backgrounds. 3185 * <p> 3186 * When non-null and valid, this is expected to contain an up-to-date copy 3187 * of the background drawable. It is cleared on temporary detach and reset 3188 * on cleanup. 3189 */ 3190 private RenderNode mBackgroundDisplayList; 3191 3192 private int mBackgroundResource; 3193 private boolean mBackgroundSizeChanged; 3194 3195 private String mViewName; 3196 3197 static class ListenerInfo { 3198 /** 3199 * Listener used to dispatch focus change events. 3200 * This field should be made private, so it is hidden from the SDK. 3201 * {@hide} 3202 */ 3203 protected OnFocusChangeListener mOnFocusChangeListener; 3204 3205 /** 3206 * Listeners for layout change events. 3207 */ 3208 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 3209 3210 /** 3211 * Listeners for attach events. 3212 */ 3213 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 3214 3215 /** 3216 * Listener used to dispatch click events. 3217 * This field should be made private, so it is hidden from the SDK. 3218 * {@hide} 3219 */ 3220 public OnClickListener mOnClickListener; 3221 3222 /** 3223 * Listener used to dispatch long click events. 3224 * This field should be made private, so it is hidden from the SDK. 3225 * {@hide} 3226 */ 3227 protected OnLongClickListener mOnLongClickListener; 3228 3229 /** 3230 * Listener used to build the context menu. 3231 * This field should be made private, so it is hidden from the SDK. 3232 * {@hide} 3233 */ 3234 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 3235 3236 private OnKeyListener mOnKeyListener; 3237 3238 private OnTouchListener mOnTouchListener; 3239 3240 private OnHoverListener mOnHoverListener; 3241 3242 private OnGenericMotionListener mOnGenericMotionListener; 3243 3244 private OnDragListener mOnDragListener; 3245 3246 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 3247 3248 OnApplyWindowInsetsListener mOnApplyWindowInsetsListener; 3249 } 3250 3251 ListenerInfo mListenerInfo; 3252 3253 /** 3254 * The application environment this view lives in. 3255 * This field should be made private, so it is hidden from the SDK. 3256 * {@hide} 3257 */ 3258 protected Context mContext; 3259 3260 private final Resources mResources; 3261 3262 private ScrollabilityCache mScrollCache; 3263 3264 private int[] mDrawableState = null; 3265 3266 /** 3267 * Stores the outline of the view, passed down to the DisplayList level for 3268 * defining shadow shape. 3269 */ 3270 private Outline mOutline; 3271 3272 /** 3273 * Animator that automatically runs based on state changes. 3274 */ 3275 private StateListAnimator mStateListAnimator; 3276 3277 /** 3278 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 3279 * the user may specify which view to go to next. 3280 */ 3281 private int mNextFocusLeftId = View.NO_ID; 3282 3283 /** 3284 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 3285 * the user may specify which view to go to next. 3286 */ 3287 private int mNextFocusRightId = View.NO_ID; 3288 3289 /** 3290 * When this view has focus and the next focus is {@link #FOCUS_UP}, 3291 * the user may specify which view to go to next. 3292 */ 3293 private int mNextFocusUpId = View.NO_ID; 3294 3295 /** 3296 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 3297 * the user may specify which view to go to next. 3298 */ 3299 private int mNextFocusDownId = View.NO_ID; 3300 3301 /** 3302 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 3303 * the user may specify which view to go to next. 3304 */ 3305 int mNextFocusForwardId = View.NO_ID; 3306 3307 private CheckForLongPress mPendingCheckForLongPress; 3308 private CheckForTap mPendingCheckForTap = null; 3309 private PerformClick mPerformClick; 3310 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 3311 3312 private UnsetPressedState mUnsetPressedState; 3313 3314 /** 3315 * Whether the long press's action has been invoked. The tap's action is invoked on the 3316 * up event while a long press is invoked as soon as the long press duration is reached, so 3317 * a long press could be performed before the tap is checked, in which case the tap's action 3318 * should not be invoked. 3319 */ 3320 private boolean mHasPerformedLongPress; 3321 3322 /** 3323 * The minimum height of the view. We'll try our best to have the height 3324 * of this view to at least this amount. 3325 */ 3326 @ViewDebug.ExportedProperty(category = "measurement") 3327 private int mMinHeight; 3328 3329 /** 3330 * The minimum width of the view. We'll try our best to have the width 3331 * of this view to at least this amount. 3332 */ 3333 @ViewDebug.ExportedProperty(category = "measurement") 3334 private int mMinWidth; 3335 3336 /** 3337 * The delegate to handle touch events that are physically in this view 3338 * but should be handled by another view. 3339 */ 3340 private TouchDelegate mTouchDelegate = null; 3341 3342 /** 3343 * Solid color to use as a background when creating the drawing cache. Enables 3344 * the cache to use 16 bit bitmaps instead of 32 bit. 3345 */ 3346 private int mDrawingCacheBackgroundColor = 0; 3347 3348 /** 3349 * Special tree observer used when mAttachInfo is null. 3350 */ 3351 private ViewTreeObserver mFloatingTreeObserver; 3352 3353 /** 3354 * Cache the touch slop from the context that created the view. 3355 */ 3356 private int mTouchSlop; 3357 3358 /** 3359 * Object that handles automatic animation of view properties. 3360 */ 3361 private ViewPropertyAnimator mAnimator = null; 3362 3363 /** 3364 * Flag indicating that a drag can cross window boundaries. When 3365 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 3366 * with this flag set, all visible applications will be able to participate 3367 * in the drag operation and receive the dragged content. 3368 * 3369 * @hide 3370 */ 3371 public static final int DRAG_FLAG_GLOBAL = 1; 3372 3373 /** 3374 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 3375 */ 3376 private float mVerticalScrollFactor; 3377 3378 /** 3379 * Position of the vertical scroll bar. 3380 */ 3381 private int mVerticalScrollbarPosition; 3382 3383 /** 3384 * Position the scroll bar at the default position as determined by the system. 3385 */ 3386 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 3387 3388 /** 3389 * Position the scroll bar along the left edge. 3390 */ 3391 public static final int SCROLLBAR_POSITION_LEFT = 1; 3392 3393 /** 3394 * Position the scroll bar along the right edge. 3395 */ 3396 public static final int SCROLLBAR_POSITION_RIGHT = 2; 3397 3398 /** 3399 * Indicates that the view does not have a layer. 3400 * 3401 * @see #getLayerType() 3402 * @see #setLayerType(int, android.graphics.Paint) 3403 * @see #LAYER_TYPE_SOFTWARE 3404 * @see #LAYER_TYPE_HARDWARE 3405 */ 3406 public static final int LAYER_TYPE_NONE = 0; 3407 3408 /** 3409 * <p>Indicates that the view has a software layer. A software layer is backed 3410 * by a bitmap and causes the view to be rendered using Android's software 3411 * rendering pipeline, even if hardware acceleration is enabled.</p> 3412 * 3413 * <p>Software layers have various usages:</p> 3414 * <p>When the application is not using hardware acceleration, a software layer 3415 * is useful to apply a specific color filter and/or blending mode and/or 3416 * translucency to a view and all its children.</p> 3417 * <p>When the application is using hardware acceleration, a software layer 3418 * is useful to render drawing primitives not supported by the hardware 3419 * accelerated pipeline. It can also be used to cache a complex view tree 3420 * into a texture and reduce the complexity of drawing operations. For instance, 3421 * when animating a complex view tree with a translation, a software layer can 3422 * be used to render the view tree only once.</p> 3423 * <p>Software layers should be avoided when the affected view tree updates 3424 * often. Every update will require to re-render the software layer, which can 3425 * potentially be slow (particularly when hardware acceleration is turned on 3426 * since the layer will have to be uploaded into a hardware texture after every 3427 * update.)</p> 3428 * 3429 * @see #getLayerType() 3430 * @see #setLayerType(int, android.graphics.Paint) 3431 * @see #LAYER_TYPE_NONE 3432 * @see #LAYER_TYPE_HARDWARE 3433 */ 3434 public static final int LAYER_TYPE_SOFTWARE = 1; 3435 3436 /** 3437 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 3438 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 3439 * OpenGL hardware) and causes the view to be rendered using Android's hardware 3440 * rendering pipeline, but only if hardware acceleration is turned on for the 3441 * view hierarchy. When hardware acceleration is turned off, hardware layers 3442 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 3443 * 3444 * <p>A hardware layer is useful to apply a specific color filter and/or 3445 * blending mode and/or translucency to a view and all its children.</p> 3446 * <p>A hardware layer can be used to cache a complex view tree into a 3447 * texture and reduce the complexity of drawing operations. For instance, 3448 * when animating a complex view tree with a translation, a hardware layer can 3449 * be used to render the view tree only once.</p> 3450 * <p>A hardware layer can also be used to increase the rendering quality when 3451 * rotation transformations are applied on a view. It can also be used to 3452 * prevent potential clipping issues when applying 3D transforms on a view.</p> 3453 * 3454 * @see #getLayerType() 3455 * @see #setLayerType(int, android.graphics.Paint) 3456 * @see #LAYER_TYPE_NONE 3457 * @see #LAYER_TYPE_SOFTWARE 3458 */ 3459 public static final int LAYER_TYPE_HARDWARE = 2; 3460 3461 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 3462 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 3463 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 3464 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 3465 }) 3466 int mLayerType = LAYER_TYPE_NONE; 3467 Paint mLayerPaint; 3468 Rect mLocalDirtyRect; 3469 private HardwareLayer mHardwareLayer; 3470 3471 /** 3472 * Set to true when drawing cache is enabled and cannot be created. 3473 * 3474 * @hide 3475 */ 3476 public boolean mCachingFailed; 3477 private Bitmap mDrawingCache; 3478 private Bitmap mUnscaledDrawingCache; 3479 3480 /** 3481 * RenderNode holding View properties, potentially holding a DisplayList of View content. 3482 * <p> 3483 * When non-null and valid, this is expected to contain an up-to-date copy 3484 * of the View content. Its DisplayList content is cleared on temporary detach and reset on 3485 * cleanup. 3486 */ 3487 final RenderNode mRenderNode; 3488 3489 /** 3490 * Set to true when the view is sending hover accessibility events because it 3491 * is the innermost hovered view. 3492 */ 3493 private boolean mSendingHoverAccessibilityEvents; 3494 3495 /** 3496 * Delegate for injecting accessibility functionality. 3497 */ 3498 AccessibilityDelegate mAccessibilityDelegate; 3499 3500 /** 3501 * The view's overlay layer. Developers get a reference to the overlay via getOverlay() 3502 * and add/remove objects to/from the overlay directly through the Overlay methods. 3503 */ 3504 ViewOverlay mOverlay; 3505 3506 /** 3507 * The currently active parent view for receiving delegated nested scrolling events. 3508 * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared 3509 * by {@link #stopNestedScroll()} at the same point where we clear 3510 * requestDisallowInterceptTouchEvent. 3511 */ 3512 private ViewParent mNestedScrollingParent; 3513 3514 /** 3515 * Consistency verifier for debugging purposes. 3516 * @hide 3517 */ 3518 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 3519 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 3520 new InputEventConsistencyVerifier(this, 0) : null; 3521 3522 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); 3523 3524 private int[] mTempNestedScrollConsumed; 3525 3526 /** 3527 * Simple constructor to use when creating a view from code. 3528 * 3529 * @param context The Context the view is running in, through which it can 3530 * access the current theme, resources, etc. 3531 */ 3532 public View(Context context) { 3533 mContext = context; 3534 mResources = context != null ? context.getResources() : null; 3535 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 3536 // Set some flags defaults 3537 mPrivateFlags2 = 3538 (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) | 3539 (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) | 3540 (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) | 3541 (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) | 3542 (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) | 3543 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT); 3544 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 3545 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 3546 mUserPaddingStart = UNDEFINED_PADDING; 3547 mUserPaddingEnd = UNDEFINED_PADDING; 3548 mRenderNode = RenderNode.create(getClass().getName()); 3549 3550 if (!sCompatibilityDone && context != null) { 3551 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3552 3553 // Older apps may need this compatibility hack for measurement. 3554 sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1; 3555 3556 // Older apps expect onMeasure() to always be called on a layout pass, regardless 3557 // of whether a layout was requested on that View. 3558 sIgnoreMeasureCache = targetSdkVersion < KITKAT; 3559 3560 // Older apps may need this to ignore the clip bounds 3561 sIgnoreClipBoundsForChildren = targetSdkVersion < L; 3562 3563 sCompatibilityDone = true; 3564 } 3565 } 3566 3567 /** 3568 * Constructor that is called when inflating a view from XML. This is called 3569 * when a view is being constructed from an XML file, supplying attributes 3570 * that were specified in the XML file. This version uses a default style of 3571 * 0, so the only attribute values applied are those in the Context's Theme 3572 * and the given AttributeSet. 3573 * 3574 * <p> 3575 * The method onFinishInflate() will be called after all children have been 3576 * added. 3577 * 3578 * @param context The Context the view is running in, through which it can 3579 * access the current theme, resources, etc. 3580 * @param attrs The attributes of the XML tag that is inflating the view. 3581 * @see #View(Context, AttributeSet, int) 3582 */ 3583 public View(Context context, AttributeSet attrs) { 3584 this(context, attrs, 0); 3585 } 3586 3587 /** 3588 * Perform inflation from XML and apply a class-specific base style from a 3589 * theme attribute. This constructor of View allows subclasses to use their 3590 * own base style when they are inflating. For example, a Button class's 3591 * constructor would call this version of the super class constructor and 3592 * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this 3593 * allows the theme's button style to modify all of the base view attributes 3594 * (in particular its background) as well as the Button class's attributes. 3595 * 3596 * @param context The Context the view is running in, through which it can 3597 * access the current theme, resources, etc. 3598 * @param attrs The attributes of the XML tag that is inflating the view. 3599 * @param defStyleAttr An attribute in the current theme that contains a 3600 * reference to a style resource that supplies default values for 3601 * the view. Can be 0 to not look for defaults. 3602 * @see #View(Context, AttributeSet) 3603 */ 3604 public View(Context context, AttributeSet attrs, int defStyleAttr) { 3605 this(context, attrs, defStyleAttr, 0); 3606 } 3607 3608 /** 3609 * Perform inflation from XML and apply a class-specific base style from a 3610 * theme attribute or style resource. This constructor of View allows 3611 * subclasses to use their own base style when they are inflating. 3612 * <p> 3613 * When determining the final value of a particular attribute, there are 3614 * four inputs that come into play: 3615 * <ol> 3616 * <li>Any attribute values in the given AttributeSet. 3617 * <li>The style resource specified in the AttributeSet (named "style"). 3618 * <li>The default style specified by <var>defStyleAttr</var>. 3619 * <li>The default style specified by <var>defStyleRes</var>. 3620 * <li>The base values in this theme. 3621 * </ol> 3622 * <p> 3623 * Each of these inputs is considered in-order, with the first listed taking 3624 * precedence over the following ones. In other words, if in the 3625 * AttributeSet you have supplied <code><Button * textColor="#ff000000"></code> 3626 * , then the button's text will <em>always</em> be black, regardless of 3627 * what is specified in any of the styles. 3628 * 3629 * @param context The Context the view is running in, through which it can 3630 * access the current theme, resources, etc. 3631 * @param attrs The attributes of the XML tag that is inflating the view. 3632 * @param defStyleAttr An attribute in the current theme that contains a 3633 * reference to a style resource that supplies default values for 3634 * the view. Can be 0 to not look for defaults. 3635 * @param defStyleRes A resource identifier of a style resource that 3636 * supplies default values for the view, used only if 3637 * defStyleAttr is 0 or can not be found in the theme. Can be 0 3638 * to not look for defaults. 3639 * @see #View(Context, AttributeSet, int) 3640 */ 3641 public View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 3642 this(context); 3643 3644 final TypedArray a = context.obtainStyledAttributes( 3645 attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes); 3646 3647 Drawable background = null; 3648 3649 int leftPadding = -1; 3650 int topPadding = -1; 3651 int rightPadding = -1; 3652 int bottomPadding = -1; 3653 int startPadding = UNDEFINED_PADDING; 3654 int endPadding = UNDEFINED_PADDING; 3655 3656 int padding = -1; 3657 3658 int viewFlagValues = 0; 3659 int viewFlagMasks = 0; 3660 3661 boolean setScrollContainer = false; 3662 3663 int x = 0; 3664 int y = 0; 3665 3666 float tx = 0; 3667 float ty = 0; 3668 float tz = 0; 3669 float elevation = 0; 3670 float rotation = 0; 3671 float rotationX = 0; 3672 float rotationY = 0; 3673 float sx = 1f; 3674 float sy = 1f; 3675 boolean transformSet = false; 3676 3677 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 3678 int overScrollMode = mOverScrollMode; 3679 boolean initializeScrollbars = false; 3680 3681 boolean startPaddingDefined = false; 3682 boolean endPaddingDefined = false; 3683 boolean leftPaddingDefined = false; 3684 boolean rightPaddingDefined = false; 3685 3686 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3687 3688 final int N = a.getIndexCount(); 3689 for (int i = 0; i < N; i++) { 3690 int attr = a.getIndex(i); 3691 switch (attr) { 3692 case com.android.internal.R.styleable.View_background: 3693 background = a.getDrawable(attr); 3694 break; 3695 case com.android.internal.R.styleable.View_padding: 3696 padding = a.getDimensionPixelSize(attr, -1); 3697 mUserPaddingLeftInitial = padding; 3698 mUserPaddingRightInitial = padding; 3699 leftPaddingDefined = true; 3700 rightPaddingDefined = true; 3701 break; 3702 case com.android.internal.R.styleable.View_paddingLeft: 3703 leftPadding = a.getDimensionPixelSize(attr, -1); 3704 mUserPaddingLeftInitial = leftPadding; 3705 leftPaddingDefined = true; 3706 break; 3707 case com.android.internal.R.styleable.View_paddingTop: 3708 topPadding = a.getDimensionPixelSize(attr, -1); 3709 break; 3710 case com.android.internal.R.styleable.View_paddingRight: 3711 rightPadding = a.getDimensionPixelSize(attr, -1); 3712 mUserPaddingRightInitial = rightPadding; 3713 rightPaddingDefined = true; 3714 break; 3715 case com.android.internal.R.styleable.View_paddingBottom: 3716 bottomPadding = a.getDimensionPixelSize(attr, -1); 3717 break; 3718 case com.android.internal.R.styleable.View_paddingStart: 3719 startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3720 startPaddingDefined = (startPadding != UNDEFINED_PADDING); 3721 break; 3722 case com.android.internal.R.styleable.View_paddingEnd: 3723 endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3724 endPaddingDefined = (endPadding != UNDEFINED_PADDING); 3725 break; 3726 case com.android.internal.R.styleable.View_scrollX: 3727 x = a.getDimensionPixelOffset(attr, 0); 3728 break; 3729 case com.android.internal.R.styleable.View_scrollY: 3730 y = a.getDimensionPixelOffset(attr, 0); 3731 break; 3732 case com.android.internal.R.styleable.View_alpha: 3733 setAlpha(a.getFloat(attr, 1f)); 3734 break; 3735 case com.android.internal.R.styleable.View_transformPivotX: 3736 setPivotX(a.getDimensionPixelOffset(attr, 0)); 3737 break; 3738 case com.android.internal.R.styleable.View_transformPivotY: 3739 setPivotY(a.getDimensionPixelOffset(attr, 0)); 3740 break; 3741 case com.android.internal.R.styleable.View_translationX: 3742 tx = a.getDimensionPixelOffset(attr, 0); 3743 transformSet = true; 3744 break; 3745 case com.android.internal.R.styleable.View_translationY: 3746 ty = a.getDimensionPixelOffset(attr, 0); 3747 transformSet = true; 3748 break; 3749 case com.android.internal.R.styleable.View_translationZ: 3750 tz = a.getDimensionPixelOffset(attr, 0); 3751 transformSet = true; 3752 break; 3753 case com.android.internal.R.styleable.View_elevation: 3754 elevation = a.getDimensionPixelOffset(attr, 0); 3755 transformSet = true; 3756 break; 3757 case com.android.internal.R.styleable.View_rotation: 3758 rotation = a.getFloat(attr, 0); 3759 transformSet = true; 3760 break; 3761 case com.android.internal.R.styleable.View_rotationX: 3762 rotationX = a.getFloat(attr, 0); 3763 transformSet = true; 3764 break; 3765 case com.android.internal.R.styleable.View_rotationY: 3766 rotationY = a.getFloat(attr, 0); 3767 transformSet = true; 3768 break; 3769 case com.android.internal.R.styleable.View_scaleX: 3770 sx = a.getFloat(attr, 1f); 3771 transformSet = true; 3772 break; 3773 case com.android.internal.R.styleable.View_scaleY: 3774 sy = a.getFloat(attr, 1f); 3775 transformSet = true; 3776 break; 3777 case com.android.internal.R.styleable.View_id: 3778 mID = a.getResourceId(attr, NO_ID); 3779 break; 3780 case com.android.internal.R.styleable.View_tag: 3781 mTag = a.getText(attr); 3782 break; 3783 case com.android.internal.R.styleable.View_fitsSystemWindows: 3784 if (a.getBoolean(attr, false)) { 3785 viewFlagValues |= FITS_SYSTEM_WINDOWS; 3786 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 3787 } 3788 break; 3789 case com.android.internal.R.styleable.View_focusable: 3790 if (a.getBoolean(attr, false)) { 3791 viewFlagValues |= FOCUSABLE; 3792 viewFlagMasks |= FOCUSABLE_MASK; 3793 } 3794 break; 3795 case com.android.internal.R.styleable.View_focusableInTouchMode: 3796 if (a.getBoolean(attr, false)) { 3797 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 3798 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 3799 } 3800 break; 3801 case com.android.internal.R.styleable.View_clickable: 3802 if (a.getBoolean(attr, false)) { 3803 viewFlagValues |= CLICKABLE; 3804 viewFlagMasks |= CLICKABLE; 3805 } 3806 break; 3807 case com.android.internal.R.styleable.View_longClickable: 3808 if (a.getBoolean(attr, false)) { 3809 viewFlagValues |= LONG_CLICKABLE; 3810 viewFlagMasks |= LONG_CLICKABLE; 3811 } 3812 break; 3813 case com.android.internal.R.styleable.View_saveEnabled: 3814 if (!a.getBoolean(attr, true)) { 3815 viewFlagValues |= SAVE_DISABLED; 3816 viewFlagMasks |= SAVE_DISABLED_MASK; 3817 } 3818 break; 3819 case com.android.internal.R.styleable.View_duplicateParentState: 3820 if (a.getBoolean(attr, false)) { 3821 viewFlagValues |= DUPLICATE_PARENT_STATE; 3822 viewFlagMasks |= DUPLICATE_PARENT_STATE; 3823 } 3824 break; 3825 case com.android.internal.R.styleable.View_visibility: 3826 final int visibility = a.getInt(attr, 0); 3827 if (visibility != 0) { 3828 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 3829 viewFlagMasks |= VISIBILITY_MASK; 3830 } 3831 break; 3832 case com.android.internal.R.styleable.View_layoutDirection: 3833 // Clear any layout direction flags (included resolved bits) already set 3834 mPrivateFlags2 &= 3835 ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK); 3836 // Set the layout direction flags depending on the value of the attribute 3837 final int layoutDirection = a.getInt(attr, -1); 3838 final int value = (layoutDirection != -1) ? 3839 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 3840 mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT); 3841 break; 3842 case com.android.internal.R.styleable.View_drawingCacheQuality: 3843 final int cacheQuality = a.getInt(attr, 0); 3844 if (cacheQuality != 0) { 3845 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 3846 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 3847 } 3848 break; 3849 case com.android.internal.R.styleable.View_contentDescription: 3850 setContentDescription(a.getString(attr)); 3851 break; 3852 case com.android.internal.R.styleable.View_labelFor: 3853 setLabelFor(a.getResourceId(attr, NO_ID)); 3854 break; 3855 case com.android.internal.R.styleable.View_soundEffectsEnabled: 3856 if (!a.getBoolean(attr, true)) { 3857 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 3858 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 3859 } 3860 break; 3861 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 3862 if (!a.getBoolean(attr, true)) { 3863 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 3864 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 3865 } 3866 break; 3867 case R.styleable.View_scrollbars: 3868 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 3869 if (scrollbars != SCROLLBARS_NONE) { 3870 viewFlagValues |= scrollbars; 3871 viewFlagMasks |= SCROLLBARS_MASK; 3872 initializeScrollbars = true; 3873 } 3874 break; 3875 //noinspection deprecation 3876 case R.styleable.View_fadingEdge: 3877 if (targetSdkVersion >= ICE_CREAM_SANDWICH) { 3878 // Ignore the attribute starting with ICS 3879 break; 3880 } 3881 // With builds < ICS, fall through and apply fading edges 3882 case R.styleable.View_requiresFadingEdge: 3883 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 3884 if (fadingEdge != FADING_EDGE_NONE) { 3885 viewFlagValues |= fadingEdge; 3886 viewFlagMasks |= FADING_EDGE_MASK; 3887 initializeFadingEdge(a); 3888 } 3889 break; 3890 case R.styleable.View_scrollbarStyle: 3891 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 3892 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3893 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 3894 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 3895 } 3896 break; 3897 case R.styleable.View_isScrollContainer: 3898 setScrollContainer = true; 3899 if (a.getBoolean(attr, false)) { 3900 setScrollContainer(true); 3901 } 3902 break; 3903 case com.android.internal.R.styleable.View_keepScreenOn: 3904 if (a.getBoolean(attr, false)) { 3905 viewFlagValues |= KEEP_SCREEN_ON; 3906 viewFlagMasks |= KEEP_SCREEN_ON; 3907 } 3908 break; 3909 case R.styleable.View_filterTouchesWhenObscured: 3910 if (a.getBoolean(attr, false)) { 3911 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 3912 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 3913 } 3914 break; 3915 case R.styleable.View_nextFocusLeft: 3916 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 3917 break; 3918 case R.styleable.View_nextFocusRight: 3919 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 3920 break; 3921 case R.styleable.View_nextFocusUp: 3922 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 3923 break; 3924 case R.styleable.View_nextFocusDown: 3925 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 3926 break; 3927 case R.styleable.View_nextFocusForward: 3928 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 3929 break; 3930 case R.styleable.View_minWidth: 3931 mMinWidth = a.getDimensionPixelSize(attr, 0); 3932 break; 3933 case R.styleable.View_minHeight: 3934 mMinHeight = a.getDimensionPixelSize(attr, 0); 3935 break; 3936 case R.styleable.View_onClick: 3937 if (context.isRestricted()) { 3938 throw new IllegalStateException("The android:onClick attribute cannot " 3939 + "be used within a restricted context"); 3940 } 3941 3942 final String handlerName = a.getString(attr); 3943 if (handlerName != null) { 3944 setOnClickListener(new OnClickListener() { 3945 private Method mHandler; 3946 3947 public void onClick(View v) { 3948 if (mHandler == null) { 3949 try { 3950 mHandler = getContext().getClass().getMethod(handlerName, 3951 View.class); 3952 } catch (NoSuchMethodException e) { 3953 int id = getId(); 3954 String idText = id == NO_ID ? "" : " with id '" 3955 + getContext().getResources().getResourceEntryName( 3956 id) + "'"; 3957 throw new IllegalStateException("Could not find a method " + 3958 handlerName + "(View) in the activity " 3959 + getContext().getClass() + " for onClick handler" 3960 + " on view " + View.this.getClass() + idText, e); 3961 } 3962 } 3963 3964 try { 3965 mHandler.invoke(getContext(), View.this); 3966 } catch (IllegalAccessException e) { 3967 throw new IllegalStateException("Could not execute non " 3968 + "public method of the activity", e); 3969 } catch (InvocationTargetException e) { 3970 throw new IllegalStateException("Could not execute " 3971 + "method of the activity", e); 3972 } 3973 } 3974 }); 3975 } 3976 break; 3977 case R.styleable.View_overScrollMode: 3978 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 3979 break; 3980 case R.styleable.View_verticalScrollbarPosition: 3981 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 3982 break; 3983 case R.styleable.View_layerType: 3984 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 3985 break; 3986 case R.styleable.View_textDirection: 3987 // Clear any text direction flag already set 3988 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 3989 // Set the text direction flags depending on the value of the attribute 3990 final int textDirection = a.getInt(attr, -1); 3991 if (textDirection != -1) { 3992 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection]; 3993 } 3994 break; 3995 case R.styleable.View_textAlignment: 3996 // Clear any text alignment flag already set 3997 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 3998 // Set the text alignment flag depending on the value of the attribute 3999 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); 4000 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment]; 4001 break; 4002 case R.styleable.View_importantForAccessibility: 4003 setImportantForAccessibility(a.getInt(attr, 4004 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); 4005 break; 4006 case R.styleable.View_accessibilityLiveRegion: 4007 setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT)); 4008 break; 4009 case R.styleable.View_viewName: 4010 setViewName(a.getString(attr)); 4011 break; 4012 case R.styleable.View_nestedScrollingEnabled: 4013 setNestedScrollingEnabled(a.getBoolean(attr, false)); 4014 break; 4015 case R.styleable.View_stateListAnimator: 4016 setStateListAnimator(AnimatorInflater.loadStateListAnimator(context, 4017 a.getResourceId(attr, 0))); 4018 break; 4019 } 4020 } 4021 4022 setOverScrollMode(overScrollMode); 4023 4024 // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet 4025 // the resolved layout direction). Those cached values will be used later during padding 4026 // resolution. 4027 mUserPaddingStart = startPadding; 4028 mUserPaddingEnd = endPadding; 4029 4030 if (background != null) { 4031 setBackground(background); 4032 } 4033 4034 // setBackground above will record that padding is currently provided by the background. 4035 // If we have padding specified via xml, record that here instead and use it. 4036 mLeftPaddingDefined = leftPaddingDefined; 4037 mRightPaddingDefined = rightPaddingDefined; 4038 4039 if (padding >= 0) { 4040 leftPadding = padding; 4041 topPadding = padding; 4042 rightPadding = padding; 4043 bottomPadding = padding; 4044 mUserPaddingLeftInitial = padding; 4045 mUserPaddingRightInitial = padding; 4046 } 4047 4048 if (isRtlCompatibilityMode()) { 4049 // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case. 4050 // left / right padding are used if defined (meaning here nothing to do). If they are not 4051 // defined and start / end padding are defined (e.g. in Frameworks resources), then we use 4052 // start / end and resolve them as left / right (layout direction is not taken into account). 4053 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4054 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4055 // defined. 4056 if (!mLeftPaddingDefined && startPaddingDefined) { 4057 leftPadding = startPadding; 4058 } 4059 mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial; 4060 if (!mRightPaddingDefined && endPaddingDefined) { 4061 rightPadding = endPadding; 4062 } 4063 mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial; 4064 } else { 4065 // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right 4066 // values defined. Otherwise, left /right values are used. 4067 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4068 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4069 // defined. 4070 final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined; 4071 4072 if (mLeftPaddingDefined && !hasRelativePadding) { 4073 mUserPaddingLeftInitial = leftPadding; 4074 } 4075 if (mRightPaddingDefined && !hasRelativePadding) { 4076 mUserPaddingRightInitial = rightPadding; 4077 } 4078 } 4079 4080 internalSetPadding( 4081 mUserPaddingLeftInitial, 4082 topPadding >= 0 ? topPadding : mPaddingTop, 4083 mUserPaddingRightInitial, 4084 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 4085 4086 if (viewFlagMasks != 0) { 4087 setFlags(viewFlagValues, viewFlagMasks); 4088 } 4089 4090 if (initializeScrollbars) { 4091 initializeScrollbars(a); 4092 } 4093 4094 a.recycle(); 4095 4096 // Needs to be called after mViewFlags is set 4097 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 4098 recomputePadding(); 4099 } 4100 4101 if (x != 0 || y != 0) { 4102 scrollTo(x, y); 4103 } 4104 4105 if (transformSet) { 4106 setTranslationX(tx); 4107 setTranslationY(ty); 4108 setTranslationZ(tz); 4109 setElevation(elevation); 4110 setRotation(rotation); 4111 setRotationX(rotationX); 4112 setRotationY(rotationY); 4113 setScaleX(sx); 4114 setScaleY(sy); 4115 } 4116 4117 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 4118 setScrollContainer(true); 4119 } 4120 4121 computeOpaqueFlags(); 4122 } 4123 4124 /** 4125 * Non-public constructor for use in testing 4126 */ 4127 View() { 4128 mResources = null; 4129 mRenderNode = RenderNode.create(getClass().getName()); 4130 } 4131 4132 public String toString() { 4133 StringBuilder out = new StringBuilder(128); 4134 out.append(getClass().getName()); 4135 out.append('{'); 4136 out.append(Integer.toHexString(System.identityHashCode(this))); 4137 out.append(' '); 4138 switch (mViewFlags&VISIBILITY_MASK) { 4139 case VISIBLE: out.append('V'); break; 4140 case INVISIBLE: out.append('I'); break; 4141 case GONE: out.append('G'); break; 4142 default: out.append('.'); break; 4143 } 4144 out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.'); 4145 out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.'); 4146 out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D'); 4147 out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.'); 4148 out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.'); 4149 out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.'); 4150 out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.'); 4151 out.append(' '); 4152 out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.'); 4153 out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.'); 4154 out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.'); 4155 if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) { 4156 out.append('p'); 4157 } else { 4158 out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.'); 4159 } 4160 out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.'); 4161 out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.'); 4162 out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.'); 4163 out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.'); 4164 out.append(' '); 4165 out.append(mLeft); 4166 out.append(','); 4167 out.append(mTop); 4168 out.append('-'); 4169 out.append(mRight); 4170 out.append(','); 4171 out.append(mBottom); 4172 final int id = getId(); 4173 if (id != NO_ID) { 4174 out.append(" #"); 4175 out.append(Integer.toHexString(id)); 4176 final Resources r = mResources; 4177 if (Resources.resourceHasPackage(id) && r != null) { 4178 try { 4179 String pkgname; 4180 switch (id&0xff000000) { 4181 case 0x7f000000: 4182 pkgname="app"; 4183 break; 4184 case 0x01000000: 4185 pkgname="android"; 4186 break; 4187 default: 4188 pkgname = r.getResourcePackageName(id); 4189 break; 4190 } 4191 String typename = r.getResourceTypeName(id); 4192 String entryname = r.getResourceEntryName(id); 4193 out.append(" "); 4194 out.append(pkgname); 4195 out.append(":"); 4196 out.append(typename); 4197 out.append("/"); 4198 out.append(entryname); 4199 } catch (Resources.NotFoundException e) { 4200 } 4201 } 4202 } 4203 out.append("}"); 4204 return out.toString(); 4205 } 4206 4207 /** 4208 * <p> 4209 * Initializes the fading edges from a given set of styled attributes. This 4210 * method should be called by subclasses that need fading edges and when an 4211 * instance of these subclasses is created programmatically rather than 4212 * being inflated from XML. This method is automatically called when the XML 4213 * is inflated. 4214 * </p> 4215 * 4216 * @param a the styled attributes set to initialize the fading edges from 4217 */ 4218 protected void initializeFadingEdge(TypedArray a) { 4219 initScrollCache(); 4220 4221 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 4222 R.styleable.View_fadingEdgeLength, 4223 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 4224 } 4225 4226 /** 4227 * Returns the size of the vertical faded edges used to indicate that more 4228 * content in this view is visible. 4229 * 4230 * @return The size in pixels of the vertical faded edge or 0 if vertical 4231 * faded edges are not enabled for this view. 4232 * @attr ref android.R.styleable#View_fadingEdgeLength 4233 */ 4234 public int getVerticalFadingEdgeLength() { 4235 if (isVerticalFadingEdgeEnabled()) { 4236 ScrollabilityCache cache = mScrollCache; 4237 if (cache != null) { 4238 return cache.fadingEdgeLength; 4239 } 4240 } 4241 return 0; 4242 } 4243 4244 /** 4245 * Set the size of the faded edge used to indicate that more content in this 4246 * view is available. Will not change whether the fading edge is enabled; use 4247 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 4248 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 4249 * for the vertical or horizontal fading edges. 4250 * 4251 * @param length The size in pixels of the faded edge used to indicate that more 4252 * content in this view is visible. 4253 */ 4254 public void setFadingEdgeLength(int length) { 4255 initScrollCache(); 4256 mScrollCache.fadingEdgeLength = length; 4257 } 4258 4259 /** 4260 * Returns the size of the horizontal faded edges used to indicate that more 4261 * content in this view is visible. 4262 * 4263 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 4264 * faded edges are not enabled for this view. 4265 * @attr ref android.R.styleable#View_fadingEdgeLength 4266 */ 4267 public int getHorizontalFadingEdgeLength() { 4268 if (isHorizontalFadingEdgeEnabled()) { 4269 ScrollabilityCache cache = mScrollCache; 4270 if (cache != null) { 4271 return cache.fadingEdgeLength; 4272 } 4273 } 4274 return 0; 4275 } 4276 4277 /** 4278 * Returns the width of the vertical scrollbar. 4279 * 4280 * @return The width in pixels of the vertical scrollbar or 0 if there 4281 * is no vertical scrollbar. 4282 */ 4283 public int getVerticalScrollbarWidth() { 4284 ScrollabilityCache cache = mScrollCache; 4285 if (cache != null) { 4286 ScrollBarDrawable scrollBar = cache.scrollBar; 4287 if (scrollBar != null) { 4288 int size = scrollBar.getSize(true); 4289 if (size <= 0) { 4290 size = cache.scrollBarSize; 4291 } 4292 return size; 4293 } 4294 return 0; 4295 } 4296 return 0; 4297 } 4298 4299 /** 4300 * Returns the height of the horizontal scrollbar. 4301 * 4302 * @return The height in pixels of the horizontal scrollbar or 0 if 4303 * there is no horizontal scrollbar. 4304 */ 4305 protected int getHorizontalScrollbarHeight() { 4306 ScrollabilityCache cache = mScrollCache; 4307 if (cache != null) { 4308 ScrollBarDrawable scrollBar = cache.scrollBar; 4309 if (scrollBar != null) { 4310 int size = scrollBar.getSize(false); 4311 if (size <= 0) { 4312 size = cache.scrollBarSize; 4313 } 4314 return size; 4315 } 4316 return 0; 4317 } 4318 return 0; 4319 } 4320 4321 /** 4322 * <p> 4323 * Initializes the scrollbars from a given set of styled attributes. This 4324 * method should be called by subclasses that need scrollbars and when an 4325 * instance of these subclasses is created programmatically rather than 4326 * being inflated from XML. This method is automatically called when the XML 4327 * is inflated. 4328 * </p> 4329 * 4330 * @param a the styled attributes set to initialize the scrollbars from 4331 */ 4332 protected void initializeScrollbars(TypedArray a) { 4333 initScrollCache(); 4334 4335 final ScrollabilityCache scrollabilityCache = mScrollCache; 4336 4337 if (scrollabilityCache.scrollBar == null) { 4338 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 4339 } 4340 4341 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 4342 4343 if (!fadeScrollbars) { 4344 scrollabilityCache.state = ScrollabilityCache.ON; 4345 } 4346 scrollabilityCache.fadeScrollBars = fadeScrollbars; 4347 4348 4349 scrollabilityCache.scrollBarFadeDuration = a.getInt( 4350 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 4351 .getScrollBarFadeDuration()); 4352 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 4353 R.styleable.View_scrollbarDefaultDelayBeforeFade, 4354 ViewConfiguration.getScrollDefaultDelay()); 4355 4356 4357 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 4358 com.android.internal.R.styleable.View_scrollbarSize, 4359 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 4360 4361 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 4362 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 4363 4364 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 4365 if (thumb != null) { 4366 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 4367 } 4368 4369 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 4370 false); 4371 if (alwaysDraw) { 4372 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 4373 } 4374 4375 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 4376 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 4377 4378 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 4379 if (thumb != null) { 4380 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 4381 } 4382 4383 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 4384 false); 4385 if (alwaysDraw) { 4386 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 4387 } 4388 4389 // Apply layout direction to the new Drawables if needed 4390 final int layoutDirection = getLayoutDirection(); 4391 if (track != null) { 4392 track.setLayoutDirection(layoutDirection); 4393 } 4394 if (thumb != null) { 4395 thumb.setLayoutDirection(layoutDirection); 4396 } 4397 4398 // Re-apply user/background padding so that scrollbar(s) get added 4399 resolvePadding(); 4400 } 4401 4402 /** 4403 * <p> 4404 * Initalizes the scrollability cache if necessary. 4405 * </p> 4406 */ 4407 private void initScrollCache() { 4408 if (mScrollCache == null) { 4409 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 4410 } 4411 } 4412 4413 private ScrollabilityCache getScrollCache() { 4414 initScrollCache(); 4415 return mScrollCache; 4416 } 4417 4418 /** 4419 * Set the position of the vertical scroll bar. Should be one of 4420 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 4421 * {@link #SCROLLBAR_POSITION_RIGHT}. 4422 * 4423 * @param position Where the vertical scroll bar should be positioned. 4424 */ 4425 public void setVerticalScrollbarPosition(int position) { 4426 if (mVerticalScrollbarPosition != position) { 4427 mVerticalScrollbarPosition = position; 4428 computeOpaqueFlags(); 4429 resolvePadding(); 4430 } 4431 } 4432 4433 /** 4434 * @return The position where the vertical scroll bar will show, if applicable. 4435 * @see #setVerticalScrollbarPosition(int) 4436 */ 4437 public int getVerticalScrollbarPosition() { 4438 return mVerticalScrollbarPosition; 4439 } 4440 4441 ListenerInfo getListenerInfo() { 4442 if (mListenerInfo != null) { 4443 return mListenerInfo; 4444 } 4445 mListenerInfo = new ListenerInfo(); 4446 return mListenerInfo; 4447 } 4448 4449 /** 4450 * Register a callback to be invoked when focus of this view changed. 4451 * 4452 * @param l The callback that will run. 4453 */ 4454 public void setOnFocusChangeListener(OnFocusChangeListener l) { 4455 getListenerInfo().mOnFocusChangeListener = l; 4456 } 4457 4458 /** 4459 * Add a listener that will be called when the bounds of the view change due to 4460 * layout processing. 4461 * 4462 * @param listener The listener that will be called when layout bounds change. 4463 */ 4464 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 4465 ListenerInfo li = getListenerInfo(); 4466 if (li.mOnLayoutChangeListeners == null) { 4467 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 4468 } 4469 if (!li.mOnLayoutChangeListeners.contains(listener)) { 4470 li.mOnLayoutChangeListeners.add(listener); 4471 } 4472 } 4473 4474 /** 4475 * Remove a listener for layout changes. 4476 * 4477 * @param listener The listener for layout bounds change. 4478 */ 4479 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 4480 ListenerInfo li = mListenerInfo; 4481 if (li == null || li.mOnLayoutChangeListeners == null) { 4482 return; 4483 } 4484 li.mOnLayoutChangeListeners.remove(listener); 4485 } 4486 4487 /** 4488 * Add a listener for attach state changes. 4489 * 4490 * This listener will be called whenever this view is attached or detached 4491 * from a window. Remove the listener using 4492 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 4493 * 4494 * @param listener Listener to attach 4495 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 4496 */ 4497 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4498 ListenerInfo li = getListenerInfo(); 4499 if (li.mOnAttachStateChangeListeners == null) { 4500 li.mOnAttachStateChangeListeners 4501 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 4502 } 4503 li.mOnAttachStateChangeListeners.add(listener); 4504 } 4505 4506 /** 4507 * Remove a listener for attach state changes. The listener will receive no further 4508 * notification of window attach/detach events. 4509 * 4510 * @param listener Listener to remove 4511 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 4512 */ 4513 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4514 ListenerInfo li = mListenerInfo; 4515 if (li == null || li.mOnAttachStateChangeListeners == null) { 4516 return; 4517 } 4518 li.mOnAttachStateChangeListeners.remove(listener); 4519 } 4520 4521 /** 4522 * Returns the focus-change callback registered for this view. 4523 * 4524 * @return The callback, or null if one is not registered. 4525 */ 4526 public OnFocusChangeListener getOnFocusChangeListener() { 4527 ListenerInfo li = mListenerInfo; 4528 return li != null ? li.mOnFocusChangeListener : null; 4529 } 4530 4531 /** 4532 * Register a callback to be invoked when this view is clicked. If this view is not 4533 * clickable, it becomes clickable. 4534 * 4535 * @param l The callback that will run 4536 * 4537 * @see #setClickable(boolean) 4538 */ 4539 public void setOnClickListener(OnClickListener l) { 4540 if (!isClickable()) { 4541 setClickable(true); 4542 } 4543 getListenerInfo().mOnClickListener = l; 4544 } 4545 4546 /** 4547 * Return whether this view has an attached OnClickListener. Returns 4548 * true if there is a listener, false if there is none. 4549 */ 4550 public boolean hasOnClickListeners() { 4551 ListenerInfo li = mListenerInfo; 4552 return (li != null && li.mOnClickListener != null); 4553 } 4554 4555 /** 4556 * Register a callback to be invoked when this view is clicked and held. If this view is not 4557 * long clickable, it becomes long clickable. 4558 * 4559 * @param l The callback that will run 4560 * 4561 * @see #setLongClickable(boolean) 4562 */ 4563 public void setOnLongClickListener(OnLongClickListener l) { 4564 if (!isLongClickable()) { 4565 setLongClickable(true); 4566 } 4567 getListenerInfo().mOnLongClickListener = l; 4568 } 4569 4570 /** 4571 * Register a callback to be invoked when the context menu for this view is 4572 * being built. If this view is not long clickable, it becomes long clickable. 4573 * 4574 * @param l The callback that will run 4575 * 4576 */ 4577 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 4578 if (!isLongClickable()) { 4579 setLongClickable(true); 4580 } 4581 getListenerInfo().mOnCreateContextMenuListener = l; 4582 } 4583 4584 /** 4585 * Call this view's OnClickListener, if it is defined. Performs all normal 4586 * actions associated with clicking: reporting accessibility event, playing 4587 * a sound, etc. 4588 * 4589 * @return True there was an assigned OnClickListener that was called, false 4590 * otherwise is returned. 4591 */ 4592 public boolean performClick() { 4593 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 4594 4595 ListenerInfo li = mListenerInfo; 4596 if (li != null && li.mOnClickListener != null) { 4597 playSoundEffect(SoundEffectConstants.CLICK); 4598 li.mOnClickListener.onClick(this); 4599 return true; 4600 } 4601 4602 return false; 4603 } 4604 4605 /** 4606 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 4607 * this only calls the listener, and does not do any associated clicking 4608 * actions like reporting an accessibility event. 4609 * 4610 * @return True there was an assigned OnClickListener that was called, false 4611 * otherwise is returned. 4612 */ 4613 public boolean callOnClick() { 4614 ListenerInfo li = mListenerInfo; 4615 if (li != null && li.mOnClickListener != null) { 4616 li.mOnClickListener.onClick(this); 4617 return true; 4618 } 4619 return false; 4620 } 4621 4622 /** 4623 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 4624 * OnLongClickListener did not consume the event. 4625 * 4626 * @return True if one of the above receivers consumed the event, false otherwise. 4627 */ 4628 public boolean performLongClick() { 4629 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 4630 4631 boolean handled = false; 4632 ListenerInfo li = mListenerInfo; 4633 if (li != null && li.mOnLongClickListener != null) { 4634 handled = li.mOnLongClickListener.onLongClick(View.this); 4635 } 4636 if (!handled) { 4637 handled = showContextMenu(); 4638 } 4639 if (handled) { 4640 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 4641 } 4642 return handled; 4643 } 4644 4645 /** 4646 * Performs button-related actions during a touch down event. 4647 * 4648 * @param event The event. 4649 * @return True if the down was consumed. 4650 * 4651 * @hide 4652 */ 4653 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 4654 if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 4655 if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) { 4656 return true; 4657 } 4658 } 4659 return false; 4660 } 4661 4662 /** 4663 * Bring up the context menu for this view. 4664 * 4665 * @return Whether a context menu was displayed. 4666 */ 4667 public boolean showContextMenu() { 4668 return getParent().showContextMenuForChild(this); 4669 } 4670 4671 /** 4672 * Bring up the context menu for this view, referring to the item under the specified point. 4673 * 4674 * @param x The referenced x coordinate. 4675 * @param y The referenced y coordinate. 4676 * @param metaState The keyboard modifiers that were pressed. 4677 * @return Whether a context menu was displayed. 4678 * 4679 * @hide 4680 */ 4681 public boolean showContextMenu(float x, float y, int metaState) { 4682 return showContextMenu(); 4683 } 4684 4685 /** 4686 * Start an action mode. 4687 * 4688 * @param callback Callback that will control the lifecycle of the action mode 4689 * @return The new action mode if it is started, null otherwise 4690 * 4691 * @see ActionMode 4692 */ 4693 public ActionMode startActionMode(ActionMode.Callback callback) { 4694 ViewParent parent = getParent(); 4695 if (parent == null) return null; 4696 return parent.startActionModeForChild(this, callback); 4697 } 4698 4699 /** 4700 * Register a callback to be invoked when a hardware key is pressed in this view. 4701 * Key presses in software input methods will generally not trigger the methods of 4702 * this listener. 4703 * @param l the key listener to attach to this view 4704 */ 4705 public void setOnKeyListener(OnKeyListener l) { 4706 getListenerInfo().mOnKeyListener = l; 4707 } 4708 4709 /** 4710 * Register a callback to be invoked when a touch event is sent to this view. 4711 * @param l the touch listener to attach to this view 4712 */ 4713 public void setOnTouchListener(OnTouchListener l) { 4714 getListenerInfo().mOnTouchListener = l; 4715 } 4716 4717 /** 4718 * Register a callback to be invoked when a generic motion event is sent to this view. 4719 * @param l the generic motion listener to attach to this view 4720 */ 4721 public void setOnGenericMotionListener(OnGenericMotionListener l) { 4722 getListenerInfo().mOnGenericMotionListener = l; 4723 } 4724 4725 /** 4726 * Register a callback to be invoked when a hover event is sent to this view. 4727 * @param l the hover listener to attach to this view 4728 */ 4729 public void setOnHoverListener(OnHoverListener l) { 4730 getListenerInfo().mOnHoverListener = l; 4731 } 4732 4733 /** 4734 * Register a drag event listener callback object for this View. The parameter is 4735 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 4736 * View, the system calls the 4737 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 4738 * @param l An implementation of {@link android.view.View.OnDragListener}. 4739 */ 4740 public void setOnDragListener(OnDragListener l) { 4741 getListenerInfo().mOnDragListener = l; 4742 } 4743 4744 /** 4745 * Give this view focus. This will cause 4746 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 4747 * 4748 * Note: this does not check whether this {@link View} should get focus, it just 4749 * gives it focus no matter what. It should only be called internally by framework 4750 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 4751 * 4752 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 4753 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 4754 * focus moved when requestFocus() is called. It may not always 4755 * apply, in which case use the default View.FOCUS_DOWN. 4756 * @param previouslyFocusedRect The rectangle of the view that had focus 4757 * prior in this View's coordinate system. 4758 */ 4759 void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) { 4760 if (DBG) { 4761 System.out.println(this + " requestFocus()"); 4762 } 4763 4764 if ((mPrivateFlags & PFLAG_FOCUSED) == 0) { 4765 mPrivateFlags |= PFLAG_FOCUSED; 4766 4767 View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null; 4768 4769 if (mParent != null) { 4770 mParent.requestChildFocus(this, this); 4771 } 4772 4773 if (mAttachInfo != null) { 4774 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this); 4775 } 4776 4777 onFocusChanged(true, direction, previouslyFocusedRect); 4778 manageFocusHotspot(true, oldFocus); 4779 refreshDrawableState(); 4780 } 4781 } 4782 4783 /** 4784 * Forwards focus information to the background drawable, if necessary. When 4785 * the view is gaining focus, <code>v</code> is the previous focus holder. 4786 * When the view is losing focus, <code>v</code> is the next focus holder. 4787 * 4788 * @param focused whether this view is focused 4789 * @param v previous or the next focus holder, or null if none 4790 */ 4791 private void manageFocusHotspot(boolean focused, View v) { 4792 if (mBackground == null) { 4793 return; 4794 } 4795 4796 final Rect r = new Rect(); 4797 if (!focused && v != null) { 4798 v.getBoundsOnScreen(r); 4799 final int[] location = new int[2]; 4800 getLocationOnScreen(location); 4801 r.offset(-location[0], -location[1]); 4802 } else { 4803 r.set(0, 0, mRight - mLeft, mBottom - mTop); 4804 } 4805 4806 final float x = r.exactCenterX(); 4807 final float y = r.exactCenterY(); 4808 mBackground.setHotspot(x, y); 4809 } 4810 4811 /** 4812 * Request that a rectangle of this view be visible on the screen, 4813 * scrolling if necessary just enough. 4814 * 4815 * <p>A View should call this if it maintains some notion of which part 4816 * of its content is interesting. For example, a text editing view 4817 * should call this when its cursor moves. 4818 * 4819 * @param rectangle The rectangle. 4820 * @return Whether any parent scrolled. 4821 */ 4822 public boolean requestRectangleOnScreen(Rect rectangle) { 4823 return requestRectangleOnScreen(rectangle, false); 4824 } 4825 4826 /** 4827 * Request that a rectangle of this view be visible on the screen, 4828 * scrolling if necessary just enough. 4829 * 4830 * <p>A View should call this if it maintains some notion of which part 4831 * of its content is interesting. For example, a text editing view 4832 * should call this when its cursor moves. 4833 * 4834 * <p>When <code>immediate</code> is set to true, scrolling will not be 4835 * animated. 4836 * 4837 * @param rectangle The rectangle. 4838 * @param immediate True to forbid animated scrolling, false otherwise 4839 * @return Whether any parent scrolled. 4840 */ 4841 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 4842 if (mParent == null) { 4843 return false; 4844 } 4845 4846 View child = this; 4847 4848 RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF(); 4849 position.set(rectangle); 4850 4851 ViewParent parent = mParent; 4852 boolean scrolled = false; 4853 while (parent != null) { 4854 rectangle.set((int) position.left, (int) position.top, 4855 (int) position.right, (int) position.bottom); 4856 4857 scrolled |= parent.requestChildRectangleOnScreen(child, 4858 rectangle, immediate); 4859 4860 if (!child.hasIdentityMatrix()) { 4861 child.getMatrix().mapRect(position); 4862 } 4863 4864 position.offset(child.mLeft, child.mTop); 4865 4866 if (!(parent instanceof View)) { 4867 break; 4868 } 4869 4870 View parentView = (View) parent; 4871 4872 position.offset(-parentView.getScrollX(), -parentView.getScrollY()); 4873 4874 child = parentView; 4875 parent = child.getParent(); 4876 } 4877 4878 return scrolled; 4879 } 4880 4881 /** 4882 * Called when this view wants to give up focus. If focus is cleared 4883 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 4884 * <p> 4885 * <strong>Note:</strong> When a View clears focus the framework is trying 4886 * to give focus to the first focusable View from the top. Hence, if this 4887 * View is the first from the top that can take focus, then all callbacks 4888 * related to clearing focus will be invoked after wich the framework will 4889 * give focus to this view. 4890 * </p> 4891 */ 4892 public void clearFocus() { 4893 if (DBG) { 4894 System.out.println(this + " clearFocus()"); 4895 } 4896 4897 clearFocusInternal(null, true, true); 4898 } 4899 4900 /** 4901 * Clears focus from the view, optionally propagating the change up through 4902 * the parent hierarchy and requesting that the root view place new focus. 4903 * 4904 * @param propagate whether to propagate the change up through the parent 4905 * hierarchy 4906 * @param refocus when propagate is true, specifies whether to request the 4907 * root view place new focus 4908 */ 4909 void clearFocusInternal(View focused, boolean propagate, boolean refocus) { 4910 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 4911 mPrivateFlags &= ~PFLAG_FOCUSED; 4912 4913 if (propagate && mParent != null) { 4914 mParent.clearChildFocus(this); 4915 } 4916 4917 onFocusChanged(false, 0, null); 4918 4919 manageFocusHotspot(false, focused); 4920 refreshDrawableState(); 4921 4922 if (propagate && (!refocus || !rootViewRequestFocus())) { 4923 notifyGlobalFocusCleared(this); 4924 } 4925 } 4926 } 4927 4928 void notifyGlobalFocusCleared(View oldFocus) { 4929 if (oldFocus != null && mAttachInfo != null) { 4930 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null); 4931 } 4932 } 4933 4934 boolean rootViewRequestFocus() { 4935 final View root = getRootView(); 4936 return root != null && root.requestFocus(); 4937 } 4938 4939 /** 4940 * Called internally by the view system when a new view is getting focus. 4941 * This is what clears the old focus. 4942 * <p> 4943 * <b>NOTE:</b> The parent view's focused child must be updated manually 4944 * after calling this method. Otherwise, the view hierarchy may be left in 4945 * an inconstent state. 4946 */ 4947 void unFocus(View focused) { 4948 if (DBG) { 4949 System.out.println(this + " unFocus()"); 4950 } 4951 4952 clearFocusInternal(focused, false, false); 4953 } 4954 4955 /** 4956 * Returns true if this view has focus iteself, or is the ancestor of the 4957 * view that has focus. 4958 * 4959 * @return True if this view has or contains focus, false otherwise. 4960 */ 4961 @ViewDebug.ExportedProperty(category = "focus") 4962 public boolean hasFocus() { 4963 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 4964 } 4965 4966 /** 4967 * Returns true if this view is focusable or if it contains a reachable View 4968 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 4969 * is a View whose parents do not block descendants focus. 4970 * 4971 * Only {@link #VISIBLE} views are considered focusable. 4972 * 4973 * @return True if the view is focusable or if the view contains a focusable 4974 * View, false otherwise. 4975 * 4976 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 4977 */ 4978 public boolean hasFocusable() { 4979 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 4980 } 4981 4982 /** 4983 * Called by the view system when the focus state of this view changes. 4984 * When the focus change event is caused by directional navigation, direction 4985 * and previouslyFocusedRect provide insight into where the focus is coming from. 4986 * When overriding, be sure to call up through to the super class so that 4987 * the standard focus handling will occur. 4988 * 4989 * @param gainFocus True if the View has focus; false otherwise. 4990 * @param direction The direction focus has moved when requestFocus() 4991 * is called to give this view focus. Values are 4992 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 4993 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 4994 * It may not always apply, in which case use the default. 4995 * @param previouslyFocusedRect The rectangle, in this view's coordinate 4996 * system, of the previously focused view. If applicable, this will be 4997 * passed in as finer grained information about where the focus is coming 4998 * from (in addition to direction). Will be <code>null</code> otherwise. 4999 */ 5000 protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction, 5001 @Nullable Rect previouslyFocusedRect) { 5002 if (gainFocus) { 5003 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 5004 } else { 5005 notifyViewAccessibilityStateChangedIfNeeded( 5006 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 5007 } 5008 5009 InputMethodManager imm = InputMethodManager.peekInstance(); 5010 if (!gainFocus) { 5011 if (isPressed()) { 5012 setPressed(false); 5013 } 5014 if (imm != null && mAttachInfo != null 5015 && mAttachInfo.mHasWindowFocus) { 5016 imm.focusOut(this); 5017 } 5018 onFocusLost(); 5019 } else if (imm != null && mAttachInfo != null 5020 && mAttachInfo.mHasWindowFocus) { 5021 imm.focusIn(this); 5022 } 5023 5024 invalidate(true); 5025 ListenerInfo li = mListenerInfo; 5026 if (li != null && li.mOnFocusChangeListener != null) { 5027 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 5028 } 5029 5030 if (mAttachInfo != null) { 5031 mAttachInfo.mKeyDispatchState.reset(this); 5032 } 5033 } 5034 5035 /** 5036 * Sends an accessibility event of the given type. If accessibility is 5037 * not enabled this method has no effect. The default implementation calls 5038 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 5039 * to populate information about the event source (this View), then calls 5040 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 5041 * populate the text content of the event source including its descendants, 5042 * and last calls 5043 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 5044 * on its parent to resuest sending of the event to interested parties. 5045 * <p> 5046 * If an {@link AccessibilityDelegate} has been specified via calling 5047 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5048 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 5049 * responsible for handling this call. 5050 * </p> 5051 * 5052 * @param eventType The type of the event to send, as defined by several types from 5053 * {@link android.view.accessibility.AccessibilityEvent}, such as 5054 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 5055 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 5056 * 5057 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5058 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5059 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 5060 * @see AccessibilityDelegate 5061 */ 5062 public void sendAccessibilityEvent(int eventType) { 5063 if (mAccessibilityDelegate != null) { 5064 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 5065 } else { 5066 sendAccessibilityEventInternal(eventType); 5067 } 5068 } 5069 5070 /** 5071 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 5072 * {@link AccessibilityEvent} to make an announcement which is related to some 5073 * sort of a context change for which none of the events representing UI transitions 5074 * is a good fit. For example, announcing a new page in a book. If accessibility 5075 * is not enabled this method does nothing. 5076 * 5077 * @param text The announcement text. 5078 */ 5079 public void announceForAccessibility(CharSequence text) { 5080 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) { 5081 AccessibilityEvent event = AccessibilityEvent.obtain( 5082 AccessibilityEvent.TYPE_ANNOUNCEMENT); 5083 onInitializeAccessibilityEvent(event); 5084 event.getText().add(text); 5085 event.setContentDescription(null); 5086 mParent.requestSendAccessibilityEvent(this, event); 5087 } 5088 } 5089 5090 /** 5091 * @see #sendAccessibilityEvent(int) 5092 * 5093 * Note: Called from the default {@link AccessibilityDelegate}. 5094 */ 5095 void sendAccessibilityEventInternal(int eventType) { 5096 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 5097 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 5098 } 5099 } 5100 5101 /** 5102 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 5103 * takes as an argument an empty {@link AccessibilityEvent} and does not 5104 * perform a check whether accessibility is enabled. 5105 * <p> 5106 * If an {@link AccessibilityDelegate} has been specified via calling 5107 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5108 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 5109 * is responsible for handling this call. 5110 * </p> 5111 * 5112 * @param event The event to send. 5113 * 5114 * @see #sendAccessibilityEvent(int) 5115 */ 5116 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 5117 if (mAccessibilityDelegate != null) { 5118 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 5119 } else { 5120 sendAccessibilityEventUncheckedInternal(event); 5121 } 5122 } 5123 5124 /** 5125 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 5126 * 5127 * Note: Called from the default {@link AccessibilityDelegate}. 5128 */ 5129 void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 5130 if (!isShown()) { 5131 return; 5132 } 5133 onInitializeAccessibilityEvent(event); 5134 // Only a subset of accessibility events populates text content. 5135 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 5136 dispatchPopulateAccessibilityEvent(event); 5137 } 5138 // In the beginning we called #isShown(), so we know that getParent() is not null. 5139 getParent().requestSendAccessibilityEvent(this, event); 5140 } 5141 5142 /** 5143 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 5144 * to its children for adding their text content to the event. Note that the 5145 * event text is populated in a separate dispatch path since we add to the 5146 * event not only the text of the source but also the text of all its descendants. 5147 * A typical implementation will call 5148 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 5149 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5150 * on each child. Override this method if custom population of the event text 5151 * content is required. 5152 * <p> 5153 * If an {@link AccessibilityDelegate} has been specified via calling 5154 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5155 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 5156 * is responsible for handling this call. 5157 * </p> 5158 * <p> 5159 * <em>Note:</em> Accessibility events of certain types are not dispatched for 5160 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 5161 * </p> 5162 * 5163 * @param event The event. 5164 * 5165 * @return True if the event population was completed. 5166 */ 5167 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 5168 if (mAccessibilityDelegate != null) { 5169 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 5170 } else { 5171 return dispatchPopulateAccessibilityEventInternal(event); 5172 } 5173 } 5174 5175 /** 5176 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5177 * 5178 * Note: Called from the default {@link AccessibilityDelegate}. 5179 */ 5180 boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5181 onPopulateAccessibilityEvent(event); 5182 return false; 5183 } 5184 5185 /** 5186 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5187 * giving a chance to this View to populate the accessibility event with its 5188 * text content. While this method is free to modify event 5189 * attributes other than text content, doing so should normally be performed in 5190 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 5191 * <p> 5192 * Example: Adding formatted date string to an accessibility event in addition 5193 * to the text added by the super implementation: 5194 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5195 * super.onPopulateAccessibilityEvent(event); 5196 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 5197 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 5198 * mCurrentDate.getTimeInMillis(), flags); 5199 * event.getText().add(selectedDateUtterance); 5200 * }</pre> 5201 * <p> 5202 * If an {@link AccessibilityDelegate} has been specified via calling 5203 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5204 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 5205 * is responsible for handling this call. 5206 * </p> 5207 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5208 * information to the event, in case the default implementation has basic information to add. 5209 * </p> 5210 * 5211 * @param event The accessibility event which to populate. 5212 * 5213 * @see #sendAccessibilityEvent(int) 5214 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5215 */ 5216 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5217 if (mAccessibilityDelegate != null) { 5218 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 5219 } else { 5220 onPopulateAccessibilityEventInternal(event); 5221 } 5222 } 5223 5224 /** 5225 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 5226 * 5227 * Note: Called from the default {@link AccessibilityDelegate}. 5228 */ 5229 void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5230 } 5231 5232 /** 5233 * Initializes an {@link AccessibilityEvent} with information about 5234 * this View which is the event source. In other words, the source of 5235 * an accessibility event is the view whose state change triggered firing 5236 * the event. 5237 * <p> 5238 * Example: Setting the password property of an event in addition 5239 * to properties set by the super implementation: 5240 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5241 * super.onInitializeAccessibilityEvent(event); 5242 * event.setPassword(true); 5243 * }</pre> 5244 * <p> 5245 * If an {@link AccessibilityDelegate} has been specified via calling 5246 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5247 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 5248 * is responsible for handling this call. 5249 * </p> 5250 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5251 * information to the event, in case the default implementation has basic information to add. 5252 * </p> 5253 * @param event The event to initialize. 5254 * 5255 * @see #sendAccessibilityEvent(int) 5256 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5257 */ 5258 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5259 if (mAccessibilityDelegate != null) { 5260 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 5261 } else { 5262 onInitializeAccessibilityEventInternal(event); 5263 } 5264 } 5265 5266 /** 5267 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5268 * 5269 * Note: Called from the default {@link AccessibilityDelegate}. 5270 */ 5271 void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 5272 event.setSource(this); 5273 event.setClassName(View.class.getName()); 5274 event.setPackageName(getContext().getPackageName()); 5275 event.setEnabled(isEnabled()); 5276 event.setContentDescription(mContentDescription); 5277 5278 switch (event.getEventType()) { 5279 case AccessibilityEvent.TYPE_VIEW_FOCUSED: { 5280 ArrayList<View> focusablesTempList = (mAttachInfo != null) 5281 ? mAttachInfo.mTempArrayList : new ArrayList<View>(); 5282 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL); 5283 event.setItemCount(focusablesTempList.size()); 5284 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 5285 if (mAttachInfo != null) { 5286 focusablesTempList.clear(); 5287 } 5288 } break; 5289 case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: { 5290 CharSequence text = getIterableTextForAccessibility(); 5291 if (text != null && text.length() > 0) { 5292 event.setFromIndex(getAccessibilitySelectionStart()); 5293 event.setToIndex(getAccessibilitySelectionEnd()); 5294 event.setItemCount(text.length()); 5295 } 5296 } break; 5297 } 5298 } 5299 5300 /** 5301 * Returns an {@link AccessibilityNodeInfo} representing this view from the 5302 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 5303 * This method is responsible for obtaining an accessibility node info from a 5304 * pool of reusable instances and calling 5305 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 5306 * initialize the former. 5307 * <p> 5308 * Note: The client is responsible for recycling the obtained instance by calling 5309 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 5310 * </p> 5311 * 5312 * @return A populated {@link AccessibilityNodeInfo}. 5313 * 5314 * @see AccessibilityNodeInfo 5315 */ 5316 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 5317 if (mAccessibilityDelegate != null) { 5318 return mAccessibilityDelegate.createAccessibilityNodeInfo(this); 5319 } else { 5320 return createAccessibilityNodeInfoInternal(); 5321 } 5322 } 5323 5324 /** 5325 * @see #createAccessibilityNodeInfo() 5326 */ 5327 AccessibilityNodeInfo createAccessibilityNodeInfoInternal() { 5328 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 5329 if (provider != null) { 5330 return provider.createAccessibilityNodeInfo(View.NO_ID); 5331 } else { 5332 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 5333 onInitializeAccessibilityNodeInfo(info); 5334 return info; 5335 } 5336 } 5337 5338 /** 5339 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 5340 * The base implementation sets: 5341 * <ul> 5342 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 5343 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 5344 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 5345 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 5346 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 5347 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 5348 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 5349 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 5350 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 5351 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 5352 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 5353 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 5354 * </ul> 5355 * <p> 5356 * Subclasses should override this method, call the super implementation, 5357 * and set additional attributes. 5358 * </p> 5359 * <p> 5360 * If an {@link AccessibilityDelegate} has been specified via calling 5361 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5362 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 5363 * is responsible for handling this call. 5364 * </p> 5365 * 5366 * @param info The instance to initialize. 5367 */ 5368 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 5369 if (mAccessibilityDelegate != null) { 5370 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 5371 } else { 5372 onInitializeAccessibilityNodeInfoInternal(info); 5373 } 5374 } 5375 5376 /** 5377 * Gets the location of this view in screen coordintates. 5378 * 5379 * @param outRect The output location 5380 */ 5381 void getBoundsOnScreen(Rect outRect) { 5382 if (mAttachInfo == null) { 5383 return; 5384 } 5385 5386 RectF position = mAttachInfo.mTmpTransformRect; 5387 position.set(0, 0, mRight - mLeft, mBottom - mTop); 5388 5389 if (!hasIdentityMatrix()) { 5390 getMatrix().mapRect(position); 5391 } 5392 5393 position.offset(mLeft, mTop); 5394 5395 ViewParent parent = mParent; 5396 while (parent instanceof View) { 5397 View parentView = (View) parent; 5398 5399 position.offset(-parentView.mScrollX, -parentView.mScrollY); 5400 5401 if (!parentView.hasIdentityMatrix()) { 5402 parentView.getMatrix().mapRect(position); 5403 } 5404 5405 position.offset(parentView.mLeft, parentView.mTop); 5406 5407 parent = parentView.mParent; 5408 } 5409 5410 if (parent instanceof ViewRootImpl) { 5411 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 5412 position.offset(0, -viewRootImpl.mCurScrollY); 5413 } 5414 5415 position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 5416 5417 outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f), 5418 (int) (position.right + 0.5f), (int) (position.bottom + 0.5f)); 5419 } 5420 5421 /** 5422 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 5423 * 5424 * Note: Called from the default {@link AccessibilityDelegate}. 5425 */ 5426 void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 5427 Rect bounds = mAttachInfo.mTmpInvalRect; 5428 5429 getDrawingRect(bounds); 5430 info.setBoundsInParent(bounds); 5431 5432 getBoundsOnScreen(bounds); 5433 info.setBoundsInScreen(bounds); 5434 5435 ViewParent parent = getParentForAccessibility(); 5436 if (parent instanceof View) { 5437 info.setParent((View) parent); 5438 } 5439 5440 if (mID != View.NO_ID) { 5441 View rootView = getRootView(); 5442 if (rootView == null) { 5443 rootView = this; 5444 } 5445 View label = rootView.findLabelForView(this, mID); 5446 if (label != null) { 5447 info.setLabeledBy(label); 5448 } 5449 5450 if ((mAttachInfo.mAccessibilityFetchFlags 5451 & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0 5452 && Resources.resourceHasPackage(mID)) { 5453 try { 5454 String viewId = getResources().getResourceName(mID); 5455 info.setViewIdResourceName(viewId); 5456 } catch (Resources.NotFoundException nfe) { 5457 /* ignore */ 5458 } 5459 } 5460 } 5461 5462 if (mLabelForId != View.NO_ID) { 5463 View rootView = getRootView(); 5464 if (rootView == null) { 5465 rootView = this; 5466 } 5467 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId); 5468 if (labeled != null) { 5469 info.setLabelFor(labeled); 5470 } 5471 } 5472 5473 info.setVisibleToUser(isVisibleToUser()); 5474 5475 info.setPackageName(mContext.getPackageName()); 5476 info.setClassName(View.class.getName()); 5477 info.setContentDescription(getContentDescription()); 5478 5479 info.setEnabled(isEnabled()); 5480 info.setClickable(isClickable()); 5481 info.setFocusable(isFocusable()); 5482 info.setFocused(isFocused()); 5483 info.setAccessibilityFocused(isAccessibilityFocused()); 5484 info.setSelected(isSelected()); 5485 info.setLongClickable(isLongClickable()); 5486 info.setLiveRegion(getAccessibilityLiveRegion()); 5487 5488 // TODO: These make sense only if we are in an AdapterView but all 5489 // views can be selected. Maybe from accessibility perspective 5490 // we should report as selectable view in an AdapterView. 5491 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 5492 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 5493 5494 if (isFocusable()) { 5495 if (isFocused()) { 5496 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 5497 } else { 5498 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 5499 } 5500 } 5501 5502 if (!isAccessibilityFocused()) { 5503 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 5504 } else { 5505 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 5506 } 5507 5508 if (isClickable() && isEnabled()) { 5509 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 5510 } 5511 5512 if (isLongClickable() && isEnabled()) { 5513 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 5514 } 5515 5516 CharSequence text = getIterableTextForAccessibility(); 5517 if (text != null && text.length() > 0) { 5518 info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd()); 5519 5520 info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); 5521 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 5522 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 5523 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 5524 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 5525 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 5526 } 5527 } 5528 5529 private View findLabelForView(View view, int labeledId) { 5530 if (mMatchLabelForPredicate == null) { 5531 mMatchLabelForPredicate = new MatchLabelForPredicate(); 5532 } 5533 mMatchLabelForPredicate.mLabeledId = labeledId; 5534 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 5535 } 5536 5537 /** 5538 * Computes whether this view is visible to the user. Such a view is 5539 * attached, visible, all its predecessors are visible, it is not clipped 5540 * entirely by its predecessors, and has an alpha greater than zero. 5541 * 5542 * @return Whether the view is visible on the screen. 5543 * 5544 * @hide 5545 */ 5546 protected boolean isVisibleToUser() { 5547 return isVisibleToUser(null); 5548 } 5549 5550 /** 5551 * Computes whether the given portion of this view is visible to the user. 5552 * Such a view is attached, visible, all its predecessors are visible, 5553 * has an alpha greater than zero, and the specified portion is not 5554 * clipped entirely by its predecessors. 5555 * 5556 * @param boundInView the portion of the view to test; coordinates should be relative; may be 5557 * <code>null</code>, and the entire view will be tested in this case. 5558 * When <code>true</code> is returned by the function, the actual visible 5559 * region will be stored in this parameter; that is, if boundInView is fully 5560 * contained within the view, no modification will be made, otherwise regions 5561 * outside of the visible area of the view will be clipped. 5562 * 5563 * @return Whether the specified portion of the view is visible on the screen. 5564 * 5565 * @hide 5566 */ 5567 protected boolean isVisibleToUser(Rect boundInView) { 5568 if (mAttachInfo != null) { 5569 // Attached to invisible window means this view is not visible. 5570 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 5571 return false; 5572 } 5573 // An invisible predecessor or one with alpha zero means 5574 // that this view is not visible to the user. 5575 Object current = this; 5576 while (current instanceof View) { 5577 View view = (View) current; 5578 // We have attach info so this view is attached and there is no 5579 // need to check whether we reach to ViewRootImpl on the way up. 5580 if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 || 5581 view.getVisibility() != VISIBLE) { 5582 return false; 5583 } 5584 current = view.mParent; 5585 } 5586 // Check if the view is entirely covered by its predecessors. 5587 Rect visibleRect = mAttachInfo.mTmpInvalRect; 5588 Point offset = mAttachInfo.mPoint; 5589 if (!getGlobalVisibleRect(visibleRect, offset)) { 5590 return false; 5591 } 5592 // Check if the visible portion intersects the rectangle of interest. 5593 if (boundInView != null) { 5594 visibleRect.offset(-offset.x, -offset.y); 5595 return boundInView.intersect(visibleRect); 5596 } 5597 return true; 5598 } 5599 return false; 5600 } 5601 5602 /** 5603 * Returns the delegate for implementing accessibility support via 5604 * composition. For more details see {@link AccessibilityDelegate}. 5605 * 5606 * @return The delegate, or null if none set. 5607 * 5608 * @hide 5609 */ 5610 public AccessibilityDelegate getAccessibilityDelegate() { 5611 return mAccessibilityDelegate; 5612 } 5613 5614 /** 5615 * Sets a delegate for implementing accessibility support via composition as 5616 * opposed to inheritance. The delegate's primary use is for implementing 5617 * backwards compatible widgets. For more details see {@link AccessibilityDelegate}. 5618 * 5619 * @param delegate The delegate instance. 5620 * 5621 * @see AccessibilityDelegate 5622 */ 5623 public void setAccessibilityDelegate(AccessibilityDelegate delegate) { 5624 mAccessibilityDelegate = delegate; 5625 } 5626 5627 /** 5628 * Gets the provider for managing a virtual view hierarchy rooted at this View 5629 * and reported to {@link android.accessibilityservice.AccessibilityService}s 5630 * that explore the window content. 5631 * <p> 5632 * If this method returns an instance, this instance is responsible for managing 5633 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 5634 * View including the one representing the View itself. Similarly the returned 5635 * instance is responsible for performing accessibility actions on any virtual 5636 * view or the root view itself. 5637 * </p> 5638 * <p> 5639 * If an {@link AccessibilityDelegate} has been specified via calling 5640 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5641 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 5642 * is responsible for handling this call. 5643 * </p> 5644 * 5645 * @return The provider. 5646 * 5647 * @see AccessibilityNodeProvider 5648 */ 5649 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 5650 if (mAccessibilityDelegate != null) { 5651 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 5652 } else { 5653 return null; 5654 } 5655 } 5656 5657 /** 5658 * Gets the unique identifier of this view on the screen for accessibility purposes. 5659 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 5660 * 5661 * @return The view accessibility id. 5662 * 5663 * @hide 5664 */ 5665 public int getAccessibilityViewId() { 5666 if (mAccessibilityViewId == NO_ID) { 5667 mAccessibilityViewId = sNextAccessibilityViewId++; 5668 } 5669 return mAccessibilityViewId; 5670 } 5671 5672 /** 5673 * Gets the unique identifier of the window in which this View reseides. 5674 * 5675 * @return The window accessibility id. 5676 * 5677 * @hide 5678 */ 5679 public int getAccessibilityWindowId() { 5680 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId 5681 : AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 5682 } 5683 5684 /** 5685 * Gets the {@link View} description. It briefly describes the view and is 5686 * primarily used for accessibility support. Set this property to enable 5687 * better accessibility support for your application. This is especially 5688 * true for views that do not have textual representation (For example, 5689 * ImageButton). 5690 * 5691 * @return The content description. 5692 * 5693 * @attr ref android.R.styleable#View_contentDescription 5694 */ 5695 @ViewDebug.ExportedProperty(category = "accessibility") 5696 public CharSequence getContentDescription() { 5697 return mContentDescription; 5698 } 5699 5700 /** 5701 * Sets the {@link View} description. It briefly describes the view and is 5702 * primarily used for accessibility support. Set this property to enable 5703 * better accessibility support for your application. This is especially 5704 * true for views that do not have textual representation (For example, 5705 * ImageButton). 5706 * 5707 * @param contentDescription The content description. 5708 * 5709 * @attr ref android.R.styleable#View_contentDescription 5710 */ 5711 @RemotableViewMethod 5712 public void setContentDescription(CharSequence contentDescription) { 5713 if (mContentDescription == null) { 5714 if (contentDescription == null) { 5715 return; 5716 } 5717 } else if (mContentDescription.equals(contentDescription)) { 5718 return; 5719 } 5720 mContentDescription = contentDescription; 5721 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 5722 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 5723 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 5724 notifySubtreeAccessibilityStateChangedIfNeeded(); 5725 } else { 5726 notifyViewAccessibilityStateChangedIfNeeded( 5727 AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION); 5728 } 5729 } 5730 5731 /** 5732 * Gets the id of a view for which this view serves as a label for 5733 * accessibility purposes. 5734 * 5735 * @return The labeled view id. 5736 */ 5737 @ViewDebug.ExportedProperty(category = "accessibility") 5738 public int getLabelFor() { 5739 return mLabelForId; 5740 } 5741 5742 /** 5743 * Sets the id of a view for which this view serves as a label for 5744 * accessibility purposes. 5745 * 5746 * @param id The labeled view id. 5747 */ 5748 @RemotableViewMethod 5749 public void setLabelFor(int id) { 5750 mLabelForId = id; 5751 if (mLabelForId != View.NO_ID 5752 && mID == View.NO_ID) { 5753 mID = generateViewId(); 5754 } 5755 } 5756 5757 /** 5758 * Invoked whenever this view loses focus, either by losing window focus or by losing 5759 * focus within its window. This method can be used to clear any state tied to the 5760 * focus. For instance, if a button is held pressed with the trackball and the window 5761 * loses focus, this method can be used to cancel the press. 5762 * 5763 * Subclasses of View overriding this method should always call super.onFocusLost(). 5764 * 5765 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 5766 * @see #onWindowFocusChanged(boolean) 5767 * 5768 * @hide pending API council approval 5769 */ 5770 protected void onFocusLost() { 5771 resetPressedState(); 5772 } 5773 5774 private void resetPressedState() { 5775 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 5776 return; 5777 } 5778 5779 if (isPressed()) { 5780 setPressed(false); 5781 5782 if (!mHasPerformedLongPress) { 5783 removeLongPressCallback(); 5784 } 5785 } 5786 } 5787 5788 /** 5789 * Returns true if this view has focus 5790 * 5791 * @return True if this view has focus, false otherwise. 5792 */ 5793 @ViewDebug.ExportedProperty(category = "focus") 5794 public boolean isFocused() { 5795 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 5796 } 5797 5798 /** 5799 * Find the view in the hierarchy rooted at this view that currently has 5800 * focus. 5801 * 5802 * @return The view that currently has focus, or null if no focused view can 5803 * be found. 5804 */ 5805 public View findFocus() { 5806 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 5807 } 5808 5809 /** 5810 * Indicates whether this view is one of the set of scrollable containers in 5811 * its window. 5812 * 5813 * @return whether this view is one of the set of scrollable containers in 5814 * its window 5815 * 5816 * @attr ref android.R.styleable#View_isScrollContainer 5817 */ 5818 public boolean isScrollContainer() { 5819 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 5820 } 5821 5822 /** 5823 * Change whether this view is one of the set of scrollable containers in 5824 * its window. This will be used to determine whether the window can 5825 * resize or must pan when a soft input area is open -- scrollable 5826 * containers allow the window to use resize mode since the container 5827 * will appropriately shrink. 5828 * 5829 * @attr ref android.R.styleable#View_isScrollContainer 5830 */ 5831 public void setScrollContainer(boolean isScrollContainer) { 5832 if (isScrollContainer) { 5833 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 5834 mAttachInfo.mScrollContainers.add(this); 5835 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 5836 } 5837 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 5838 } else { 5839 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 5840 mAttachInfo.mScrollContainers.remove(this); 5841 } 5842 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 5843 } 5844 } 5845 5846 /** 5847 * Returns the quality of the drawing cache. 5848 * 5849 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5850 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5851 * 5852 * @see #setDrawingCacheQuality(int) 5853 * @see #setDrawingCacheEnabled(boolean) 5854 * @see #isDrawingCacheEnabled() 5855 * 5856 * @attr ref android.R.styleable#View_drawingCacheQuality 5857 */ 5858 @DrawingCacheQuality 5859 public int getDrawingCacheQuality() { 5860 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 5861 } 5862 5863 /** 5864 * Set the drawing cache quality of this view. This value is used only when the 5865 * drawing cache is enabled 5866 * 5867 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5868 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5869 * 5870 * @see #getDrawingCacheQuality() 5871 * @see #setDrawingCacheEnabled(boolean) 5872 * @see #isDrawingCacheEnabled() 5873 * 5874 * @attr ref android.R.styleable#View_drawingCacheQuality 5875 */ 5876 public void setDrawingCacheQuality(@DrawingCacheQuality int quality) { 5877 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 5878 } 5879 5880 /** 5881 * Returns whether the screen should remain on, corresponding to the current 5882 * value of {@link #KEEP_SCREEN_ON}. 5883 * 5884 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 5885 * 5886 * @see #setKeepScreenOn(boolean) 5887 * 5888 * @attr ref android.R.styleable#View_keepScreenOn 5889 */ 5890 public boolean getKeepScreenOn() { 5891 return (mViewFlags & KEEP_SCREEN_ON) != 0; 5892 } 5893 5894 /** 5895 * Controls whether the screen should remain on, modifying the 5896 * value of {@link #KEEP_SCREEN_ON}. 5897 * 5898 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 5899 * 5900 * @see #getKeepScreenOn() 5901 * 5902 * @attr ref android.R.styleable#View_keepScreenOn 5903 */ 5904 public void setKeepScreenOn(boolean keepScreenOn) { 5905 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 5906 } 5907 5908 /** 5909 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5910 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5911 * 5912 * @attr ref android.R.styleable#View_nextFocusLeft 5913 */ 5914 public int getNextFocusLeftId() { 5915 return mNextFocusLeftId; 5916 } 5917 5918 /** 5919 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5920 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 5921 * decide automatically. 5922 * 5923 * @attr ref android.R.styleable#View_nextFocusLeft 5924 */ 5925 public void setNextFocusLeftId(int nextFocusLeftId) { 5926 mNextFocusLeftId = nextFocusLeftId; 5927 } 5928 5929 /** 5930 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5931 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5932 * 5933 * @attr ref android.R.styleable#View_nextFocusRight 5934 */ 5935 public int getNextFocusRightId() { 5936 return mNextFocusRightId; 5937 } 5938 5939 /** 5940 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5941 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 5942 * decide automatically. 5943 * 5944 * @attr ref android.R.styleable#View_nextFocusRight 5945 */ 5946 public void setNextFocusRightId(int nextFocusRightId) { 5947 mNextFocusRightId = nextFocusRightId; 5948 } 5949 5950 /** 5951 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 5952 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5953 * 5954 * @attr ref android.R.styleable#View_nextFocusUp 5955 */ 5956 public int getNextFocusUpId() { 5957 return mNextFocusUpId; 5958 } 5959 5960 /** 5961 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 5962 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 5963 * decide automatically. 5964 * 5965 * @attr ref android.R.styleable#View_nextFocusUp 5966 */ 5967 public void setNextFocusUpId(int nextFocusUpId) { 5968 mNextFocusUpId = nextFocusUpId; 5969 } 5970 5971 /** 5972 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 5973 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5974 * 5975 * @attr ref android.R.styleable#View_nextFocusDown 5976 */ 5977 public int getNextFocusDownId() { 5978 return mNextFocusDownId; 5979 } 5980 5981 /** 5982 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 5983 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 5984 * decide automatically. 5985 * 5986 * @attr ref android.R.styleable#View_nextFocusDown 5987 */ 5988 public void setNextFocusDownId(int nextFocusDownId) { 5989 mNextFocusDownId = nextFocusDownId; 5990 } 5991 5992 /** 5993 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 5994 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5995 * 5996 * @attr ref android.R.styleable#View_nextFocusForward 5997 */ 5998 public int getNextFocusForwardId() { 5999 return mNextFocusForwardId; 6000 } 6001 6002 /** 6003 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 6004 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 6005 * decide automatically. 6006 * 6007 * @attr ref android.R.styleable#View_nextFocusForward 6008 */ 6009 public void setNextFocusForwardId(int nextFocusForwardId) { 6010 mNextFocusForwardId = nextFocusForwardId; 6011 } 6012 6013 /** 6014 * Returns the visibility of this view and all of its ancestors 6015 * 6016 * @return True if this view and all of its ancestors are {@link #VISIBLE} 6017 */ 6018 public boolean isShown() { 6019 View current = this; 6020 //noinspection ConstantConditions 6021 do { 6022 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 6023 return false; 6024 } 6025 ViewParent parent = current.mParent; 6026 if (parent == null) { 6027 return false; // We are not attached to the view root 6028 } 6029 if (!(parent instanceof View)) { 6030 return true; 6031 } 6032 current = (View) parent; 6033 } while (current != null); 6034 6035 return false; 6036 } 6037 6038 /** 6039 * Called by the view hierarchy when the content insets for a window have 6040 * changed, to allow it to adjust its content to fit within those windows. 6041 * The content insets tell you the space that the status bar, input method, 6042 * and other system windows infringe on the application's window. 6043 * 6044 * <p>You do not normally need to deal with this function, since the default 6045 * window decoration given to applications takes care of applying it to the 6046 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 6047 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 6048 * and your content can be placed under those system elements. You can then 6049 * use this method within your view hierarchy if you have parts of your UI 6050 * which you would like to ensure are not being covered. 6051 * 6052 * <p>The default implementation of this method simply applies the content 6053 * insets to the view's padding, consuming that content (modifying the 6054 * insets to be 0), and returning true. This behavior is off by default, but can 6055 * be enabled through {@link #setFitsSystemWindows(boolean)}. 6056 * 6057 * <p>This function's traversal down the hierarchy is depth-first. The same content 6058 * insets object is propagated down the hierarchy, so any changes made to it will 6059 * be seen by all following views (including potentially ones above in 6060 * the hierarchy since this is a depth-first traversal). The first view 6061 * that returns true will abort the entire traversal. 6062 * 6063 * <p>The default implementation works well for a situation where it is 6064 * used with a container that covers the entire window, allowing it to 6065 * apply the appropriate insets to its content on all edges. If you need 6066 * a more complicated layout (such as two different views fitting system 6067 * windows, one on the top of the window, and one on the bottom), 6068 * you can override the method and handle the insets however you would like. 6069 * Note that the insets provided by the framework are always relative to the 6070 * far edges of the window, not accounting for the location of the called view 6071 * within that window. (In fact when this method is called you do not yet know 6072 * where the layout will place the view, as it is done before layout happens.) 6073 * 6074 * <p>Note: unlike many View methods, there is no dispatch phase to this 6075 * call. If you are overriding it in a ViewGroup and want to allow the 6076 * call to continue to your children, you must be sure to call the super 6077 * implementation. 6078 * 6079 * <p>Here is a sample layout that makes use of fitting system windows 6080 * to have controls for a video view placed inside of the window decorations 6081 * that it hides and shows. This can be used with code like the second 6082 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 6083 * 6084 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 6085 * 6086 * @param insets Current content insets of the window. Prior to 6087 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 6088 * the insets or else you and Android will be unhappy. 6089 * 6090 * @return {@code true} if this view applied the insets and it should not 6091 * continue propagating further down the hierarchy, {@code false} otherwise. 6092 * @see #getFitsSystemWindows() 6093 * @see #setFitsSystemWindows(boolean) 6094 * @see #setSystemUiVisibility(int) 6095 * 6096 * @deprecated As of API XX use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply 6097 * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use 6098 * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)} 6099 * to implement handling their own insets. 6100 */ 6101 protected boolean fitSystemWindows(Rect insets) { 6102 if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) { 6103 // If we're not in the process of dispatching the newer apply insets call, 6104 // that means we're not in the compatibility path. Dispatch into the newer 6105 // apply insets path and take things from there. 6106 try { 6107 mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS; 6108 return !dispatchApplyWindowInsets(new WindowInsets(insets)).hasInsets(); 6109 } finally { 6110 mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS; 6111 } 6112 } else { 6113 // We're being called from the newer apply insets path. 6114 // Perform the standard fallback behavior. 6115 return fitSystemWindowsInt(insets); 6116 } 6117 } 6118 6119 private boolean fitSystemWindowsInt(Rect insets) { 6120 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 6121 mUserPaddingStart = UNDEFINED_PADDING; 6122 mUserPaddingEnd = UNDEFINED_PADDING; 6123 Rect localInsets = sThreadLocal.get(); 6124 if (localInsets == null) { 6125 localInsets = new Rect(); 6126 sThreadLocal.set(localInsets); 6127 } 6128 boolean res = computeFitSystemWindows(insets, localInsets); 6129 mUserPaddingLeftInitial = localInsets.left; 6130 mUserPaddingRightInitial = localInsets.right; 6131 internalSetPadding(localInsets.left, localInsets.top, 6132 localInsets.right, localInsets.bottom); 6133 return res; 6134 } 6135 return false; 6136 } 6137 6138 /** 6139 * Called when the view should apply {@link WindowInsets} according to its internal policy. 6140 * 6141 * <p>This method should be overridden by views that wish to apply a policy different from or 6142 * in addition to the default behavior. Clients that wish to force a view subtree 6143 * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p> 6144 * 6145 * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set 6146 * it will be called during dispatch instead of this method. The listener may optionally 6147 * call this method from its own implementation if it wishes to apply the view's default 6148 * insets policy in addition to its own.</p> 6149 * 6150 * <p>Implementations of this method should either return the insets parameter unchanged 6151 * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed 6152 * that this view applied itself. This allows new inset types added in future platform 6153 * versions to pass through existing implementations unchanged without being erroneously 6154 * consumed.</p> 6155 * 6156 * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows} 6157 * property is set then the view will consume the system window insets and apply them 6158 * as padding for the view.</p> 6159 * 6160 * @param insets Insets to apply 6161 * @return The supplied insets with any applied insets consumed 6162 */ 6163 public WindowInsets onApplyWindowInsets(WindowInsets insets) { 6164 if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) { 6165 // We weren't called from within a direct call to fitSystemWindows, 6166 // call into it as a fallback in case we're in a class that overrides it 6167 // and has logic to perform. 6168 if (fitSystemWindows(insets.getSystemWindowInsets())) { 6169 return insets.consumeSystemWindowInsets(); 6170 } 6171 } else { 6172 // We were called from within a direct call to fitSystemWindows. 6173 if (fitSystemWindowsInt(insets.getSystemWindowInsets())) { 6174 return insets.consumeSystemWindowInsets(); 6175 } 6176 } 6177 return insets; 6178 } 6179 6180 /** 6181 * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying 6182 * window insets to this view. The listener's 6183 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 6184 * method will be called instead of the view's 6185 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 6186 * 6187 * @param listener Listener to set 6188 * 6189 * @see #onApplyWindowInsets(WindowInsets) 6190 */ 6191 public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) { 6192 getListenerInfo().mOnApplyWindowInsetsListener = listener; 6193 } 6194 6195 /** 6196 * Request to apply the given window insets to this view or another view in its subtree. 6197 * 6198 * <p>This method should be called by clients wishing to apply insets corresponding to areas 6199 * obscured by window decorations or overlays. This can include the status and navigation bars, 6200 * action bars, input methods and more. New inset categories may be added in the future. 6201 * The method returns the insets provided minus any that were applied by this view or its 6202 * children.</p> 6203 * 6204 * <p>Clients wishing to provide custom behavior should override the 6205 * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a 6206 * {@link OnApplyWindowInsetsListener} via the 6207 * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener} 6208 * method.</p> 6209 * 6210 * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method. 6211 * </p> 6212 * 6213 * @param insets Insets to apply 6214 * @return The provided insets minus the insets that were consumed 6215 */ 6216 public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) { 6217 try { 6218 mPrivateFlags3 |= PFLAG3_APPLYING_INSETS; 6219 if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) { 6220 return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets); 6221 } else { 6222 return onApplyWindowInsets(insets); 6223 } 6224 } finally { 6225 mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS; 6226 } 6227 } 6228 6229 /** 6230 * @hide Compute the insets that should be consumed by this view and the ones 6231 * that should propagate to those under it. 6232 */ 6233 protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) { 6234 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 6235 || mAttachInfo == null 6236 || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0 6237 && !mAttachInfo.mOverscanRequested)) { 6238 outLocalInsets.set(inoutInsets); 6239 inoutInsets.set(0, 0, 0, 0); 6240 return true; 6241 } else { 6242 // The application wants to take care of fitting system window for 6243 // the content... however we still need to take care of any overscan here. 6244 final Rect overscan = mAttachInfo.mOverscanInsets; 6245 outLocalInsets.set(overscan); 6246 inoutInsets.left -= overscan.left; 6247 inoutInsets.top -= overscan.top; 6248 inoutInsets.right -= overscan.right; 6249 inoutInsets.bottom -= overscan.bottom; 6250 return false; 6251 } 6252 } 6253 6254 /** 6255 * Sets whether or not this view should account for system screen decorations 6256 * such as the status bar and inset its content; that is, controlling whether 6257 * the default implementation of {@link #fitSystemWindows(Rect)} will be 6258 * executed. See that method for more details. 6259 * 6260 * <p>Note that if you are providing your own implementation of 6261 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 6262 * flag to true -- your implementation will be overriding the default 6263 * implementation that checks this flag. 6264 * 6265 * @param fitSystemWindows If true, then the default implementation of 6266 * {@link #fitSystemWindows(Rect)} will be executed. 6267 * 6268 * @attr ref android.R.styleable#View_fitsSystemWindows 6269 * @see #getFitsSystemWindows() 6270 * @see #fitSystemWindows(Rect) 6271 * @see #setSystemUiVisibility(int) 6272 */ 6273 public void setFitsSystemWindows(boolean fitSystemWindows) { 6274 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 6275 } 6276 6277 /** 6278 * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method 6279 * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)} 6280 * will be executed. 6281 * 6282 * @return {@code true} if the default implementation of 6283 * {@link #fitSystemWindows(Rect)} will be executed. 6284 * 6285 * @attr ref android.R.styleable#View_fitsSystemWindows 6286 * @see #setFitsSystemWindows(boolean) 6287 * @see #fitSystemWindows(Rect) 6288 * @see #setSystemUiVisibility(int) 6289 */ 6290 public boolean getFitsSystemWindows() { 6291 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 6292 } 6293 6294 /** @hide */ 6295 public boolean fitsSystemWindows() { 6296 return getFitsSystemWindows(); 6297 } 6298 6299 /** 6300 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 6301 * @deprecated Use {@link #requestApplyInsets()} for newer platform versions. 6302 */ 6303 public void requestFitSystemWindows() { 6304 if (mParent != null) { 6305 mParent.requestFitSystemWindows(); 6306 } 6307 } 6308 6309 /** 6310 * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed. 6311 */ 6312 public void requestApplyInsets() { 6313 requestFitSystemWindows(); 6314 } 6315 6316 /** 6317 * For use by PhoneWindow to make its own system window fitting optional. 6318 * @hide 6319 */ 6320 public void makeOptionalFitsSystemWindows() { 6321 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 6322 } 6323 6324 /** 6325 * Returns the visibility status for this view. 6326 * 6327 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6328 * @attr ref android.R.styleable#View_visibility 6329 */ 6330 @ViewDebug.ExportedProperty(mapping = { 6331 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 6332 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 6333 @ViewDebug.IntToString(from = GONE, to = "GONE") 6334 }) 6335 @Visibility 6336 public int getVisibility() { 6337 return mViewFlags & VISIBILITY_MASK; 6338 } 6339 6340 /** 6341 * Set the enabled state of this view. 6342 * 6343 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6344 * @attr ref android.R.styleable#View_visibility 6345 */ 6346 @RemotableViewMethod 6347 public void setVisibility(@Visibility int visibility) { 6348 setFlags(visibility, VISIBILITY_MASK); 6349 if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false); 6350 } 6351 6352 /** 6353 * Returns the enabled status for this view. The interpretation of the 6354 * enabled state varies by subclass. 6355 * 6356 * @return True if this view is enabled, false otherwise. 6357 */ 6358 @ViewDebug.ExportedProperty 6359 public boolean isEnabled() { 6360 return (mViewFlags & ENABLED_MASK) == ENABLED; 6361 } 6362 6363 /** 6364 * Set the enabled state of this view. The interpretation of the enabled 6365 * state varies by subclass. 6366 * 6367 * @param enabled True if this view is enabled, false otherwise. 6368 */ 6369 @RemotableViewMethod 6370 public void setEnabled(boolean enabled) { 6371 if (enabled == isEnabled()) return; 6372 6373 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 6374 6375 /* 6376 * The View most likely has to change its appearance, so refresh 6377 * the drawable state. 6378 */ 6379 refreshDrawableState(); 6380 6381 // Invalidate too, since the default behavior for views is to be 6382 // be drawn at 50% alpha rather than to change the drawable. 6383 invalidate(true); 6384 6385 if (!enabled) { 6386 cancelPendingInputEvents(); 6387 } 6388 } 6389 6390 /** 6391 * Set whether this view can receive the focus. 6392 * 6393 * Setting this to false will also ensure that this view is not focusable 6394 * in touch mode. 6395 * 6396 * @param focusable If true, this view can receive the focus. 6397 * 6398 * @see #setFocusableInTouchMode(boolean) 6399 * @attr ref android.R.styleable#View_focusable 6400 */ 6401 public void setFocusable(boolean focusable) { 6402 if (!focusable) { 6403 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 6404 } 6405 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 6406 } 6407 6408 /** 6409 * Set whether this view can receive focus while in touch mode. 6410 * 6411 * Setting this to true will also ensure that this view is focusable. 6412 * 6413 * @param focusableInTouchMode If true, this view can receive the focus while 6414 * in touch mode. 6415 * 6416 * @see #setFocusable(boolean) 6417 * @attr ref android.R.styleable#View_focusableInTouchMode 6418 */ 6419 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 6420 // Focusable in touch mode should always be set before the focusable flag 6421 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 6422 // which, in touch mode, will not successfully request focus on this view 6423 // because the focusable in touch mode flag is not set 6424 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 6425 if (focusableInTouchMode) { 6426 setFlags(FOCUSABLE, FOCUSABLE_MASK); 6427 } 6428 } 6429 6430 /** 6431 * Set whether this view should have sound effects enabled for events such as 6432 * clicking and touching. 6433 * 6434 * <p>You may wish to disable sound effects for a view if you already play sounds, 6435 * for instance, a dial key that plays dtmf tones. 6436 * 6437 * @param soundEffectsEnabled whether sound effects are enabled for this view. 6438 * @see #isSoundEffectsEnabled() 6439 * @see #playSoundEffect(int) 6440 * @attr ref android.R.styleable#View_soundEffectsEnabled 6441 */ 6442 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 6443 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 6444 } 6445 6446 /** 6447 * @return whether this view should have sound effects enabled for events such as 6448 * clicking and touching. 6449 * 6450 * @see #setSoundEffectsEnabled(boolean) 6451 * @see #playSoundEffect(int) 6452 * @attr ref android.R.styleable#View_soundEffectsEnabled 6453 */ 6454 @ViewDebug.ExportedProperty 6455 public boolean isSoundEffectsEnabled() { 6456 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 6457 } 6458 6459 /** 6460 * Set whether this view should have haptic feedback for events such as 6461 * long presses. 6462 * 6463 * <p>You may wish to disable haptic feedback if your view already controls 6464 * its own haptic feedback. 6465 * 6466 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 6467 * @see #isHapticFeedbackEnabled() 6468 * @see #performHapticFeedback(int) 6469 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6470 */ 6471 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 6472 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 6473 } 6474 6475 /** 6476 * @return whether this view should have haptic feedback enabled for events 6477 * long presses. 6478 * 6479 * @see #setHapticFeedbackEnabled(boolean) 6480 * @see #performHapticFeedback(int) 6481 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6482 */ 6483 @ViewDebug.ExportedProperty 6484 public boolean isHapticFeedbackEnabled() { 6485 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 6486 } 6487 6488 /** 6489 * Returns the layout direction for this view. 6490 * 6491 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 6492 * {@link #LAYOUT_DIRECTION_RTL}, 6493 * {@link #LAYOUT_DIRECTION_INHERIT} or 6494 * {@link #LAYOUT_DIRECTION_LOCALE}. 6495 * 6496 * @attr ref android.R.styleable#View_layoutDirection 6497 * 6498 * @hide 6499 */ 6500 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6501 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 6502 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 6503 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 6504 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 6505 }) 6506 @LayoutDir 6507 public int getRawLayoutDirection() { 6508 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 6509 } 6510 6511 /** 6512 * Set the layout direction for this view. This will propagate a reset of layout direction 6513 * resolution to the view's children and resolve layout direction for this view. 6514 * 6515 * @param layoutDirection the layout direction to set. Should be one of: 6516 * 6517 * {@link #LAYOUT_DIRECTION_LTR}, 6518 * {@link #LAYOUT_DIRECTION_RTL}, 6519 * {@link #LAYOUT_DIRECTION_INHERIT}, 6520 * {@link #LAYOUT_DIRECTION_LOCALE}. 6521 * 6522 * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution 6523 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 6524 * will return the default {@link #LAYOUT_DIRECTION_LTR}. 6525 * 6526 * @attr ref android.R.styleable#View_layoutDirection 6527 */ 6528 @RemotableViewMethod 6529 public void setLayoutDirection(@LayoutDir int layoutDirection) { 6530 if (getRawLayoutDirection() != layoutDirection) { 6531 // Reset the current layout direction and the resolved one 6532 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 6533 resetRtlProperties(); 6534 // Set the new layout direction (filtered) 6535 mPrivateFlags2 |= 6536 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 6537 // We need to resolve all RTL properties as they all depend on layout direction 6538 resolveRtlPropertiesIfNeeded(); 6539 requestLayout(); 6540 invalidate(true); 6541 } 6542 } 6543 6544 /** 6545 * Returns the resolved layout direction for this view. 6546 * 6547 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 6548 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 6549 * 6550 * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version 6551 * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}. 6552 * 6553 * @attr ref android.R.styleable#View_layoutDirection 6554 */ 6555 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6556 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 6557 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 6558 }) 6559 @ResolvedLayoutDir 6560 public int getLayoutDirection() { 6561 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 6562 if (targetSdkVersion < JELLY_BEAN_MR1) { 6563 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 6564 return LAYOUT_DIRECTION_RESOLVED_DEFAULT; 6565 } 6566 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == 6567 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 6568 } 6569 6570 /** 6571 * Indicates whether or not this view's layout is right-to-left. This is resolved from 6572 * layout attribute and/or the inherited value from the parent 6573 * 6574 * @return true if the layout is right-to-left. 6575 * 6576 * @hide 6577 */ 6578 @ViewDebug.ExportedProperty(category = "layout") 6579 public boolean isLayoutRtl() { 6580 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 6581 } 6582 6583 /** 6584 * Indicates whether the view is currently tracking transient state that the 6585 * app should not need to concern itself with saving and restoring, but that 6586 * the framework should take special note to preserve when possible. 6587 * 6588 * <p>A view with transient state cannot be trivially rebound from an external 6589 * data source, such as an adapter binding item views in a list. This may be 6590 * because the view is performing an animation, tracking user selection 6591 * of content, or similar.</p> 6592 * 6593 * @return true if the view has transient state 6594 */ 6595 @ViewDebug.ExportedProperty(category = "layout") 6596 public boolean hasTransientState() { 6597 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 6598 } 6599 6600 /** 6601 * Set whether this view is currently tracking transient state that the 6602 * framework should attempt to preserve when possible. This flag is reference counted, 6603 * so every call to setHasTransientState(true) should be paired with a later call 6604 * to setHasTransientState(false). 6605 * 6606 * <p>A view with transient state cannot be trivially rebound from an external 6607 * data source, such as an adapter binding item views in a list. This may be 6608 * because the view is performing an animation, tracking user selection 6609 * of content, or similar.</p> 6610 * 6611 * @param hasTransientState true if this view has transient state 6612 */ 6613 public void setHasTransientState(boolean hasTransientState) { 6614 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 6615 mTransientStateCount - 1; 6616 if (mTransientStateCount < 0) { 6617 mTransientStateCount = 0; 6618 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 6619 "unmatched pair of setHasTransientState calls"); 6620 } else if ((hasTransientState && mTransientStateCount == 1) || 6621 (!hasTransientState && mTransientStateCount == 0)) { 6622 // update flag if we've just incremented up from 0 or decremented down to 0 6623 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 6624 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 6625 if (mParent != null) { 6626 try { 6627 mParent.childHasTransientStateChanged(this, hasTransientState); 6628 } catch (AbstractMethodError e) { 6629 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 6630 " does not fully implement ViewParent", e); 6631 } 6632 } 6633 } 6634 } 6635 6636 /** 6637 * Returns true if this view is currently attached to a window. 6638 */ 6639 public boolean isAttachedToWindow() { 6640 return mAttachInfo != null; 6641 } 6642 6643 /** 6644 * Returns true if this view has been through at least one layout since it 6645 * was last attached to or detached from a window. 6646 */ 6647 public boolean isLaidOut() { 6648 return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT; 6649 } 6650 6651 /** 6652 * If this view doesn't do any drawing on its own, set this flag to 6653 * allow further optimizations. By default, this flag is not set on 6654 * View, but could be set on some View subclasses such as ViewGroup. 6655 * 6656 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 6657 * you should clear this flag. 6658 * 6659 * @param willNotDraw whether or not this View draw on its own 6660 */ 6661 public void setWillNotDraw(boolean willNotDraw) { 6662 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 6663 } 6664 6665 /** 6666 * Returns whether or not this View draws on its own. 6667 * 6668 * @return true if this view has nothing to draw, false otherwise 6669 */ 6670 @ViewDebug.ExportedProperty(category = "drawing") 6671 public boolean willNotDraw() { 6672 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 6673 } 6674 6675 /** 6676 * When a View's drawing cache is enabled, drawing is redirected to an 6677 * offscreen bitmap. Some views, like an ImageView, must be able to 6678 * bypass this mechanism if they already draw a single bitmap, to avoid 6679 * unnecessary usage of the memory. 6680 * 6681 * @param willNotCacheDrawing true if this view does not cache its 6682 * drawing, false otherwise 6683 */ 6684 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 6685 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 6686 } 6687 6688 /** 6689 * Returns whether or not this View can cache its drawing or not. 6690 * 6691 * @return true if this view does not cache its drawing, false otherwise 6692 */ 6693 @ViewDebug.ExportedProperty(category = "drawing") 6694 public boolean willNotCacheDrawing() { 6695 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 6696 } 6697 6698 /** 6699 * Indicates whether this view reacts to click events or not. 6700 * 6701 * @return true if the view is clickable, false otherwise 6702 * 6703 * @see #setClickable(boolean) 6704 * @attr ref android.R.styleable#View_clickable 6705 */ 6706 @ViewDebug.ExportedProperty 6707 public boolean isClickable() { 6708 return (mViewFlags & CLICKABLE) == CLICKABLE; 6709 } 6710 6711 /** 6712 * Enables or disables click events for this view. When a view 6713 * is clickable it will change its state to "pressed" on every click. 6714 * Subclasses should set the view clickable to visually react to 6715 * user's clicks. 6716 * 6717 * @param clickable true to make the view clickable, false otherwise 6718 * 6719 * @see #isClickable() 6720 * @attr ref android.R.styleable#View_clickable 6721 */ 6722 public void setClickable(boolean clickable) { 6723 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 6724 } 6725 6726 /** 6727 * Indicates whether this view reacts to long click events or not. 6728 * 6729 * @return true if the view is long clickable, false otherwise 6730 * 6731 * @see #setLongClickable(boolean) 6732 * @attr ref android.R.styleable#View_longClickable 6733 */ 6734 public boolean isLongClickable() { 6735 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 6736 } 6737 6738 /** 6739 * Enables or disables long click events for this view. When a view is long 6740 * clickable it reacts to the user holding down the button for a longer 6741 * duration than a tap. This event can either launch the listener or a 6742 * context menu. 6743 * 6744 * @param longClickable true to make the view long clickable, false otherwise 6745 * @see #isLongClickable() 6746 * @attr ref android.R.styleable#View_longClickable 6747 */ 6748 public void setLongClickable(boolean longClickable) { 6749 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 6750 } 6751 6752 /** 6753 * Sets the pressed state for this view and provides a touch coordinate for 6754 * animation hinting. 6755 * 6756 * @param pressed Pass true to set the View's internal state to "pressed", 6757 * or false to reverts the View's internal state from a 6758 * previously set "pressed" state. 6759 * @param x The x coordinate of the touch that caused the press 6760 * @param y The y coordinate of the touch that caused the press 6761 */ 6762 private void setPressed(boolean pressed, float x, float y) { 6763 if (pressed) { 6764 setHotspot(x, y); 6765 } 6766 6767 setPressed(pressed); 6768 } 6769 6770 /** 6771 * Sets the pressed state for this view. 6772 * 6773 * @see #isClickable() 6774 * @see #setClickable(boolean) 6775 * 6776 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 6777 * the View's internal state from a previously set "pressed" state. 6778 */ 6779 public void setPressed(boolean pressed) { 6780 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 6781 6782 if (pressed) { 6783 mPrivateFlags |= PFLAG_PRESSED; 6784 } else { 6785 mPrivateFlags &= ~PFLAG_PRESSED; 6786 } 6787 6788 if (needsRefresh) { 6789 refreshDrawableState(); 6790 } 6791 dispatchSetPressed(pressed); 6792 } 6793 6794 /** 6795 * Dispatch setPressed to all of this View's children. 6796 * 6797 * @see #setPressed(boolean) 6798 * 6799 * @param pressed The new pressed state 6800 */ 6801 protected void dispatchSetPressed(boolean pressed) { 6802 } 6803 6804 /** 6805 * Indicates whether the view is currently in pressed state. Unless 6806 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 6807 * the pressed state. 6808 * 6809 * @see #setPressed(boolean) 6810 * @see #isClickable() 6811 * @see #setClickable(boolean) 6812 * 6813 * @return true if the view is currently pressed, false otherwise 6814 */ 6815 public boolean isPressed() { 6816 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 6817 } 6818 6819 /** 6820 * Indicates whether this view will save its state (that is, 6821 * whether its {@link #onSaveInstanceState} method will be called). 6822 * 6823 * @return Returns true if the view state saving is enabled, else false. 6824 * 6825 * @see #setSaveEnabled(boolean) 6826 * @attr ref android.R.styleable#View_saveEnabled 6827 */ 6828 public boolean isSaveEnabled() { 6829 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 6830 } 6831 6832 /** 6833 * Controls whether the saving of this view's state is 6834 * enabled (that is, whether its {@link #onSaveInstanceState} method 6835 * will be called). Note that even if freezing is enabled, the 6836 * view still must have an id assigned to it (via {@link #setId(int)}) 6837 * for its state to be saved. This flag can only disable the 6838 * saving of this view; any child views may still have their state saved. 6839 * 6840 * @param enabled Set to false to <em>disable</em> state saving, or true 6841 * (the default) to allow it. 6842 * 6843 * @see #isSaveEnabled() 6844 * @see #setId(int) 6845 * @see #onSaveInstanceState() 6846 * @attr ref android.R.styleable#View_saveEnabled 6847 */ 6848 public void setSaveEnabled(boolean enabled) { 6849 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 6850 } 6851 6852 /** 6853 * Gets whether the framework should discard touches when the view's 6854 * window is obscured by another visible window. 6855 * Refer to the {@link View} security documentation for more details. 6856 * 6857 * @return True if touch filtering is enabled. 6858 * 6859 * @see #setFilterTouchesWhenObscured(boolean) 6860 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6861 */ 6862 @ViewDebug.ExportedProperty 6863 public boolean getFilterTouchesWhenObscured() { 6864 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 6865 } 6866 6867 /** 6868 * Sets whether the framework should discard touches when the view's 6869 * window is obscured by another visible window. 6870 * Refer to the {@link View} security documentation for more details. 6871 * 6872 * @param enabled True if touch filtering should be enabled. 6873 * 6874 * @see #getFilterTouchesWhenObscured 6875 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6876 */ 6877 public void setFilterTouchesWhenObscured(boolean enabled) { 6878 setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0, 6879 FILTER_TOUCHES_WHEN_OBSCURED); 6880 } 6881 6882 /** 6883 * Indicates whether the entire hierarchy under this view will save its 6884 * state when a state saving traversal occurs from its parent. The default 6885 * is true; if false, these views will not be saved unless 6886 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6887 * 6888 * @return Returns true if the view state saving from parent is enabled, else false. 6889 * 6890 * @see #setSaveFromParentEnabled(boolean) 6891 */ 6892 public boolean isSaveFromParentEnabled() { 6893 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 6894 } 6895 6896 /** 6897 * Controls whether the entire hierarchy under this view will save its 6898 * state when a state saving traversal occurs from its parent. The default 6899 * is true; if false, these views will not be saved unless 6900 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6901 * 6902 * @param enabled Set to false to <em>disable</em> state saving, or true 6903 * (the default) to allow it. 6904 * 6905 * @see #isSaveFromParentEnabled() 6906 * @see #setId(int) 6907 * @see #onSaveInstanceState() 6908 */ 6909 public void setSaveFromParentEnabled(boolean enabled) { 6910 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 6911 } 6912 6913 6914 /** 6915 * Returns whether this View is able to take focus. 6916 * 6917 * @return True if this view can take focus, or false otherwise. 6918 * @attr ref android.R.styleable#View_focusable 6919 */ 6920 @ViewDebug.ExportedProperty(category = "focus") 6921 public final boolean isFocusable() { 6922 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 6923 } 6924 6925 /** 6926 * When a view is focusable, it may not want to take focus when in touch mode. 6927 * For example, a button would like focus when the user is navigating via a D-pad 6928 * so that the user can click on it, but once the user starts touching the screen, 6929 * the button shouldn't take focus 6930 * @return Whether the view is focusable in touch mode. 6931 * @attr ref android.R.styleable#View_focusableInTouchMode 6932 */ 6933 @ViewDebug.ExportedProperty 6934 public final boolean isFocusableInTouchMode() { 6935 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 6936 } 6937 6938 /** 6939 * Find the nearest view in the specified direction that can take focus. 6940 * This does not actually give focus to that view. 6941 * 6942 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 6943 * 6944 * @return The nearest focusable in the specified direction, or null if none 6945 * can be found. 6946 */ 6947 public View focusSearch(@FocusRealDirection int direction) { 6948 if (mParent != null) { 6949 return mParent.focusSearch(this, direction); 6950 } else { 6951 return null; 6952 } 6953 } 6954 6955 /** 6956 * This method is the last chance for the focused view and its ancestors to 6957 * respond to an arrow key. This is called when the focused view did not 6958 * consume the key internally, nor could the view system find a new view in 6959 * the requested direction to give focus to. 6960 * 6961 * @param focused The currently focused view. 6962 * @param direction The direction focus wants to move. One of FOCUS_UP, 6963 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 6964 * @return True if the this view consumed this unhandled move. 6965 */ 6966 public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) { 6967 return false; 6968 } 6969 6970 /** 6971 * If a user manually specified the next view id for a particular direction, 6972 * use the root to look up the view. 6973 * @param root The root view of the hierarchy containing this view. 6974 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 6975 * or FOCUS_BACKWARD. 6976 * @return The user specified next view, or null if there is none. 6977 */ 6978 View findUserSetNextFocus(View root, @FocusDirection int direction) { 6979 switch (direction) { 6980 case FOCUS_LEFT: 6981 if (mNextFocusLeftId == View.NO_ID) return null; 6982 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 6983 case FOCUS_RIGHT: 6984 if (mNextFocusRightId == View.NO_ID) return null; 6985 return findViewInsideOutShouldExist(root, mNextFocusRightId); 6986 case FOCUS_UP: 6987 if (mNextFocusUpId == View.NO_ID) return null; 6988 return findViewInsideOutShouldExist(root, mNextFocusUpId); 6989 case FOCUS_DOWN: 6990 if (mNextFocusDownId == View.NO_ID) return null; 6991 return findViewInsideOutShouldExist(root, mNextFocusDownId); 6992 case FOCUS_FORWARD: 6993 if (mNextFocusForwardId == View.NO_ID) return null; 6994 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 6995 case FOCUS_BACKWARD: { 6996 if (mID == View.NO_ID) return null; 6997 final int id = mID; 6998 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 6999 @Override 7000 public boolean apply(View t) { 7001 return t.mNextFocusForwardId == id; 7002 } 7003 }); 7004 } 7005 } 7006 return null; 7007 } 7008 7009 private View findViewInsideOutShouldExist(View root, int id) { 7010 if (mMatchIdPredicate == null) { 7011 mMatchIdPredicate = new MatchIdPredicate(); 7012 } 7013 mMatchIdPredicate.mId = id; 7014 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 7015 if (result == null) { 7016 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 7017 } 7018 return result; 7019 } 7020 7021 /** 7022 * Find and return all focusable views that are descendants of this view, 7023 * possibly including this view if it is focusable itself. 7024 * 7025 * @param direction The direction of the focus 7026 * @return A list of focusable views 7027 */ 7028 public ArrayList<View> getFocusables(@FocusDirection int direction) { 7029 ArrayList<View> result = new ArrayList<View>(24); 7030 addFocusables(result, direction); 7031 return result; 7032 } 7033 7034 /** 7035 * Add any focusable views that are descendants of this view (possibly 7036 * including this view if it is focusable itself) to views. If we are in touch mode, 7037 * only add views that are also focusable in touch mode. 7038 * 7039 * @param views Focusable views found so far 7040 * @param direction The direction of the focus 7041 */ 7042 public void addFocusables(ArrayList<View> views, @FocusDirection int direction) { 7043 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 7044 } 7045 7046 /** 7047 * Adds any focusable views that are descendants of this view (possibly 7048 * including this view if it is focusable itself) to views. This method 7049 * adds all focusable views regardless if we are in touch mode or 7050 * only views focusable in touch mode if we are in touch mode or 7051 * only views that can take accessibility focus if accessibility is enabeld 7052 * depending on the focusable mode paramater. 7053 * 7054 * @param views Focusable views found so far or null if all we are interested is 7055 * the number of focusables. 7056 * @param direction The direction of the focus. 7057 * @param focusableMode The type of focusables to be added. 7058 * 7059 * @see #FOCUSABLES_ALL 7060 * @see #FOCUSABLES_TOUCH_MODE 7061 */ 7062 public void addFocusables(ArrayList<View> views, @FocusDirection int direction, 7063 @FocusableMode int focusableMode) { 7064 if (views == null) { 7065 return; 7066 } 7067 if (!isFocusable()) { 7068 return; 7069 } 7070 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 7071 && isInTouchMode() && !isFocusableInTouchMode()) { 7072 return; 7073 } 7074 views.add(this); 7075 } 7076 7077 /** 7078 * Finds the Views that contain given text. The containment is case insensitive. 7079 * The search is performed by either the text that the View renders or the content 7080 * description that describes the view for accessibility purposes and the view does 7081 * not render or both. Clients can specify how the search is to be performed via 7082 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 7083 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 7084 * 7085 * @param outViews The output list of matching Views. 7086 * @param searched The text to match against. 7087 * 7088 * @see #FIND_VIEWS_WITH_TEXT 7089 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 7090 * @see #setContentDescription(CharSequence) 7091 */ 7092 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, 7093 @FindViewFlags int flags) { 7094 if (getAccessibilityNodeProvider() != null) { 7095 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 7096 outViews.add(this); 7097 } 7098 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 7099 && (searched != null && searched.length() > 0) 7100 && (mContentDescription != null && mContentDescription.length() > 0)) { 7101 String searchedLowerCase = searched.toString().toLowerCase(); 7102 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 7103 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 7104 outViews.add(this); 7105 } 7106 } 7107 } 7108 7109 /** 7110 * Find and return all touchable views that are descendants of this view, 7111 * possibly including this view if it is touchable itself. 7112 * 7113 * @return A list of touchable views 7114 */ 7115 public ArrayList<View> getTouchables() { 7116 ArrayList<View> result = new ArrayList<View>(); 7117 addTouchables(result); 7118 return result; 7119 } 7120 7121 /** 7122 * Add any touchable views that are descendants of this view (possibly 7123 * including this view if it is touchable itself) to views. 7124 * 7125 * @param views Touchable views found so far 7126 */ 7127 public void addTouchables(ArrayList<View> views) { 7128 final int viewFlags = mViewFlags; 7129 7130 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 7131 && (viewFlags & ENABLED_MASK) == ENABLED) { 7132 views.add(this); 7133 } 7134 } 7135 7136 /** 7137 * Returns whether this View is accessibility focused. 7138 * 7139 * @return True if this View is accessibility focused. 7140 */ 7141 public boolean isAccessibilityFocused() { 7142 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 7143 } 7144 7145 /** 7146 * Call this to try to give accessibility focus to this view. 7147 * 7148 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 7149 * returns false or the view is no visible or the view already has accessibility 7150 * focus. 7151 * 7152 * See also {@link #focusSearch(int)}, which is what you call to say that you 7153 * have focus, and you want your parent to look for the next one. 7154 * 7155 * @return Whether this view actually took accessibility focus. 7156 * 7157 * @hide 7158 */ 7159 public boolean requestAccessibilityFocus() { 7160 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 7161 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 7162 return false; 7163 } 7164 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7165 return false; 7166 } 7167 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 7168 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 7169 ViewRootImpl viewRootImpl = getViewRootImpl(); 7170 if (viewRootImpl != null) { 7171 viewRootImpl.setAccessibilityFocus(this, null); 7172 } 7173 Rect rect = (mAttachInfo != null) ? mAttachInfo.mTmpInvalRect : new Rect(); 7174 getDrawingRect(rect); 7175 requestRectangleOnScreen(rect, false); 7176 invalidate(); 7177 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 7178 return true; 7179 } 7180 return false; 7181 } 7182 7183 /** 7184 * Call this to try to clear accessibility focus of this view. 7185 * 7186 * See also {@link #focusSearch(int)}, which is what you call to say that you 7187 * have focus, and you want your parent to look for the next one. 7188 * 7189 * @hide 7190 */ 7191 public void clearAccessibilityFocus() { 7192 clearAccessibilityFocusNoCallbacks(); 7193 // Clear the global reference of accessibility focus if this 7194 // view or any of its descendants had accessibility focus. 7195 ViewRootImpl viewRootImpl = getViewRootImpl(); 7196 if (viewRootImpl != null) { 7197 View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 7198 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 7199 viewRootImpl.setAccessibilityFocus(null, null); 7200 } 7201 } 7202 } 7203 7204 private void sendAccessibilityHoverEvent(int eventType) { 7205 // Since we are not delivering to a client accessibility events from not 7206 // important views (unless the clinet request that) we need to fire the 7207 // event from the deepest view exposed to the client. As a consequence if 7208 // the user crosses a not exposed view the client will see enter and exit 7209 // of the exposed predecessor followed by and enter and exit of that same 7210 // predecessor when entering and exiting the not exposed descendant. This 7211 // is fine since the client has a clear idea which view is hovered at the 7212 // price of a couple more events being sent. This is a simple and 7213 // working solution. 7214 View source = this; 7215 while (true) { 7216 if (source.includeForAccessibility()) { 7217 source.sendAccessibilityEvent(eventType); 7218 return; 7219 } 7220 ViewParent parent = source.getParent(); 7221 if (parent instanceof View) { 7222 source = (View) parent; 7223 } else { 7224 return; 7225 } 7226 } 7227 } 7228 7229 /** 7230 * Clears accessibility focus without calling any callback methods 7231 * normally invoked in {@link #clearAccessibilityFocus()}. This method 7232 * is used for clearing accessibility focus when giving this focus to 7233 * another view. 7234 */ 7235 void clearAccessibilityFocusNoCallbacks() { 7236 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 7237 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 7238 invalidate(); 7239 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 7240 } 7241 } 7242 7243 /** 7244 * Call this to try to give focus to a specific view or to one of its 7245 * descendants. 7246 * 7247 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7248 * false), or if it is focusable and it is not focusable in touch mode 7249 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7250 * 7251 * See also {@link #focusSearch(int)}, which is what you call to say that you 7252 * have focus, and you want your parent to look for the next one. 7253 * 7254 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 7255 * {@link #FOCUS_DOWN} and <code>null</code>. 7256 * 7257 * @return Whether this view or one of its descendants actually took focus. 7258 */ 7259 public final boolean requestFocus() { 7260 return requestFocus(View.FOCUS_DOWN); 7261 } 7262 7263 /** 7264 * Call this to try to give focus to a specific view or to one of its 7265 * descendants and give it a hint about what direction focus is heading. 7266 * 7267 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7268 * false), or if it is focusable and it is not focusable in touch mode 7269 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7270 * 7271 * See also {@link #focusSearch(int)}, which is what you call to say that you 7272 * have focus, and you want your parent to look for the next one. 7273 * 7274 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 7275 * <code>null</code> set for the previously focused rectangle. 7276 * 7277 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7278 * @return Whether this view or one of its descendants actually took focus. 7279 */ 7280 public final boolean requestFocus(int direction) { 7281 return requestFocus(direction, null); 7282 } 7283 7284 /** 7285 * Call this to try to give focus to a specific view or to one of its descendants 7286 * and give it hints about the direction and a specific rectangle that the focus 7287 * is coming from. The rectangle can help give larger views a finer grained hint 7288 * about where focus is coming from, and therefore, where to show selection, or 7289 * forward focus change internally. 7290 * 7291 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7292 * false), or if it is focusable and it is not focusable in touch mode 7293 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7294 * 7295 * A View will not take focus if it is not visible. 7296 * 7297 * A View will not take focus if one of its parents has 7298 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 7299 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 7300 * 7301 * See also {@link #focusSearch(int)}, which is what you call to say that you 7302 * have focus, and you want your parent to look for the next one. 7303 * 7304 * You may wish to override this method if your custom {@link View} has an internal 7305 * {@link View} that it wishes to forward the request to. 7306 * 7307 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7308 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 7309 * to give a finer grained hint about where focus is coming from. May be null 7310 * if there is no hint. 7311 * @return Whether this view or one of its descendants actually took focus. 7312 */ 7313 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 7314 return requestFocusNoSearch(direction, previouslyFocusedRect); 7315 } 7316 7317 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 7318 // need to be focusable 7319 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 7320 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7321 return false; 7322 } 7323 7324 // need to be focusable in touch mode if in touch mode 7325 if (isInTouchMode() && 7326 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 7327 return false; 7328 } 7329 7330 // need to not have any parents blocking us 7331 if (hasAncestorThatBlocksDescendantFocus()) { 7332 return false; 7333 } 7334 7335 handleFocusGainInternal(direction, previouslyFocusedRect); 7336 return true; 7337 } 7338 7339 /** 7340 * Call this to try to give focus to a specific view or to one of its descendants. This is a 7341 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 7342 * touch mode to request focus when they are touched. 7343 * 7344 * @return Whether this view or one of its descendants actually took focus. 7345 * 7346 * @see #isInTouchMode() 7347 * 7348 */ 7349 public final boolean requestFocusFromTouch() { 7350 // Leave touch mode if we need to 7351 if (isInTouchMode()) { 7352 ViewRootImpl viewRoot = getViewRootImpl(); 7353 if (viewRoot != null) { 7354 viewRoot.ensureTouchMode(false); 7355 } 7356 } 7357 return requestFocus(View.FOCUS_DOWN); 7358 } 7359 7360 /** 7361 * @return Whether any ancestor of this view blocks descendant focus. 7362 */ 7363 private boolean hasAncestorThatBlocksDescendantFocus() { 7364 ViewParent ancestor = mParent; 7365 while (ancestor instanceof ViewGroup) { 7366 final ViewGroup vgAncestor = (ViewGroup) ancestor; 7367 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) { 7368 return true; 7369 } else { 7370 ancestor = vgAncestor.getParent(); 7371 } 7372 } 7373 return false; 7374 } 7375 7376 /** 7377 * Gets the mode for determining whether this View is important for accessibility 7378 * which is if it fires accessibility events and if it is reported to 7379 * accessibility services that query the screen. 7380 * 7381 * @return The mode for determining whether a View is important for accessibility. 7382 * 7383 * @attr ref android.R.styleable#View_importantForAccessibility 7384 * 7385 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7386 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7387 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7388 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7389 */ 7390 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 7391 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 7392 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 7393 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"), 7394 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS, 7395 to = "noHideDescendants") 7396 }) 7397 public int getImportantForAccessibility() { 7398 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7399 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7400 } 7401 7402 /** 7403 * Sets the live region mode for this view. This indicates to accessibility 7404 * services whether they should automatically notify the user about changes 7405 * to the view's content description or text, or to the content descriptions 7406 * or text of the view's children (where applicable). 7407 * <p> 7408 * For example, in a login screen with a TextView that displays an "incorrect 7409 * password" notification, that view should be marked as a live region with 7410 * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7411 * <p> 7412 * To disable change notifications for this view, use 7413 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region 7414 * mode for most views. 7415 * <p> 7416 * To indicate that the user should be notified of changes, use 7417 * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7418 * <p> 7419 * If the view's changes should interrupt ongoing speech and notify the user 7420 * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}. 7421 * 7422 * @param mode The live region mode for this view, one of: 7423 * <ul> 7424 * <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE} 7425 * <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE} 7426 * <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE} 7427 * </ul> 7428 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7429 */ 7430 public void setAccessibilityLiveRegion(int mode) { 7431 if (mode != getAccessibilityLiveRegion()) { 7432 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7433 mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT) 7434 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7435 notifyViewAccessibilityStateChangedIfNeeded( 7436 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7437 } 7438 } 7439 7440 /** 7441 * Gets the live region mode for this View. 7442 * 7443 * @return The live region mode for the view. 7444 * 7445 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7446 * 7447 * @see #setAccessibilityLiveRegion(int) 7448 */ 7449 public int getAccessibilityLiveRegion() { 7450 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK) 7451 >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 7452 } 7453 7454 /** 7455 * Sets how to determine whether this view is important for accessibility 7456 * which is if it fires accessibility events and if it is reported to 7457 * accessibility services that query the screen. 7458 * 7459 * @param mode How to determine whether this view is important for accessibility. 7460 * 7461 * @attr ref android.R.styleable#View_importantForAccessibility 7462 * 7463 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7464 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7465 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7466 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7467 */ 7468 public void setImportantForAccessibility(int mode) { 7469 final int oldMode = getImportantForAccessibility(); 7470 if (mode != oldMode) { 7471 // If we're moving between AUTO and another state, we might not need 7472 // to send a subtree changed notification. We'll store the computed 7473 // importance, since we'll need to check it later to make sure. 7474 final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO 7475 || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO; 7476 final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility(); 7477 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7478 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 7479 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7480 if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) { 7481 notifySubtreeAccessibilityStateChangedIfNeeded(); 7482 } else { 7483 notifyViewAccessibilityStateChangedIfNeeded( 7484 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7485 } 7486 } 7487 } 7488 7489 /** 7490 * Computes whether this view should be exposed for accessibility. In 7491 * general, views that are interactive or provide information are exposed 7492 * while views that serve only as containers are hidden. 7493 * <p> 7494 * If an ancestor of this view has importance 7495 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method 7496 * returns <code>false</code>. 7497 * <p> 7498 * Otherwise, the value is computed according to the view's 7499 * {@link #getImportantForAccessibility()} value: 7500 * <ol> 7501 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or 7502 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false 7503 * </code> 7504 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code> 7505 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if 7506 * view satisfies any of the following: 7507 * <ul> 7508 * <li>Is actionable, e.g. {@link #isClickable()}, 7509 * {@link #isLongClickable()}, or {@link #isFocusable()} 7510 * <li>Has an {@link AccessibilityDelegate} 7511 * <li>Has an interaction listener, e.g. {@link OnTouchListener}, 7512 * {@link OnKeyListener}, etc. 7513 * <li>Is an accessibility live region, e.g. 7514 * {@link #getAccessibilityLiveRegion()} is not 7515 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. 7516 * </ul> 7517 * </ol> 7518 * 7519 * @return Whether the view is exposed for accessibility. 7520 * @see #setImportantForAccessibility(int) 7521 * @see #getImportantForAccessibility() 7522 */ 7523 public boolean isImportantForAccessibility() { 7524 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7525 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7526 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO 7527 || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 7528 return false; 7529 } 7530 7531 // Check parent mode to ensure we're not hidden. 7532 ViewParent parent = mParent; 7533 while (parent instanceof View) { 7534 if (((View) parent).getImportantForAccessibility() 7535 == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 7536 return false; 7537 } 7538 parent = parent.getParent(); 7539 } 7540 7541 return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility() 7542 || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null 7543 || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE; 7544 } 7545 7546 /** 7547 * Gets the parent for accessibility purposes. Note that the parent for 7548 * accessibility is not necessary the immediate parent. It is the first 7549 * predecessor that is important for accessibility. 7550 * 7551 * @return The parent for accessibility purposes. 7552 */ 7553 public ViewParent getParentForAccessibility() { 7554 if (mParent instanceof View) { 7555 View parentView = (View) mParent; 7556 if (parentView.includeForAccessibility()) { 7557 return mParent; 7558 } else { 7559 return mParent.getParentForAccessibility(); 7560 } 7561 } 7562 return null; 7563 } 7564 7565 /** 7566 * Adds the children of a given View for accessibility. Since some Views are 7567 * not important for accessibility the children for accessibility are not 7568 * necessarily direct children of the view, rather they are the first level of 7569 * descendants important for accessibility. 7570 * 7571 * @param children The list of children for accessibility. 7572 */ 7573 public void addChildrenForAccessibility(ArrayList<View> children) { 7574 7575 } 7576 7577 /** 7578 * Whether to regard this view for accessibility. A view is regarded for 7579 * accessibility if it is important for accessibility or the querying 7580 * accessibility service has explicitly requested that view not 7581 * important for accessibility are regarded. 7582 * 7583 * @return Whether to regard the view for accessibility. 7584 * 7585 * @hide 7586 */ 7587 public boolean includeForAccessibility() { 7588 if (mAttachInfo != null) { 7589 return (mAttachInfo.mAccessibilityFetchFlags 7590 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0 7591 || isImportantForAccessibility(); 7592 } 7593 return false; 7594 } 7595 7596 /** 7597 * Returns whether the View is considered actionable from 7598 * accessibility perspective. Such view are important for 7599 * accessibility. 7600 * 7601 * @return True if the view is actionable for accessibility. 7602 * 7603 * @hide 7604 */ 7605 public boolean isActionableForAccessibility() { 7606 return (isClickable() || isLongClickable() || isFocusable()); 7607 } 7608 7609 /** 7610 * Returns whether the View has registered callbacks which makes it 7611 * important for accessibility. 7612 * 7613 * @return True if the view is actionable for accessibility. 7614 */ 7615 private boolean hasListenersForAccessibility() { 7616 ListenerInfo info = getListenerInfo(); 7617 return mTouchDelegate != null || info.mOnKeyListener != null 7618 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 7619 || info.mOnHoverListener != null || info.mOnDragListener != null; 7620 } 7621 7622 /** 7623 * Notifies that the accessibility state of this view changed. The change 7624 * is local to this view and does not represent structural changes such 7625 * as children and parent. For example, the view became focusable. The 7626 * notification is at at most once every 7627 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7628 * to avoid unnecessary load to the system. Also once a view has a pending 7629 * notification this method is a NOP until the notification has been sent. 7630 * 7631 * @hide 7632 */ 7633 public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) { 7634 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7635 return; 7636 } 7637 if (mSendViewStateChangedAccessibilityEvent == null) { 7638 mSendViewStateChangedAccessibilityEvent = 7639 new SendViewStateChangedAccessibilityEvent(); 7640 } 7641 mSendViewStateChangedAccessibilityEvent.runOrPost(changeType); 7642 } 7643 7644 /** 7645 * Notifies that the accessibility state of this view changed. The change 7646 * is *not* local to this view and does represent structural changes such 7647 * as children and parent. For example, the view size changed. The 7648 * notification is at at most once every 7649 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7650 * to avoid unnecessary load to the system. Also once a view has a pending 7651 * notifucation this method is a NOP until the notification has been sent. 7652 * 7653 * @hide 7654 */ 7655 public void notifySubtreeAccessibilityStateChangedIfNeeded() { 7656 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7657 return; 7658 } 7659 if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) { 7660 mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 7661 if (mParent != null) { 7662 try { 7663 mParent.notifySubtreeAccessibilityStateChanged( 7664 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE); 7665 } catch (AbstractMethodError e) { 7666 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 7667 " does not fully implement ViewParent", e); 7668 } 7669 } 7670 } 7671 } 7672 7673 /** 7674 * Reset the flag indicating the accessibility state of the subtree rooted 7675 * at this view changed. 7676 */ 7677 void resetSubtreeAccessibilityStateChanged() { 7678 mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 7679 } 7680 7681 /** 7682 * Performs the specified accessibility action on the view. For 7683 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 7684 * <p> 7685 * If an {@link AccessibilityDelegate} has been specified via calling 7686 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 7687 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 7688 * is responsible for handling this call. 7689 * </p> 7690 * 7691 * @param action The action to perform. 7692 * @param arguments Optional action arguments. 7693 * @return Whether the action was performed. 7694 */ 7695 public boolean performAccessibilityAction(int action, Bundle arguments) { 7696 if (mAccessibilityDelegate != null) { 7697 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 7698 } else { 7699 return performAccessibilityActionInternal(action, arguments); 7700 } 7701 } 7702 7703 /** 7704 * @see #performAccessibilityAction(int, Bundle) 7705 * 7706 * Note: Called from the default {@link AccessibilityDelegate}. 7707 */ 7708 boolean performAccessibilityActionInternal(int action, Bundle arguments) { 7709 switch (action) { 7710 case AccessibilityNodeInfo.ACTION_CLICK: { 7711 if (isClickable()) { 7712 performClick(); 7713 return true; 7714 } 7715 } break; 7716 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 7717 if (isLongClickable()) { 7718 performLongClick(); 7719 return true; 7720 } 7721 } break; 7722 case AccessibilityNodeInfo.ACTION_FOCUS: { 7723 if (!hasFocus()) { 7724 // Get out of touch mode since accessibility 7725 // wants to move focus around. 7726 getViewRootImpl().ensureTouchMode(false); 7727 return requestFocus(); 7728 } 7729 } break; 7730 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 7731 if (hasFocus()) { 7732 clearFocus(); 7733 return !isFocused(); 7734 } 7735 } break; 7736 case AccessibilityNodeInfo.ACTION_SELECT: { 7737 if (!isSelected()) { 7738 setSelected(true); 7739 return isSelected(); 7740 } 7741 } break; 7742 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 7743 if (isSelected()) { 7744 setSelected(false); 7745 return !isSelected(); 7746 } 7747 } break; 7748 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 7749 if (!isAccessibilityFocused()) { 7750 return requestAccessibilityFocus(); 7751 } 7752 } break; 7753 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 7754 if (isAccessibilityFocused()) { 7755 clearAccessibilityFocus(); 7756 return true; 7757 } 7758 } break; 7759 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 7760 if (arguments != null) { 7761 final int granularity = arguments.getInt( 7762 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 7763 final boolean extendSelection = arguments.getBoolean( 7764 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 7765 return traverseAtGranularity(granularity, true, extendSelection); 7766 } 7767 } break; 7768 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 7769 if (arguments != null) { 7770 final int granularity = arguments.getInt( 7771 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 7772 final boolean extendSelection = arguments.getBoolean( 7773 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 7774 return traverseAtGranularity(granularity, false, extendSelection); 7775 } 7776 } break; 7777 case AccessibilityNodeInfo.ACTION_SET_SELECTION: { 7778 CharSequence text = getIterableTextForAccessibility(); 7779 if (text == null) { 7780 return false; 7781 } 7782 final int start = (arguments != null) ? arguments.getInt( 7783 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1; 7784 final int end = (arguments != null) ? arguments.getInt( 7785 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1; 7786 // Only cursor position can be specified (selection length == 0) 7787 if ((getAccessibilitySelectionStart() != start 7788 || getAccessibilitySelectionEnd() != end) 7789 && (start == end)) { 7790 setAccessibilitySelection(start, end); 7791 notifyViewAccessibilityStateChangedIfNeeded( 7792 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7793 return true; 7794 } 7795 } break; 7796 } 7797 return false; 7798 } 7799 7800 private boolean traverseAtGranularity(int granularity, boolean forward, 7801 boolean extendSelection) { 7802 CharSequence text = getIterableTextForAccessibility(); 7803 if (text == null || text.length() == 0) { 7804 return false; 7805 } 7806 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 7807 if (iterator == null) { 7808 return false; 7809 } 7810 int current = getAccessibilitySelectionEnd(); 7811 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 7812 current = forward ? 0 : text.length(); 7813 } 7814 final int[] range = forward ? iterator.following(current) : iterator.preceding(current); 7815 if (range == null) { 7816 return false; 7817 } 7818 final int segmentStart = range[0]; 7819 final int segmentEnd = range[1]; 7820 int selectionStart; 7821 int selectionEnd; 7822 if (extendSelection && isAccessibilitySelectionExtendable()) { 7823 selectionStart = getAccessibilitySelectionStart(); 7824 if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 7825 selectionStart = forward ? segmentStart : segmentEnd; 7826 } 7827 selectionEnd = forward ? segmentEnd : segmentStart; 7828 } else { 7829 selectionStart = selectionEnd= forward ? segmentEnd : segmentStart; 7830 } 7831 setAccessibilitySelection(selectionStart, selectionEnd); 7832 final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY 7833 : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY; 7834 sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd); 7835 return true; 7836 } 7837 7838 /** 7839 * Gets the text reported for accessibility purposes. 7840 * 7841 * @return The accessibility text. 7842 * 7843 * @hide 7844 */ 7845 public CharSequence getIterableTextForAccessibility() { 7846 return getContentDescription(); 7847 } 7848 7849 /** 7850 * Gets whether accessibility selection can be extended. 7851 * 7852 * @return If selection is extensible. 7853 * 7854 * @hide 7855 */ 7856 public boolean isAccessibilitySelectionExtendable() { 7857 return false; 7858 } 7859 7860 /** 7861 * @hide 7862 */ 7863 public int getAccessibilitySelectionStart() { 7864 return mAccessibilityCursorPosition; 7865 } 7866 7867 /** 7868 * @hide 7869 */ 7870 public int getAccessibilitySelectionEnd() { 7871 return getAccessibilitySelectionStart(); 7872 } 7873 7874 /** 7875 * @hide 7876 */ 7877 public void setAccessibilitySelection(int start, int end) { 7878 if (start == end && end == mAccessibilityCursorPosition) { 7879 return; 7880 } 7881 if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) { 7882 mAccessibilityCursorPosition = start; 7883 } else { 7884 mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 7885 } 7886 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 7887 } 7888 7889 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 7890 int fromIndex, int toIndex) { 7891 if (mParent == null) { 7892 return; 7893 } 7894 AccessibilityEvent event = AccessibilityEvent.obtain( 7895 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 7896 onInitializeAccessibilityEvent(event); 7897 onPopulateAccessibilityEvent(event); 7898 event.setFromIndex(fromIndex); 7899 event.setToIndex(toIndex); 7900 event.setAction(action); 7901 event.setMovementGranularity(granularity); 7902 mParent.requestSendAccessibilityEvent(this, event); 7903 } 7904 7905 /** 7906 * @hide 7907 */ 7908 public TextSegmentIterator getIteratorForGranularity(int granularity) { 7909 switch (granularity) { 7910 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 7911 CharSequence text = getIterableTextForAccessibility(); 7912 if (text != null && text.length() > 0) { 7913 CharacterTextSegmentIterator iterator = 7914 CharacterTextSegmentIterator.getInstance( 7915 mContext.getResources().getConfiguration().locale); 7916 iterator.initialize(text.toString()); 7917 return iterator; 7918 } 7919 } break; 7920 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 7921 CharSequence text = getIterableTextForAccessibility(); 7922 if (text != null && text.length() > 0) { 7923 WordTextSegmentIterator iterator = 7924 WordTextSegmentIterator.getInstance( 7925 mContext.getResources().getConfiguration().locale); 7926 iterator.initialize(text.toString()); 7927 return iterator; 7928 } 7929 } break; 7930 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 7931 CharSequence text = getIterableTextForAccessibility(); 7932 if (text != null && text.length() > 0) { 7933 ParagraphTextSegmentIterator iterator = 7934 ParagraphTextSegmentIterator.getInstance(); 7935 iterator.initialize(text.toString()); 7936 return iterator; 7937 } 7938 } break; 7939 } 7940 return null; 7941 } 7942 7943 /** 7944 * @hide 7945 */ 7946 public void dispatchStartTemporaryDetach() { 7947 onStartTemporaryDetach(); 7948 } 7949 7950 /** 7951 * This is called when a container is going to temporarily detach a child, with 7952 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 7953 * It will either be followed by {@link #onFinishTemporaryDetach()} or 7954 * {@link #onDetachedFromWindow()} when the container is done. 7955 */ 7956 public void onStartTemporaryDetach() { 7957 removeUnsetPressCallback(); 7958 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 7959 } 7960 7961 /** 7962 * @hide 7963 */ 7964 public void dispatchFinishTemporaryDetach() { 7965 onFinishTemporaryDetach(); 7966 } 7967 7968 /** 7969 * Called after {@link #onStartTemporaryDetach} when the container is done 7970 * changing the view. 7971 */ 7972 public void onFinishTemporaryDetach() { 7973 } 7974 7975 /** 7976 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 7977 * for this view's window. Returns null if the view is not currently attached 7978 * to the window. Normally you will not need to use this directly, but 7979 * just use the standard high-level event callbacks like 7980 * {@link #onKeyDown(int, KeyEvent)}. 7981 */ 7982 public KeyEvent.DispatcherState getKeyDispatcherState() { 7983 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 7984 } 7985 7986 /** 7987 * Dispatch a key event before it is processed by any input method 7988 * associated with the view hierarchy. This can be used to intercept 7989 * key events in special situations before the IME consumes them; a 7990 * typical example would be handling the BACK key to update the application's 7991 * UI instead of allowing the IME to see it and close itself. 7992 * 7993 * @param event The key event to be dispatched. 7994 * @return True if the event was handled, false otherwise. 7995 */ 7996 public boolean dispatchKeyEventPreIme(KeyEvent event) { 7997 return onKeyPreIme(event.getKeyCode(), event); 7998 } 7999 8000 /** 8001 * Dispatch a key event to the next view on the focus path. This path runs 8002 * from the top of the view tree down to the currently focused view. If this 8003 * view has focus, it will dispatch to itself. Otherwise it will dispatch 8004 * the next node down the focus path. This method also fires any key 8005 * listeners. 8006 * 8007 * @param event The key event to be dispatched. 8008 * @return True if the event was handled, false otherwise. 8009 */ 8010 public boolean dispatchKeyEvent(KeyEvent event) { 8011 if (mInputEventConsistencyVerifier != null) { 8012 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 8013 } 8014 8015 // Give any attached key listener a first crack at the event. 8016 //noinspection SimplifiableIfStatement 8017 ListenerInfo li = mListenerInfo; 8018 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 8019 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 8020 return true; 8021 } 8022 8023 if (event.dispatch(this, mAttachInfo != null 8024 ? mAttachInfo.mKeyDispatchState : null, this)) { 8025 return true; 8026 } 8027 8028 if (mInputEventConsistencyVerifier != null) { 8029 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8030 } 8031 return false; 8032 } 8033 8034 /** 8035 * Dispatches a key shortcut event. 8036 * 8037 * @param event The key event to be dispatched. 8038 * @return True if the event was handled by the view, false otherwise. 8039 */ 8040 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 8041 return onKeyShortcut(event.getKeyCode(), event); 8042 } 8043 8044 /** 8045 * Pass the touch screen motion event down to the target view, or this 8046 * view if it is the target. 8047 * 8048 * @param event The motion event to be dispatched. 8049 * @return True if the event was handled by the view, false otherwise. 8050 */ 8051 public boolean dispatchTouchEvent(MotionEvent event) { 8052 boolean result = false; 8053 8054 if (mInputEventConsistencyVerifier != null) { 8055 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 8056 } 8057 8058 final int actionMasked = event.getActionMasked(); 8059 if (actionMasked == MotionEvent.ACTION_DOWN) { 8060 // Defensive cleanup for new gesture 8061 stopNestedScroll(); 8062 } 8063 8064 if (onFilterTouchEventForSecurity(event)) { 8065 //noinspection SimplifiableIfStatement 8066 ListenerInfo li = mListenerInfo; 8067 if (li != null && li.mOnTouchListener != null 8068 && (mViewFlags & ENABLED_MASK) == ENABLED 8069 && li.mOnTouchListener.onTouch(this, event)) { 8070 result = true; 8071 } 8072 8073 if (!result && onTouchEvent(event)) { 8074 result = true; 8075 } 8076 } 8077 8078 if (!result && mInputEventConsistencyVerifier != null) { 8079 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8080 } 8081 8082 // Clean up after nested scrolls if this is the end of a gesture; 8083 // also cancel it if we tried an ACTION_DOWN but we didn't want the rest 8084 // of the gesture. 8085 if (actionMasked == MotionEvent.ACTION_UP || 8086 actionMasked == MotionEvent.ACTION_CANCEL || 8087 (actionMasked == MotionEvent.ACTION_DOWN && !result)) { 8088 stopNestedScroll(); 8089 } 8090 8091 return result; 8092 } 8093 8094 /** 8095 * Filter the touch event to apply security policies. 8096 * 8097 * @param event The motion event to be filtered. 8098 * @return True if the event should be dispatched, false if the event should be dropped. 8099 * 8100 * @see #getFilterTouchesWhenObscured 8101 */ 8102 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 8103 //noinspection RedundantIfStatement 8104 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 8105 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 8106 // Window is obscured, drop this touch. 8107 return false; 8108 } 8109 return true; 8110 } 8111 8112 /** 8113 * Pass a trackball motion event down to the focused view. 8114 * 8115 * @param event The motion event to be dispatched. 8116 * @return True if the event was handled by the view, false otherwise. 8117 */ 8118 public boolean dispatchTrackballEvent(MotionEvent event) { 8119 if (mInputEventConsistencyVerifier != null) { 8120 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 8121 } 8122 8123 return onTrackballEvent(event); 8124 } 8125 8126 /** 8127 * Dispatch a generic motion event. 8128 * <p> 8129 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 8130 * are delivered to the view under the pointer. All other generic motion events are 8131 * delivered to the focused view. Hover events are handled specially and are delivered 8132 * to {@link #onHoverEvent(MotionEvent)}. 8133 * </p> 8134 * 8135 * @param event The motion event to be dispatched. 8136 * @return True if the event was handled by the view, false otherwise. 8137 */ 8138 public boolean dispatchGenericMotionEvent(MotionEvent event) { 8139 if (mInputEventConsistencyVerifier != null) { 8140 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 8141 } 8142 8143 final int source = event.getSource(); 8144 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 8145 final int action = event.getAction(); 8146 if (action == MotionEvent.ACTION_HOVER_ENTER 8147 || action == MotionEvent.ACTION_HOVER_MOVE 8148 || action == MotionEvent.ACTION_HOVER_EXIT) { 8149 if (dispatchHoverEvent(event)) { 8150 return true; 8151 } 8152 } else if (dispatchGenericPointerEvent(event)) { 8153 return true; 8154 } 8155 } else if (dispatchGenericFocusedEvent(event)) { 8156 return true; 8157 } 8158 8159 if (dispatchGenericMotionEventInternal(event)) { 8160 return true; 8161 } 8162 8163 if (mInputEventConsistencyVerifier != null) { 8164 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8165 } 8166 return false; 8167 } 8168 8169 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 8170 //noinspection SimplifiableIfStatement 8171 ListenerInfo li = mListenerInfo; 8172 if (li != null && li.mOnGenericMotionListener != null 8173 && (mViewFlags & ENABLED_MASK) == ENABLED 8174 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 8175 return true; 8176 } 8177 8178 if (onGenericMotionEvent(event)) { 8179 return true; 8180 } 8181 8182 if (mInputEventConsistencyVerifier != null) { 8183 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8184 } 8185 return false; 8186 } 8187 8188 /** 8189 * Dispatch a hover event. 8190 * <p> 8191 * Do not call this method directly. 8192 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8193 * </p> 8194 * 8195 * @param event The motion event to be dispatched. 8196 * @return True if the event was handled by the view, false otherwise. 8197 */ 8198 protected boolean dispatchHoverEvent(MotionEvent event) { 8199 ListenerInfo li = mListenerInfo; 8200 //noinspection SimplifiableIfStatement 8201 if (li != null && li.mOnHoverListener != null 8202 && (mViewFlags & ENABLED_MASK) == ENABLED 8203 && li.mOnHoverListener.onHover(this, event)) { 8204 return true; 8205 } 8206 8207 return onHoverEvent(event); 8208 } 8209 8210 /** 8211 * Returns true if the view has a child to which it has recently sent 8212 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 8213 * it does not have a hovered child, then it must be the innermost hovered view. 8214 * @hide 8215 */ 8216 protected boolean hasHoveredChild() { 8217 return false; 8218 } 8219 8220 /** 8221 * Dispatch a generic motion event to the view under the first pointer. 8222 * <p> 8223 * Do not call this method directly. 8224 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8225 * </p> 8226 * 8227 * @param event The motion event to be dispatched. 8228 * @return True if the event was handled by the view, false otherwise. 8229 */ 8230 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 8231 return false; 8232 } 8233 8234 /** 8235 * Dispatch a generic motion event to the currently focused view. 8236 * <p> 8237 * Do not call this method directly. 8238 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8239 * </p> 8240 * 8241 * @param event The motion event to be dispatched. 8242 * @return True if the event was handled by the view, false otherwise. 8243 */ 8244 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 8245 return false; 8246 } 8247 8248 /** 8249 * Dispatch a pointer event. 8250 * <p> 8251 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 8252 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 8253 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 8254 * and should not be expected to handle other pointing device features. 8255 * </p> 8256 * 8257 * @param event The motion event to be dispatched. 8258 * @return True if the event was handled by the view, false otherwise. 8259 * @hide 8260 */ 8261 public final boolean dispatchPointerEvent(MotionEvent event) { 8262 if (event.isTouchEvent()) { 8263 return dispatchTouchEvent(event); 8264 } else { 8265 return dispatchGenericMotionEvent(event); 8266 } 8267 } 8268 8269 /** 8270 * Called when the window containing this view gains or loses window focus. 8271 * ViewGroups should override to route to their children. 8272 * 8273 * @param hasFocus True if the window containing this view now has focus, 8274 * false otherwise. 8275 */ 8276 public void dispatchWindowFocusChanged(boolean hasFocus) { 8277 onWindowFocusChanged(hasFocus); 8278 } 8279 8280 /** 8281 * Called when the window containing this view gains or loses focus. Note 8282 * that this is separate from view focus: to receive key events, both 8283 * your view and its window must have focus. If a window is displayed 8284 * on top of yours that takes input focus, then your own window will lose 8285 * focus but the view focus will remain unchanged. 8286 * 8287 * @param hasWindowFocus True if the window containing this view now has 8288 * focus, false otherwise. 8289 */ 8290 public void onWindowFocusChanged(boolean hasWindowFocus) { 8291 InputMethodManager imm = InputMethodManager.peekInstance(); 8292 if (!hasWindowFocus) { 8293 if (isPressed()) { 8294 setPressed(false); 8295 } 8296 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 8297 imm.focusOut(this); 8298 } 8299 removeLongPressCallback(); 8300 removeTapCallback(); 8301 onFocusLost(); 8302 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 8303 imm.focusIn(this); 8304 } 8305 refreshDrawableState(); 8306 } 8307 8308 /** 8309 * Returns true if this view is in a window that currently has window focus. 8310 * Note that this is not the same as the view itself having focus. 8311 * 8312 * @return True if this view is in a window that currently has window focus. 8313 */ 8314 public boolean hasWindowFocus() { 8315 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 8316 } 8317 8318 /** 8319 * Dispatch a view visibility change down the view hierarchy. 8320 * ViewGroups should override to route to their children. 8321 * @param changedView The view whose visibility changed. Could be 'this' or 8322 * an ancestor view. 8323 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 8324 * {@link #INVISIBLE} or {@link #GONE}. 8325 */ 8326 protected void dispatchVisibilityChanged(@NonNull View changedView, 8327 @Visibility int visibility) { 8328 onVisibilityChanged(changedView, visibility); 8329 } 8330 8331 /** 8332 * Called when the visibility of the view or an ancestor of the view is changed. 8333 * @param changedView The view whose visibility changed. Could be 'this' or 8334 * an ancestor view. 8335 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 8336 * {@link #INVISIBLE} or {@link #GONE}. 8337 */ 8338 protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) { 8339 if (visibility == VISIBLE) { 8340 if (mAttachInfo != null) { 8341 initialAwakenScrollBars(); 8342 } else { 8343 mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 8344 } 8345 } 8346 } 8347 8348 /** 8349 * Dispatch a hint about whether this view is displayed. For instance, when 8350 * a View moves out of the screen, it might receives a display hint indicating 8351 * the view is not displayed. Applications should not <em>rely</em> on this hint 8352 * as there is no guarantee that they will receive one. 8353 * 8354 * @param hint A hint about whether or not this view is displayed: 8355 * {@link #VISIBLE} or {@link #INVISIBLE}. 8356 */ 8357 public void dispatchDisplayHint(@Visibility int hint) { 8358 onDisplayHint(hint); 8359 } 8360 8361 /** 8362 * Gives this view a hint about whether is displayed or not. For instance, when 8363 * a View moves out of the screen, it might receives a display hint indicating 8364 * the view is not displayed. Applications should not <em>rely</em> on this hint 8365 * as there is no guarantee that they will receive one. 8366 * 8367 * @param hint A hint about whether or not this view is displayed: 8368 * {@link #VISIBLE} or {@link #INVISIBLE}. 8369 */ 8370 protected void onDisplayHint(@Visibility int hint) { 8371 } 8372 8373 /** 8374 * Dispatch a window visibility change down the view hierarchy. 8375 * ViewGroups should override to route to their children. 8376 * 8377 * @param visibility The new visibility of the window. 8378 * 8379 * @see #onWindowVisibilityChanged(int) 8380 */ 8381 public void dispatchWindowVisibilityChanged(@Visibility int visibility) { 8382 onWindowVisibilityChanged(visibility); 8383 } 8384 8385 /** 8386 * Called when the window containing has change its visibility 8387 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 8388 * that this tells you whether or not your window is being made visible 8389 * to the window manager; this does <em>not</em> tell you whether or not 8390 * your window is obscured by other windows on the screen, even if it 8391 * is itself visible. 8392 * 8393 * @param visibility The new visibility of the window. 8394 */ 8395 protected void onWindowVisibilityChanged(@Visibility int visibility) { 8396 if (visibility == VISIBLE) { 8397 initialAwakenScrollBars(); 8398 } 8399 } 8400 8401 /** 8402 * Returns the current visibility of the window this view is attached to 8403 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 8404 * 8405 * @return Returns the current visibility of the view's window. 8406 */ 8407 @Visibility 8408 public int getWindowVisibility() { 8409 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 8410 } 8411 8412 /** 8413 * Retrieve the overall visible display size in which the window this view is 8414 * attached to has been positioned in. This takes into account screen 8415 * decorations above the window, for both cases where the window itself 8416 * is being position inside of them or the window is being placed under 8417 * then and covered insets are used for the window to position its content 8418 * inside. In effect, this tells you the available area where content can 8419 * be placed and remain visible to users. 8420 * 8421 * <p>This function requires an IPC back to the window manager to retrieve 8422 * the requested information, so should not be used in performance critical 8423 * code like drawing. 8424 * 8425 * @param outRect Filled in with the visible display frame. If the view 8426 * is not attached to a window, this is simply the raw display size. 8427 */ 8428 public void getWindowVisibleDisplayFrame(Rect outRect) { 8429 if (mAttachInfo != null) { 8430 try { 8431 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 8432 } catch (RemoteException e) { 8433 return; 8434 } 8435 // XXX This is really broken, and probably all needs to be done 8436 // in the window manager, and we need to know more about whether 8437 // we want the area behind or in front of the IME. 8438 final Rect insets = mAttachInfo.mVisibleInsets; 8439 outRect.left += insets.left; 8440 outRect.top += insets.top; 8441 outRect.right -= insets.right; 8442 outRect.bottom -= insets.bottom; 8443 return; 8444 } 8445 // The view is not attached to a display so we don't have a context. 8446 // Make a best guess about the display size. 8447 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 8448 d.getRectSize(outRect); 8449 } 8450 8451 /** 8452 * Dispatch a notification about a resource configuration change down 8453 * the view hierarchy. 8454 * ViewGroups should override to route to their children. 8455 * 8456 * @param newConfig The new resource configuration. 8457 * 8458 * @see #onConfigurationChanged(android.content.res.Configuration) 8459 */ 8460 public void dispatchConfigurationChanged(Configuration newConfig) { 8461 onConfigurationChanged(newConfig); 8462 } 8463 8464 /** 8465 * Called when the current configuration of the resources being used 8466 * by the application have changed. You can use this to decide when 8467 * to reload resources that can changed based on orientation and other 8468 * configuration characterstics. You only need to use this if you are 8469 * not relying on the normal {@link android.app.Activity} mechanism of 8470 * recreating the activity instance upon a configuration change. 8471 * 8472 * @param newConfig The new resource configuration. 8473 */ 8474 protected void onConfigurationChanged(Configuration newConfig) { 8475 } 8476 8477 /** 8478 * Private function to aggregate all per-view attributes in to the view 8479 * root. 8480 */ 8481 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8482 performCollectViewAttributes(attachInfo, visibility); 8483 } 8484 8485 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8486 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 8487 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 8488 attachInfo.mKeepScreenOn = true; 8489 } 8490 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 8491 ListenerInfo li = mListenerInfo; 8492 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 8493 attachInfo.mHasSystemUiListeners = true; 8494 } 8495 } 8496 } 8497 8498 void needGlobalAttributesUpdate(boolean force) { 8499 final AttachInfo ai = mAttachInfo; 8500 if (ai != null && !ai.mRecomputeGlobalAttributes) { 8501 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 8502 || ai.mHasSystemUiListeners) { 8503 ai.mRecomputeGlobalAttributes = true; 8504 } 8505 } 8506 } 8507 8508 /** 8509 * Returns whether the device is currently in touch mode. Touch mode is entered 8510 * once the user begins interacting with the device by touch, and affects various 8511 * things like whether focus is always visible to the user. 8512 * 8513 * @return Whether the device is in touch mode. 8514 */ 8515 @ViewDebug.ExportedProperty 8516 public boolean isInTouchMode() { 8517 if (mAttachInfo != null) { 8518 return mAttachInfo.mInTouchMode; 8519 } else { 8520 return ViewRootImpl.isInTouchMode(); 8521 } 8522 } 8523 8524 /** 8525 * Returns the context the view is running in, through which it can 8526 * access the current theme, resources, etc. 8527 * 8528 * @return The view's Context. 8529 */ 8530 @ViewDebug.CapturedViewProperty 8531 public final Context getContext() { 8532 return mContext; 8533 } 8534 8535 /** 8536 * Handle a key event before it is processed by any input method 8537 * associated with the view hierarchy. This can be used to intercept 8538 * key events in special situations before the IME consumes them; a 8539 * typical example would be handling the BACK key to update the application's 8540 * UI instead of allowing the IME to see it and close itself. 8541 * 8542 * @param keyCode The value in event.getKeyCode(). 8543 * @param event Description of the key event. 8544 * @return If you handled the event, return true. If you want to allow the 8545 * event to be handled by the next receiver, return false. 8546 */ 8547 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 8548 return false; 8549 } 8550 8551 /** 8552 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 8553 * KeyEvent.Callback.onKeyDown()}: perform press of the view 8554 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 8555 * is released, if the view is enabled and clickable. 8556 * 8557 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8558 * although some may elect to do so in some situations. Do not rely on this to 8559 * catch software key presses. 8560 * 8561 * @param keyCode A key code that represents the button pressed, from 8562 * {@link android.view.KeyEvent}. 8563 * @param event The KeyEvent object that defines the button action. 8564 */ 8565 public boolean onKeyDown(int keyCode, KeyEvent event) { 8566 boolean result = false; 8567 8568 if (KeyEvent.isConfirmKey(keyCode)) { 8569 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8570 return true; 8571 } 8572 // Long clickable items don't necessarily have to be clickable 8573 if (((mViewFlags & CLICKABLE) == CLICKABLE || 8574 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 8575 (event.getRepeatCount() == 0)) { 8576 setPressed(true); 8577 checkForLongClick(0); 8578 return true; 8579 } 8580 } 8581 return result; 8582 } 8583 8584 /** 8585 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 8586 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 8587 * the event). 8588 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8589 * although some may elect to do so in some situations. Do not rely on this to 8590 * catch software key presses. 8591 */ 8592 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 8593 return false; 8594 } 8595 8596 /** 8597 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 8598 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 8599 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 8600 * {@link KeyEvent#KEYCODE_ENTER} is released. 8601 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8602 * although some may elect to do so in some situations. Do not rely on this to 8603 * catch software key presses. 8604 * 8605 * @param keyCode A key code that represents the button pressed, from 8606 * {@link android.view.KeyEvent}. 8607 * @param event The KeyEvent object that defines the button action. 8608 */ 8609 public boolean onKeyUp(int keyCode, KeyEvent event) { 8610 if (KeyEvent.isConfirmKey(keyCode)) { 8611 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8612 return true; 8613 } 8614 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 8615 setPressed(false); 8616 8617 if (!mHasPerformedLongPress) { 8618 // This is a tap, so remove the longpress check 8619 removeLongPressCallback(); 8620 return performClick(); 8621 } 8622 } 8623 } 8624 return false; 8625 } 8626 8627 /** 8628 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 8629 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 8630 * the event). 8631 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8632 * although some may elect to do so in some situations. Do not rely on this to 8633 * catch software key presses. 8634 * 8635 * @param keyCode A key code that represents the button pressed, from 8636 * {@link android.view.KeyEvent}. 8637 * @param repeatCount The number of times the action was made. 8638 * @param event The KeyEvent object that defines the button action. 8639 */ 8640 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 8641 return false; 8642 } 8643 8644 /** 8645 * Called on the focused view when a key shortcut event is not handled. 8646 * Override this method to implement local key shortcuts for the View. 8647 * Key shortcuts can also be implemented by setting the 8648 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 8649 * 8650 * @param keyCode The value in event.getKeyCode(). 8651 * @param event Description of the key event. 8652 * @return If you handled the event, return true. If you want to allow the 8653 * event to be handled by the next receiver, return false. 8654 */ 8655 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 8656 return false; 8657 } 8658 8659 /** 8660 * Check whether the called view is a text editor, in which case it 8661 * would make sense to automatically display a soft input window for 8662 * it. Subclasses should override this if they implement 8663 * {@link #onCreateInputConnection(EditorInfo)} to return true if 8664 * a call on that method would return a non-null InputConnection, and 8665 * they are really a first-class editor that the user would normally 8666 * start typing on when the go into a window containing your view. 8667 * 8668 * <p>The default implementation always returns false. This does 8669 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 8670 * will not be called or the user can not otherwise perform edits on your 8671 * view; it is just a hint to the system that this is not the primary 8672 * purpose of this view. 8673 * 8674 * @return Returns true if this view is a text editor, else false. 8675 */ 8676 public boolean onCheckIsTextEditor() { 8677 return false; 8678 } 8679 8680 /** 8681 * Create a new InputConnection for an InputMethod to interact 8682 * with the view. The default implementation returns null, since it doesn't 8683 * support input methods. You can override this to implement such support. 8684 * This is only needed for views that take focus and text input. 8685 * 8686 * <p>When implementing this, you probably also want to implement 8687 * {@link #onCheckIsTextEditor()} to indicate you will return a 8688 * non-null InputConnection.</p> 8689 * 8690 * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo} 8691 * object correctly and in its entirety, so that the connected IME can rely 8692 * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart} 8693 * and {@link android.view.inputmethod.EditorInfo#initialSelEnd} members 8694 * must be filled in with the correct cursor position for IMEs to work correctly 8695 * with your application.</p> 8696 * 8697 * @param outAttrs Fill in with attribute information about the connection. 8698 */ 8699 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 8700 return null; 8701 } 8702 8703 /** 8704 * Called by the {@link android.view.inputmethod.InputMethodManager} 8705 * when a view who is not the current 8706 * input connection target is trying to make a call on the manager. The 8707 * default implementation returns false; you can override this to return 8708 * true for certain views if you are performing InputConnection proxying 8709 * to them. 8710 * @param view The View that is making the InputMethodManager call. 8711 * @return Return true to allow the call, false to reject. 8712 */ 8713 public boolean checkInputConnectionProxy(View view) { 8714 return false; 8715 } 8716 8717 /** 8718 * Show the context menu for this view. It is not safe to hold on to the 8719 * menu after returning from this method. 8720 * 8721 * You should normally not overload this method. Overload 8722 * {@link #onCreateContextMenu(ContextMenu)} or define an 8723 * {@link OnCreateContextMenuListener} to add items to the context menu. 8724 * 8725 * @param menu The context menu to populate 8726 */ 8727 public void createContextMenu(ContextMenu menu) { 8728 ContextMenuInfo menuInfo = getContextMenuInfo(); 8729 8730 // Sets the current menu info so all items added to menu will have 8731 // my extra info set. 8732 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 8733 8734 onCreateContextMenu(menu); 8735 ListenerInfo li = mListenerInfo; 8736 if (li != null && li.mOnCreateContextMenuListener != null) { 8737 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 8738 } 8739 8740 // Clear the extra information so subsequent items that aren't mine don't 8741 // have my extra info. 8742 ((MenuBuilder)menu).setCurrentMenuInfo(null); 8743 8744 if (mParent != null) { 8745 mParent.createContextMenu(menu); 8746 } 8747 } 8748 8749 /** 8750 * Views should implement this if they have extra information to associate 8751 * with the context menu. The return result is supplied as a parameter to 8752 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 8753 * callback. 8754 * 8755 * @return Extra information about the item for which the context menu 8756 * should be shown. This information will vary across different 8757 * subclasses of View. 8758 */ 8759 protected ContextMenuInfo getContextMenuInfo() { 8760 return null; 8761 } 8762 8763 /** 8764 * Views should implement this if the view itself is going to add items to 8765 * the context menu. 8766 * 8767 * @param menu the context menu to populate 8768 */ 8769 protected void onCreateContextMenu(ContextMenu menu) { 8770 } 8771 8772 /** 8773 * Implement this method to handle trackball motion events. The 8774 * <em>relative</em> movement of the trackball since the last event 8775 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 8776 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 8777 * that a movement of 1 corresponds to the user pressing one DPAD key (so 8778 * they will often be fractional values, representing the more fine-grained 8779 * movement information available from a trackball). 8780 * 8781 * @param event The motion event. 8782 * @return True if the event was handled, false otherwise. 8783 */ 8784 public boolean onTrackballEvent(MotionEvent event) { 8785 return false; 8786 } 8787 8788 /** 8789 * Implement this method to handle generic motion events. 8790 * <p> 8791 * Generic motion events describe joystick movements, mouse hovers, track pad 8792 * touches, scroll wheel movements and other input events. The 8793 * {@link MotionEvent#getSource() source} of the motion event specifies 8794 * the class of input that was received. Implementations of this method 8795 * must examine the bits in the source before processing the event. 8796 * The following code example shows how this is done. 8797 * </p><p> 8798 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 8799 * are delivered to the view under the pointer. All other generic motion events are 8800 * delivered to the focused view. 8801 * </p> 8802 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 8803 * if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) { 8804 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 8805 * // process the joystick movement... 8806 * return true; 8807 * } 8808 * } 8809 * if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { 8810 * switch (event.getAction()) { 8811 * case MotionEvent.ACTION_HOVER_MOVE: 8812 * // process the mouse hover movement... 8813 * return true; 8814 * case MotionEvent.ACTION_SCROLL: 8815 * // process the scroll wheel movement... 8816 * return true; 8817 * } 8818 * } 8819 * return super.onGenericMotionEvent(event); 8820 * }</pre> 8821 * 8822 * @param event The generic motion event being processed. 8823 * @return True if the event was handled, false otherwise. 8824 */ 8825 public boolean onGenericMotionEvent(MotionEvent event) { 8826 return false; 8827 } 8828 8829 /** 8830 * Implement this method to handle hover events. 8831 * <p> 8832 * This method is called whenever a pointer is hovering into, over, or out of the 8833 * bounds of a view and the view is not currently being touched. 8834 * Hover events are represented as pointer events with action 8835 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 8836 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 8837 * </p> 8838 * <ul> 8839 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 8840 * when the pointer enters the bounds of the view.</li> 8841 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 8842 * when the pointer has already entered the bounds of the view and has moved.</li> 8843 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 8844 * when the pointer has exited the bounds of the view or when the pointer is 8845 * about to go down due to a button click, tap, or similar user action that 8846 * causes the view to be touched.</li> 8847 * </ul> 8848 * <p> 8849 * The view should implement this method to return true to indicate that it is 8850 * handling the hover event, such as by changing its drawable state. 8851 * </p><p> 8852 * The default implementation calls {@link #setHovered} to update the hovered state 8853 * of the view when a hover enter or hover exit event is received, if the view 8854 * is enabled and is clickable. The default implementation also sends hover 8855 * accessibility events. 8856 * </p> 8857 * 8858 * @param event The motion event that describes the hover. 8859 * @return True if the view handled the hover event. 8860 * 8861 * @see #isHovered 8862 * @see #setHovered 8863 * @see #onHoverChanged 8864 */ 8865 public boolean onHoverEvent(MotionEvent event) { 8866 // The root view may receive hover (or touch) events that are outside the bounds of 8867 // the window. This code ensures that we only send accessibility events for 8868 // hovers that are actually within the bounds of the root view. 8869 final int action = event.getActionMasked(); 8870 if (!mSendingHoverAccessibilityEvents) { 8871 if ((action == MotionEvent.ACTION_HOVER_ENTER 8872 || action == MotionEvent.ACTION_HOVER_MOVE) 8873 && !hasHoveredChild() 8874 && pointInView(event.getX(), event.getY())) { 8875 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 8876 mSendingHoverAccessibilityEvents = true; 8877 } 8878 } else { 8879 if (action == MotionEvent.ACTION_HOVER_EXIT 8880 || (action == MotionEvent.ACTION_MOVE 8881 && !pointInView(event.getX(), event.getY()))) { 8882 mSendingHoverAccessibilityEvents = false; 8883 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 8884 } 8885 } 8886 8887 if (isHoverable()) { 8888 switch (action) { 8889 case MotionEvent.ACTION_HOVER_ENTER: 8890 setHovered(true); 8891 break; 8892 case MotionEvent.ACTION_HOVER_EXIT: 8893 setHovered(false); 8894 break; 8895 } 8896 8897 // Dispatch the event to onGenericMotionEvent before returning true. 8898 // This is to provide compatibility with existing applications that 8899 // handled HOVER_MOVE events in onGenericMotionEvent and that would 8900 // break because of the new default handling for hoverable views 8901 // in onHoverEvent. 8902 // Note that onGenericMotionEvent will be called by default when 8903 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 8904 dispatchGenericMotionEventInternal(event); 8905 // The event was already handled by calling setHovered(), so always 8906 // return true. 8907 return true; 8908 } 8909 8910 return false; 8911 } 8912 8913 /** 8914 * Returns true if the view should handle {@link #onHoverEvent} 8915 * by calling {@link #setHovered} to change its hovered state. 8916 * 8917 * @return True if the view is hoverable. 8918 */ 8919 private boolean isHoverable() { 8920 final int viewFlags = mViewFlags; 8921 if ((viewFlags & ENABLED_MASK) == DISABLED) { 8922 return false; 8923 } 8924 8925 return (viewFlags & CLICKABLE) == CLICKABLE 8926 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 8927 } 8928 8929 /** 8930 * Returns true if the view is currently hovered. 8931 * 8932 * @return True if the view is currently hovered. 8933 * 8934 * @see #setHovered 8935 * @see #onHoverChanged 8936 */ 8937 @ViewDebug.ExportedProperty 8938 public boolean isHovered() { 8939 return (mPrivateFlags & PFLAG_HOVERED) != 0; 8940 } 8941 8942 /** 8943 * Sets whether the view is currently hovered. 8944 * <p> 8945 * Calling this method also changes the drawable state of the view. This 8946 * enables the view to react to hover by using different drawable resources 8947 * to change its appearance. 8948 * </p><p> 8949 * The {@link #onHoverChanged} method is called when the hovered state changes. 8950 * </p> 8951 * 8952 * @param hovered True if the view is hovered. 8953 * 8954 * @see #isHovered 8955 * @see #onHoverChanged 8956 */ 8957 public void setHovered(boolean hovered) { 8958 if (hovered) { 8959 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 8960 mPrivateFlags |= PFLAG_HOVERED; 8961 refreshDrawableState(); 8962 onHoverChanged(true); 8963 } 8964 } else { 8965 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 8966 mPrivateFlags &= ~PFLAG_HOVERED; 8967 refreshDrawableState(); 8968 onHoverChanged(false); 8969 } 8970 } 8971 } 8972 8973 /** 8974 * Implement this method to handle hover state changes. 8975 * <p> 8976 * This method is called whenever the hover state changes as a result of a 8977 * call to {@link #setHovered}. 8978 * </p> 8979 * 8980 * @param hovered The current hover state, as returned by {@link #isHovered}. 8981 * 8982 * @see #isHovered 8983 * @see #setHovered 8984 */ 8985 public void onHoverChanged(boolean hovered) { 8986 } 8987 8988 /** 8989 * Implement this method to handle touch screen motion events. 8990 * <p> 8991 * If this method is used to detect click actions, it is recommended that 8992 * the actions be performed by implementing and calling 8993 * {@link #performClick()}. This will ensure consistent system behavior, 8994 * including: 8995 * <ul> 8996 * <li>obeying click sound preferences 8997 * <li>dispatching OnClickListener calls 8998 * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when 8999 * accessibility features are enabled 9000 * </ul> 9001 * 9002 * @param event The motion event. 9003 * @return True if the event was handled, false otherwise. 9004 */ 9005 public boolean onTouchEvent(MotionEvent event) { 9006 final float x = event.getX(); 9007 final float y = event.getY(); 9008 final int viewFlags = mViewFlags; 9009 9010 if ((viewFlags & ENABLED_MASK) == DISABLED) { 9011 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 9012 setPressed(false); 9013 } 9014 // A disabled view that is clickable still consumes the touch 9015 // events, it just doesn't respond to them. 9016 return (((viewFlags & CLICKABLE) == CLICKABLE || 9017 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 9018 } 9019 9020 if (mTouchDelegate != null) { 9021 if (mTouchDelegate.onTouchEvent(event)) { 9022 return true; 9023 } 9024 } 9025 9026 if (((viewFlags & CLICKABLE) == CLICKABLE || 9027 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 9028 switch (event.getAction()) { 9029 case MotionEvent.ACTION_UP: 9030 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 9031 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 9032 // take focus if we don't have it already and we should in 9033 // touch mode. 9034 boolean focusTaken = false; 9035 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 9036 focusTaken = requestFocus(); 9037 } 9038 9039 if (prepressed) { 9040 // The button is being released before we actually 9041 // showed it as pressed. Make it show the pressed 9042 // state now (before scheduling the click) to ensure 9043 // the user sees it. 9044 setPressed(true, x, y); 9045 } 9046 9047 if (!mHasPerformedLongPress) { 9048 // This is a tap, so remove the longpress check 9049 removeLongPressCallback(); 9050 9051 // Only perform take click actions if we were in the pressed state 9052 if (!focusTaken) { 9053 // Use a Runnable and post this rather than calling 9054 // performClick directly. This lets other visual state 9055 // of the view update before click actions start. 9056 if (mPerformClick == null) { 9057 mPerformClick = new PerformClick(); 9058 } 9059 if (!post(mPerformClick)) { 9060 performClick(); 9061 } 9062 } 9063 } 9064 9065 if (mUnsetPressedState == null) { 9066 mUnsetPressedState = new UnsetPressedState(); 9067 } 9068 9069 if (prepressed) { 9070 postDelayed(mUnsetPressedState, 9071 ViewConfiguration.getPressedStateDuration()); 9072 } else if (!post(mUnsetPressedState)) { 9073 // If the post failed, unpress right now 9074 mUnsetPressedState.run(); 9075 } 9076 9077 removeTapCallback(); 9078 } 9079 break; 9080 9081 case MotionEvent.ACTION_DOWN: 9082 mHasPerformedLongPress = false; 9083 9084 if (performButtonActionOnTouchDown(event)) { 9085 break; 9086 } 9087 9088 // Walk up the hierarchy to determine if we're inside a scrolling container. 9089 boolean isInScrollingContainer = isInScrollingContainer(); 9090 9091 // For views inside a scrolling container, delay the pressed feedback for 9092 // a short period in case this is a scroll. 9093 if (isInScrollingContainer) { 9094 mPrivateFlags |= PFLAG_PREPRESSED; 9095 if (mPendingCheckForTap == null) { 9096 mPendingCheckForTap = new CheckForTap(); 9097 } 9098 mPendingCheckForTap.x = event.getX(); 9099 mPendingCheckForTap.y = event.getY(); 9100 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 9101 } else { 9102 // Not inside a scrolling container, so show the feedback right away 9103 setHotspot(x, y); 9104 setPressed(true); 9105 checkForLongClick(0); 9106 } 9107 break; 9108 9109 case MotionEvent.ACTION_CANCEL: 9110 setPressed(false); 9111 removeTapCallback(); 9112 removeLongPressCallback(); 9113 break; 9114 9115 case MotionEvent.ACTION_MOVE: 9116 setHotspot(x, y); 9117 9118 // Be lenient about moving outside of buttons 9119 if (!pointInView(x, y, mTouchSlop)) { 9120 // Outside button 9121 removeTapCallback(); 9122 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 9123 // Remove any future long press/tap checks 9124 removeLongPressCallback(); 9125 9126 setPressed(false); 9127 } 9128 } 9129 break; 9130 } 9131 9132 return true; 9133 } 9134 9135 return false; 9136 } 9137 9138 private void setHotspot(float x, float y) { 9139 if (mBackground != null) { 9140 mBackground.setHotspot(x, y); 9141 } 9142 } 9143 9144 /** 9145 * @hide 9146 */ 9147 public boolean isInScrollingContainer() { 9148 ViewParent p = getParent(); 9149 while (p != null && p instanceof ViewGroup) { 9150 if (((ViewGroup) p).shouldDelayChildPressedState()) { 9151 return true; 9152 } 9153 p = p.getParent(); 9154 } 9155 return false; 9156 } 9157 9158 /** 9159 * Remove the longpress detection timer. 9160 */ 9161 private void removeLongPressCallback() { 9162 if (mPendingCheckForLongPress != null) { 9163 removeCallbacks(mPendingCheckForLongPress); 9164 } 9165 } 9166 9167 /** 9168 * Remove the pending click action 9169 */ 9170 private void removePerformClickCallback() { 9171 if (mPerformClick != null) { 9172 removeCallbacks(mPerformClick); 9173 } 9174 } 9175 9176 /** 9177 * Remove the prepress detection timer. 9178 */ 9179 private void removeUnsetPressCallback() { 9180 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 9181 setPressed(false); 9182 removeCallbacks(mUnsetPressedState); 9183 } 9184 } 9185 9186 /** 9187 * Remove the tap detection timer. 9188 */ 9189 private void removeTapCallback() { 9190 if (mPendingCheckForTap != null) { 9191 mPrivateFlags &= ~PFLAG_PREPRESSED; 9192 removeCallbacks(mPendingCheckForTap); 9193 } 9194 } 9195 9196 /** 9197 * Cancels a pending long press. Your subclass can use this if you 9198 * want the context menu to come up if the user presses and holds 9199 * at the same place, but you don't want it to come up if they press 9200 * and then move around enough to cause scrolling. 9201 */ 9202 public void cancelLongPress() { 9203 removeLongPressCallback(); 9204 9205 /* 9206 * The prepressed state handled by the tap callback is a display 9207 * construct, but the tap callback will post a long press callback 9208 * less its own timeout. Remove it here. 9209 */ 9210 removeTapCallback(); 9211 } 9212 9213 /** 9214 * Remove the pending callback for sending a 9215 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 9216 */ 9217 private void removeSendViewScrolledAccessibilityEventCallback() { 9218 if (mSendViewScrolledAccessibilityEvent != null) { 9219 removeCallbacks(mSendViewScrolledAccessibilityEvent); 9220 mSendViewScrolledAccessibilityEvent.mIsPending = false; 9221 } 9222 } 9223 9224 /** 9225 * Sets the TouchDelegate for this View. 9226 */ 9227 public void setTouchDelegate(TouchDelegate delegate) { 9228 mTouchDelegate = delegate; 9229 } 9230 9231 /** 9232 * Gets the TouchDelegate for this View. 9233 */ 9234 public TouchDelegate getTouchDelegate() { 9235 return mTouchDelegate; 9236 } 9237 9238 /** 9239 * Request unbuffered dispatch of the given stream of MotionEvents to this View. 9240 * 9241 * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input 9242 * system not batch {@link MotionEvent}s but instead deliver them as soon as they're 9243 * available. This method should only be called for touch events. 9244 * 9245 * <p class="note">This api is not intended for most applications. Buffered dispatch 9246 * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent 9247 * streams will not improve your input latency. Side effects include: increased latency, 9248 * jittery scrolls and inability to take advantage of system resampling. Talk to your input 9249 * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for 9250 * you.</p> 9251 */ 9252 public final void requestUnbufferedDispatch(MotionEvent event) { 9253 final int action = event.getAction(); 9254 if (mAttachInfo == null 9255 || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE 9256 || !event.isTouchEvent()) { 9257 return; 9258 } 9259 mAttachInfo.mUnbufferedDispatchRequested = true; 9260 } 9261 9262 /** 9263 * Set flags controlling behavior of this view. 9264 * 9265 * @param flags Constant indicating the value which should be set 9266 * @param mask Constant indicating the bit range that should be changed 9267 */ 9268 void setFlags(int flags, int mask) { 9269 final boolean accessibilityEnabled = 9270 AccessibilityManager.getInstance(mContext).isEnabled(); 9271 final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility(); 9272 9273 int old = mViewFlags; 9274 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 9275 9276 int changed = mViewFlags ^ old; 9277 if (changed == 0) { 9278 return; 9279 } 9280 int privateFlags = mPrivateFlags; 9281 9282 /* Check if the FOCUSABLE bit has changed */ 9283 if (((changed & FOCUSABLE_MASK) != 0) && 9284 ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) { 9285 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 9286 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 9287 /* Give up focus if we are no longer focusable */ 9288 clearFocus(); 9289 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 9290 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 9291 /* 9292 * Tell the view system that we are now available to take focus 9293 * if no one else already has it. 9294 */ 9295 if (mParent != null) mParent.focusableViewAvailable(this); 9296 } 9297 } 9298 9299 final int newVisibility = flags & VISIBILITY_MASK; 9300 if (newVisibility == VISIBLE) { 9301 if ((changed & VISIBILITY_MASK) != 0) { 9302 /* 9303 * If this view is becoming visible, invalidate it in case it changed while 9304 * it was not visible. Marking it drawn ensures that the invalidation will 9305 * go through. 9306 */ 9307 mPrivateFlags |= PFLAG_DRAWN; 9308 invalidate(true); 9309 9310 needGlobalAttributesUpdate(true); 9311 9312 // a view becoming visible is worth notifying the parent 9313 // about in case nothing has focus. even if this specific view 9314 // isn't focusable, it may contain something that is, so let 9315 // the root view try to give this focus if nothing else does. 9316 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 9317 mParent.focusableViewAvailable(this); 9318 } 9319 } 9320 } 9321 9322 /* Check if the GONE bit has changed */ 9323 if ((changed & GONE) != 0) { 9324 needGlobalAttributesUpdate(false); 9325 requestLayout(); 9326 9327 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 9328 if (hasFocus()) clearFocus(); 9329 clearAccessibilityFocus(); 9330 destroyDrawingCache(); 9331 if (mParent instanceof View) { 9332 // GONE views noop invalidation, so invalidate the parent 9333 ((View) mParent).invalidate(true); 9334 } 9335 // Mark the view drawn to ensure that it gets invalidated properly the next 9336 // time it is visible and gets invalidated 9337 mPrivateFlags |= PFLAG_DRAWN; 9338 } 9339 if (mAttachInfo != null) { 9340 mAttachInfo.mViewVisibilityChanged = true; 9341 } 9342 } 9343 9344 /* Check if the VISIBLE bit has changed */ 9345 if ((changed & INVISIBLE) != 0) { 9346 needGlobalAttributesUpdate(false); 9347 /* 9348 * If this view is becoming invisible, set the DRAWN flag so that 9349 * the next invalidate() will not be skipped. 9350 */ 9351 mPrivateFlags |= PFLAG_DRAWN; 9352 9353 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) { 9354 // root view becoming invisible shouldn't clear focus and accessibility focus 9355 if (getRootView() != this) { 9356 if (hasFocus()) clearFocus(); 9357 clearAccessibilityFocus(); 9358 } 9359 } 9360 if (mAttachInfo != null) { 9361 mAttachInfo.mViewVisibilityChanged = true; 9362 } 9363 } 9364 9365 if ((changed & VISIBILITY_MASK) != 0) { 9366 // If the view is invisible, cleanup its display list to free up resources 9367 if (newVisibility != VISIBLE && mAttachInfo != null) { 9368 cleanupDraw(); 9369 } 9370 9371 if (mParent instanceof ViewGroup) { 9372 ((ViewGroup) mParent).onChildVisibilityChanged(this, 9373 (changed & VISIBILITY_MASK), newVisibility); 9374 ((View) mParent).invalidate(true); 9375 } else if (mParent != null) { 9376 mParent.invalidateChild(this, null); 9377 } 9378 dispatchVisibilityChanged(this, newVisibility); 9379 9380 notifySubtreeAccessibilityStateChangedIfNeeded(); 9381 } 9382 9383 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 9384 destroyDrawingCache(); 9385 } 9386 9387 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 9388 destroyDrawingCache(); 9389 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9390 invalidateParentCaches(); 9391 } 9392 9393 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 9394 destroyDrawingCache(); 9395 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9396 } 9397 9398 if ((changed & DRAW_MASK) != 0) { 9399 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 9400 if (mBackground != null) { 9401 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9402 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 9403 } else { 9404 mPrivateFlags |= PFLAG_SKIP_DRAW; 9405 } 9406 } else { 9407 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9408 } 9409 requestLayout(); 9410 invalidate(true); 9411 } 9412 9413 if ((changed & KEEP_SCREEN_ON) != 0) { 9414 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 9415 mParent.recomputeViewAttributes(this); 9416 } 9417 } 9418 9419 if (accessibilityEnabled) { 9420 if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0 9421 || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) { 9422 if (oldIncludeForAccessibility != includeForAccessibility()) { 9423 notifySubtreeAccessibilityStateChangedIfNeeded(); 9424 } else { 9425 notifyViewAccessibilityStateChangedIfNeeded( 9426 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9427 } 9428 } else if ((changed & ENABLED_MASK) != 0) { 9429 notifyViewAccessibilityStateChangedIfNeeded( 9430 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9431 } 9432 } 9433 } 9434 9435 /** 9436 * Change the view's z order in the tree, so it's on top of other sibling 9437 * views. This ordering change may affect layout, if the parent container 9438 * uses an order-dependent layout scheme (e.g., LinearLayout). Prior 9439 * to {@link android.os.Build.VERSION_CODES#KITKAT} this 9440 * method should be followed by calls to {@link #requestLayout()} and 9441 * {@link View#invalidate()} on the view's parent to force the parent to redraw 9442 * with the new child ordering. 9443 * 9444 * @see ViewGroup#bringChildToFront(View) 9445 */ 9446 public void bringToFront() { 9447 if (mParent != null) { 9448 mParent.bringChildToFront(this); 9449 } 9450 } 9451 9452 /** 9453 * This is called in response to an internal scroll in this view (i.e., the 9454 * view scrolled its own contents). This is typically as a result of 9455 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 9456 * called. 9457 * 9458 * @param l Current horizontal scroll origin. 9459 * @param t Current vertical scroll origin. 9460 * @param oldl Previous horizontal scroll origin. 9461 * @param oldt Previous vertical scroll origin. 9462 */ 9463 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 9464 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 9465 postSendViewScrolledAccessibilityEventCallback(); 9466 } 9467 9468 mBackgroundSizeChanged = true; 9469 9470 final AttachInfo ai = mAttachInfo; 9471 if (ai != null) { 9472 ai.mViewScrollChanged = true; 9473 } 9474 } 9475 9476 /** 9477 * Interface definition for a callback to be invoked when the layout bounds of a view 9478 * changes due to layout processing. 9479 */ 9480 public interface OnLayoutChangeListener { 9481 /** 9482 * Called when the layout bounds of a view changes due to layout processing. 9483 * 9484 * @param v The view whose bounds have changed. 9485 * @param left The new value of the view's left property. 9486 * @param top The new value of the view's top property. 9487 * @param right The new value of the view's right property. 9488 * @param bottom The new value of the view's bottom property. 9489 * @param oldLeft The previous value of the view's left property. 9490 * @param oldTop The previous value of the view's top property. 9491 * @param oldRight The previous value of the view's right property. 9492 * @param oldBottom The previous value of the view's bottom property. 9493 */ 9494 void onLayoutChange(View v, int left, int top, int right, int bottom, 9495 int oldLeft, int oldTop, int oldRight, int oldBottom); 9496 } 9497 9498 /** 9499 * This is called during layout when the size of this view has changed. If 9500 * you were just added to the view hierarchy, you're called with the old 9501 * values of 0. 9502 * 9503 * @param w Current width of this view. 9504 * @param h Current height of this view. 9505 * @param oldw Old width of this view. 9506 * @param oldh Old height of this view. 9507 */ 9508 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 9509 } 9510 9511 /** 9512 * Called by draw to draw the child views. This may be overridden 9513 * by derived classes to gain control just before its children are drawn 9514 * (but after its own view has been drawn). 9515 * @param canvas the canvas on which to draw the view 9516 */ 9517 protected void dispatchDraw(Canvas canvas) { 9518 9519 } 9520 9521 /** 9522 * Gets the parent of this view. Note that the parent is a 9523 * ViewParent and not necessarily a View. 9524 * 9525 * @return Parent of this view. 9526 */ 9527 public final ViewParent getParent() { 9528 return mParent; 9529 } 9530 9531 /** 9532 * Set the horizontal scrolled position of your view. This will cause a call to 9533 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9534 * invalidated. 9535 * @param value the x position to scroll to 9536 */ 9537 public void setScrollX(int value) { 9538 scrollTo(value, mScrollY); 9539 } 9540 9541 /** 9542 * Set the vertical scrolled position of your view. This will cause a call to 9543 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9544 * invalidated. 9545 * @param value the y position to scroll to 9546 */ 9547 public void setScrollY(int value) { 9548 scrollTo(mScrollX, value); 9549 } 9550 9551 /** 9552 * Return the scrolled left position of this view. This is the left edge of 9553 * the displayed part of your view. You do not need to draw any pixels 9554 * farther left, since those are outside of the frame of your view on 9555 * screen. 9556 * 9557 * @return The left edge of the displayed part of your view, in pixels. 9558 */ 9559 public final int getScrollX() { 9560 return mScrollX; 9561 } 9562 9563 /** 9564 * Return the scrolled top position of this view. This is the top edge of 9565 * the displayed part of your view. You do not need to draw any pixels above 9566 * it, since those are outside of the frame of your view on screen. 9567 * 9568 * @return The top edge of the displayed part of your view, in pixels. 9569 */ 9570 public final int getScrollY() { 9571 return mScrollY; 9572 } 9573 9574 /** 9575 * Return the width of the your view. 9576 * 9577 * @return The width of your view, in pixels. 9578 */ 9579 @ViewDebug.ExportedProperty(category = "layout") 9580 public final int getWidth() { 9581 return mRight - mLeft; 9582 } 9583 9584 /** 9585 * Return the height of your view. 9586 * 9587 * @return The height of your view, in pixels. 9588 */ 9589 @ViewDebug.ExportedProperty(category = "layout") 9590 public final int getHeight() { 9591 return mBottom - mTop; 9592 } 9593 9594 /** 9595 * Return the visible drawing bounds of your view. Fills in the output 9596 * rectangle with the values from getScrollX(), getScrollY(), 9597 * getWidth(), and getHeight(). These bounds do not account for any 9598 * transformation properties currently set on the view, such as 9599 * {@link #setScaleX(float)} or {@link #setRotation(float)}. 9600 * 9601 * @param outRect The (scrolled) drawing bounds of the view. 9602 */ 9603 public void getDrawingRect(Rect outRect) { 9604 outRect.left = mScrollX; 9605 outRect.top = mScrollY; 9606 outRect.right = mScrollX + (mRight - mLeft); 9607 outRect.bottom = mScrollY + (mBottom - mTop); 9608 } 9609 9610 /** 9611 * Like {@link #getMeasuredWidthAndState()}, but only returns the 9612 * raw width component (that is the result is masked by 9613 * {@link #MEASURED_SIZE_MASK}). 9614 * 9615 * @return The raw measured width of this view. 9616 */ 9617 public final int getMeasuredWidth() { 9618 return mMeasuredWidth & MEASURED_SIZE_MASK; 9619 } 9620 9621 /** 9622 * Return the full width measurement information for this view as computed 9623 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 9624 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 9625 * This should be used during measurement and layout calculations only. Use 9626 * {@link #getWidth()} to see how wide a view is after layout. 9627 * 9628 * @return The measured width of this view as a bit mask. 9629 */ 9630 public final int getMeasuredWidthAndState() { 9631 return mMeasuredWidth; 9632 } 9633 9634 /** 9635 * Like {@link #getMeasuredHeightAndState()}, but only returns the 9636 * raw width component (that is the result is masked by 9637 * {@link #MEASURED_SIZE_MASK}). 9638 * 9639 * @return The raw measured height of this view. 9640 */ 9641 public final int getMeasuredHeight() { 9642 return mMeasuredHeight & MEASURED_SIZE_MASK; 9643 } 9644 9645 /** 9646 * Return the full height measurement information for this view as computed 9647 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 9648 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 9649 * This should be used during measurement and layout calculations only. Use 9650 * {@link #getHeight()} to see how wide a view is after layout. 9651 * 9652 * @return The measured width of this view as a bit mask. 9653 */ 9654 public final int getMeasuredHeightAndState() { 9655 return mMeasuredHeight; 9656 } 9657 9658 /** 9659 * Return only the state bits of {@link #getMeasuredWidthAndState()} 9660 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 9661 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 9662 * and the height component is at the shifted bits 9663 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 9664 */ 9665 public final int getMeasuredState() { 9666 return (mMeasuredWidth&MEASURED_STATE_MASK) 9667 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 9668 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 9669 } 9670 9671 /** 9672 * The transform matrix of this view, which is calculated based on the current 9673 * roation, scale, and pivot properties. 9674 * 9675 * @see #getRotation() 9676 * @see #getScaleX() 9677 * @see #getScaleY() 9678 * @see #getPivotX() 9679 * @see #getPivotY() 9680 * @return The current transform matrix for the view 9681 */ 9682 public Matrix getMatrix() { 9683 ensureTransformationInfo(); 9684 final Matrix matrix = mTransformationInfo.mMatrix; 9685 mRenderNode.getMatrix(matrix); 9686 return matrix; 9687 } 9688 9689 /** 9690 * Returns true if the transform matrix is the identity matrix. 9691 * Recomputes the matrix if necessary. 9692 * 9693 * @return True if the transform matrix is the identity matrix, false otherwise. 9694 */ 9695 final boolean hasIdentityMatrix() { 9696 return mRenderNode.hasIdentityMatrix(); 9697 } 9698 9699 void ensureTransformationInfo() { 9700 if (mTransformationInfo == null) { 9701 mTransformationInfo = new TransformationInfo(); 9702 } 9703 } 9704 9705 /** 9706 * Utility method to retrieve the inverse of the current mMatrix property. 9707 * We cache the matrix to avoid recalculating it when transform properties 9708 * have not changed. 9709 * 9710 * @return The inverse of the current matrix of this view. 9711 */ 9712 final Matrix getInverseMatrix() { 9713 ensureTransformationInfo(); 9714 if (mTransformationInfo.mInverseMatrix == null) { 9715 mTransformationInfo.mInverseMatrix = new Matrix(); 9716 } 9717 final Matrix matrix = mTransformationInfo.mInverseMatrix; 9718 mRenderNode.getInverseMatrix(matrix); 9719 return matrix; 9720 } 9721 9722 /** 9723 * Gets the distance along the Z axis from the camera to this view. 9724 * 9725 * @see #setCameraDistance(float) 9726 * 9727 * @return The distance along the Z axis. 9728 */ 9729 public float getCameraDistance() { 9730 final float dpi = mResources.getDisplayMetrics().densityDpi; 9731 return -(mRenderNode.getCameraDistance() * dpi); 9732 } 9733 9734 /** 9735 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 9736 * views are drawn) from the camera to this view. The camera's distance 9737 * affects 3D transformations, for instance rotations around the X and Y 9738 * axis. If the rotationX or rotationY properties are changed and this view is 9739 * large (more than half the size of the screen), it is recommended to always 9740 * use a camera distance that's greater than the height (X axis rotation) or 9741 * the width (Y axis rotation) of this view.</p> 9742 * 9743 * <p>The distance of the camera from the view plane can have an affect on the 9744 * perspective distortion of the view when it is rotated around the x or y axis. 9745 * For example, a large distance will result in a large viewing angle, and there 9746 * will not be much perspective distortion of the view as it rotates. A short 9747 * distance may cause much more perspective distortion upon rotation, and can 9748 * also result in some drawing artifacts if the rotated view ends up partially 9749 * behind the camera (which is why the recommendation is to use a distance at 9750 * least as far as the size of the view, if the view is to be rotated.)</p> 9751 * 9752 * <p>The distance is expressed in "depth pixels." The default distance depends 9753 * on the screen density. For instance, on a medium density display, the 9754 * default distance is 1280. On a high density display, the default distance 9755 * is 1920.</p> 9756 * 9757 * <p>If you want to specify a distance that leads to visually consistent 9758 * results across various densities, use the following formula:</p> 9759 * <pre> 9760 * float scale = context.getResources().getDisplayMetrics().density; 9761 * view.setCameraDistance(distance * scale); 9762 * </pre> 9763 * 9764 * <p>The density scale factor of a high density display is 1.5, 9765 * and 1920 = 1280 * 1.5.</p> 9766 * 9767 * @param distance The distance in "depth pixels", if negative the opposite 9768 * value is used 9769 * 9770 * @see #setRotationX(float) 9771 * @see #setRotationY(float) 9772 */ 9773 public void setCameraDistance(float distance) { 9774 final float dpi = mResources.getDisplayMetrics().densityDpi; 9775 9776 invalidateViewProperty(true, false); 9777 mRenderNode.setCameraDistance(-Math.abs(distance) / dpi); 9778 invalidateViewProperty(false, false); 9779 9780 invalidateParentIfNeededAndWasQuickRejected(); 9781 } 9782 9783 /** 9784 * The degrees that the view is rotated around the pivot point. 9785 * 9786 * @see #setRotation(float) 9787 * @see #getPivotX() 9788 * @see #getPivotY() 9789 * 9790 * @return The degrees of rotation. 9791 */ 9792 @ViewDebug.ExportedProperty(category = "drawing") 9793 public float getRotation() { 9794 return mRenderNode.getRotation(); 9795 } 9796 9797 /** 9798 * Sets the degrees that the view is rotated around the pivot point. Increasing values 9799 * result in clockwise rotation. 9800 * 9801 * @param rotation The degrees of rotation. 9802 * 9803 * @see #getRotation() 9804 * @see #getPivotX() 9805 * @see #getPivotY() 9806 * @see #setRotationX(float) 9807 * @see #setRotationY(float) 9808 * 9809 * @attr ref android.R.styleable#View_rotation 9810 */ 9811 public void setRotation(float rotation) { 9812 if (rotation != getRotation()) { 9813 // Double-invalidation is necessary to capture view's old and new areas 9814 invalidateViewProperty(true, false); 9815 mRenderNode.setRotation(rotation); 9816 invalidateViewProperty(false, true); 9817 9818 invalidateParentIfNeededAndWasQuickRejected(); 9819 notifySubtreeAccessibilityStateChangedIfNeeded(); 9820 } 9821 } 9822 9823 /** 9824 * The degrees that the view is rotated around the vertical axis through the pivot point. 9825 * 9826 * @see #getPivotX() 9827 * @see #getPivotY() 9828 * @see #setRotationY(float) 9829 * 9830 * @return The degrees of Y rotation. 9831 */ 9832 @ViewDebug.ExportedProperty(category = "drawing") 9833 public float getRotationY() { 9834 return mRenderNode.getRotationY(); 9835 } 9836 9837 /** 9838 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 9839 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 9840 * down the y axis. 9841 * 9842 * When rotating large views, it is recommended to adjust the camera distance 9843 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 9844 * 9845 * @param rotationY The degrees of Y rotation. 9846 * 9847 * @see #getRotationY() 9848 * @see #getPivotX() 9849 * @see #getPivotY() 9850 * @see #setRotation(float) 9851 * @see #setRotationX(float) 9852 * @see #setCameraDistance(float) 9853 * 9854 * @attr ref android.R.styleable#View_rotationY 9855 */ 9856 public void setRotationY(float rotationY) { 9857 if (rotationY != getRotationY()) { 9858 invalidateViewProperty(true, false); 9859 mRenderNode.setRotationY(rotationY); 9860 invalidateViewProperty(false, true); 9861 9862 invalidateParentIfNeededAndWasQuickRejected(); 9863 notifySubtreeAccessibilityStateChangedIfNeeded(); 9864 } 9865 } 9866 9867 /** 9868 * The degrees that the view is rotated around the horizontal axis through the pivot point. 9869 * 9870 * @see #getPivotX() 9871 * @see #getPivotY() 9872 * @see #setRotationX(float) 9873 * 9874 * @return The degrees of X rotation. 9875 */ 9876 @ViewDebug.ExportedProperty(category = "drawing") 9877 public float getRotationX() { 9878 return mRenderNode.getRotationX(); 9879 } 9880 9881 /** 9882 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 9883 * Increasing values result in clockwise rotation from the viewpoint of looking down the 9884 * x axis. 9885 * 9886 * When rotating large views, it is recommended to adjust the camera distance 9887 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 9888 * 9889 * @param rotationX The degrees of X rotation. 9890 * 9891 * @see #getRotationX() 9892 * @see #getPivotX() 9893 * @see #getPivotY() 9894 * @see #setRotation(float) 9895 * @see #setRotationY(float) 9896 * @see #setCameraDistance(float) 9897 * 9898 * @attr ref android.R.styleable#View_rotationX 9899 */ 9900 public void setRotationX(float rotationX) { 9901 if (rotationX != getRotationX()) { 9902 invalidateViewProperty(true, false); 9903 mRenderNode.setRotationX(rotationX); 9904 invalidateViewProperty(false, true); 9905 9906 invalidateParentIfNeededAndWasQuickRejected(); 9907 notifySubtreeAccessibilityStateChangedIfNeeded(); 9908 } 9909 } 9910 9911 /** 9912 * The amount that the view is scaled in x around the pivot point, as a proportion of 9913 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 9914 * 9915 * <p>By default, this is 1.0f. 9916 * 9917 * @see #getPivotX() 9918 * @see #getPivotY() 9919 * @return The scaling factor. 9920 */ 9921 @ViewDebug.ExportedProperty(category = "drawing") 9922 public float getScaleX() { 9923 return mRenderNode.getScaleX(); 9924 } 9925 9926 /** 9927 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 9928 * the view's unscaled width. A value of 1 means that no scaling is applied. 9929 * 9930 * @param scaleX The scaling factor. 9931 * @see #getPivotX() 9932 * @see #getPivotY() 9933 * 9934 * @attr ref android.R.styleable#View_scaleX 9935 */ 9936 public void setScaleX(float scaleX) { 9937 if (scaleX != getScaleX()) { 9938 invalidateViewProperty(true, false); 9939 mRenderNode.setScaleX(scaleX); 9940 invalidateViewProperty(false, true); 9941 9942 invalidateParentIfNeededAndWasQuickRejected(); 9943 notifySubtreeAccessibilityStateChangedIfNeeded(); 9944 } 9945 } 9946 9947 /** 9948 * The amount that the view is scaled in y around the pivot point, as a proportion of 9949 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 9950 * 9951 * <p>By default, this is 1.0f. 9952 * 9953 * @see #getPivotX() 9954 * @see #getPivotY() 9955 * @return The scaling factor. 9956 */ 9957 @ViewDebug.ExportedProperty(category = "drawing") 9958 public float getScaleY() { 9959 return mRenderNode.getScaleY(); 9960 } 9961 9962 /** 9963 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 9964 * the view's unscaled width. A value of 1 means that no scaling is applied. 9965 * 9966 * @param scaleY The scaling factor. 9967 * @see #getPivotX() 9968 * @see #getPivotY() 9969 * 9970 * @attr ref android.R.styleable#View_scaleY 9971 */ 9972 public void setScaleY(float scaleY) { 9973 if (scaleY != getScaleY()) { 9974 invalidateViewProperty(true, false); 9975 mRenderNode.setScaleY(scaleY); 9976 invalidateViewProperty(false, true); 9977 9978 invalidateParentIfNeededAndWasQuickRejected(); 9979 notifySubtreeAccessibilityStateChangedIfNeeded(); 9980 } 9981 } 9982 9983 /** 9984 * The x location of the point around which the view is {@link #setRotation(float) rotated} 9985 * and {@link #setScaleX(float) scaled}. 9986 * 9987 * @see #getRotation() 9988 * @see #getScaleX() 9989 * @see #getScaleY() 9990 * @see #getPivotY() 9991 * @return The x location of the pivot point. 9992 * 9993 * @attr ref android.R.styleable#View_transformPivotX 9994 */ 9995 @ViewDebug.ExportedProperty(category = "drawing") 9996 public float getPivotX() { 9997 return mRenderNode.getPivotX(); 9998 } 9999 10000 /** 10001 * Sets the x location of the point around which the view is 10002 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 10003 * By default, the pivot point is centered on the object. 10004 * Setting this property disables this behavior and causes the view to use only the 10005 * explicitly set pivotX and pivotY values. 10006 * 10007 * @param pivotX The x location of the pivot point. 10008 * @see #getRotation() 10009 * @see #getScaleX() 10010 * @see #getScaleY() 10011 * @see #getPivotY() 10012 * 10013 * @attr ref android.R.styleable#View_transformPivotX 10014 */ 10015 public void setPivotX(float pivotX) { 10016 if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) { 10017 invalidateViewProperty(true, false); 10018 mRenderNode.setPivotX(pivotX); 10019 invalidateViewProperty(false, true); 10020 10021 invalidateParentIfNeededAndWasQuickRejected(); 10022 } 10023 } 10024 10025 /** 10026 * The y location of the point around which the view is {@link #setRotation(float) rotated} 10027 * and {@link #setScaleY(float) scaled}. 10028 * 10029 * @see #getRotation() 10030 * @see #getScaleX() 10031 * @see #getScaleY() 10032 * @see #getPivotY() 10033 * @return The y location of the pivot point. 10034 * 10035 * @attr ref android.R.styleable#View_transformPivotY 10036 */ 10037 @ViewDebug.ExportedProperty(category = "drawing") 10038 public float getPivotY() { 10039 return mRenderNode.getPivotY(); 10040 } 10041 10042 /** 10043 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 10044 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 10045 * Setting this property disables this behavior and causes the view to use only the 10046 * explicitly set pivotX and pivotY values. 10047 * 10048 * @param pivotY The y location of the pivot point. 10049 * @see #getRotation() 10050 * @see #getScaleX() 10051 * @see #getScaleY() 10052 * @see #getPivotY() 10053 * 10054 * @attr ref android.R.styleable#View_transformPivotY 10055 */ 10056 public void setPivotY(float pivotY) { 10057 if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) { 10058 invalidateViewProperty(true, false); 10059 mRenderNode.setPivotY(pivotY); 10060 invalidateViewProperty(false, true); 10061 10062 invalidateParentIfNeededAndWasQuickRejected(); 10063 } 10064 } 10065 10066 /** 10067 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 10068 * completely transparent and 1 means the view is completely opaque. 10069 * 10070 * <p>By default this is 1.0f. 10071 * @return The opacity of the view. 10072 */ 10073 @ViewDebug.ExportedProperty(category = "drawing") 10074 public float getAlpha() { 10075 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 10076 } 10077 10078 /** 10079 * Returns whether this View has content which overlaps. 10080 * 10081 * <p>This function, intended to be overridden by specific View types, is an optimization when 10082 * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to 10083 * an offscreen buffer and then composited into place, which can be expensive. If the view has 10084 * no overlapping rendering, the view can draw each primitive with the appropriate alpha value 10085 * directly. An example of overlapping rendering is a TextView with a background image, such as 10086 * a Button. An example of non-overlapping rendering is a TextView with no background, or an 10087 * ImageView with only the foreground image. The default implementation returns true; subclasses 10088 * should override if they have cases which can be optimized.</p> 10089 * 10090 * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas} 10091 * necessitates that a View return true if it uses the methods internally without passing the 10092 * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p> 10093 * 10094 * @return true if the content in this view might overlap, false otherwise. 10095 */ 10096 public boolean hasOverlappingRendering() { 10097 return true; 10098 } 10099 10100 /** 10101 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 10102 * completely transparent and 1 means the view is completely opaque.</p> 10103 * 10104 * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant 10105 * performance implications, especially for large views. It is best to use the alpha property 10106 * sparingly and transiently, as in the case of fading animations.</p> 10107 * 10108 * <p>For a view with a frequently changing alpha, such as during a fading animation, it is 10109 * strongly recommended for performance reasons to either override 10110 * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a 10111 * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p> 10112 * 10113 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 10114 * responsible for applying the opacity itself.</p> 10115 * 10116 * <p>Note that if the view is backed by a 10117 * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a 10118 * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than 10119 * 1.0 will supercede the alpha of the layer paint.</p> 10120 * 10121 * @param alpha The opacity of the view. 10122 * 10123 * @see #hasOverlappingRendering() 10124 * @see #setLayerType(int, android.graphics.Paint) 10125 * 10126 * @attr ref android.R.styleable#View_alpha 10127 */ 10128 public void setAlpha(float alpha) { 10129 ensureTransformationInfo(); 10130 if (mTransformationInfo.mAlpha != alpha) { 10131 mTransformationInfo.mAlpha = alpha; 10132 if (onSetAlpha((int) (alpha * 255))) { 10133 mPrivateFlags |= PFLAG_ALPHA_SET; 10134 // subclass is handling alpha - don't optimize rendering cache invalidation 10135 invalidateParentCaches(); 10136 invalidate(true); 10137 } else { 10138 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10139 invalidateViewProperty(true, false); 10140 mRenderNode.setAlpha(getFinalAlpha()); 10141 notifyViewAccessibilityStateChangedIfNeeded( 10142 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 10143 } 10144 } 10145 } 10146 10147 /** 10148 * Faster version of setAlpha() which performs the same steps except there are 10149 * no calls to invalidate(). The caller of this function should perform proper invalidation 10150 * on the parent and this object. The return value indicates whether the subclass handles 10151 * alpha (the return value for onSetAlpha()). 10152 * 10153 * @param alpha The new value for the alpha property 10154 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 10155 * the new value for the alpha property is different from the old value 10156 */ 10157 boolean setAlphaNoInvalidation(float alpha) { 10158 ensureTransformationInfo(); 10159 if (mTransformationInfo.mAlpha != alpha) { 10160 mTransformationInfo.mAlpha = alpha; 10161 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 10162 if (subclassHandlesAlpha) { 10163 mPrivateFlags |= PFLAG_ALPHA_SET; 10164 return true; 10165 } else { 10166 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10167 mRenderNode.setAlpha(getFinalAlpha()); 10168 } 10169 } 10170 return false; 10171 } 10172 10173 /** 10174 * This property is hidden and intended only for use by the Fade transition, which 10175 * animates it to produce a visual translucency that does not side-effect (or get 10176 * affected by) the real alpha property. This value is composited with the other 10177 * alpha value (and the AlphaAnimation value, when that is present) to produce 10178 * a final visual translucency result, which is what is passed into the DisplayList. 10179 * 10180 * @hide 10181 */ 10182 public void setTransitionAlpha(float alpha) { 10183 ensureTransformationInfo(); 10184 if (mTransformationInfo.mTransitionAlpha != alpha) { 10185 mTransformationInfo.mTransitionAlpha = alpha; 10186 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10187 invalidateViewProperty(true, false); 10188 mRenderNode.setAlpha(getFinalAlpha()); 10189 } 10190 } 10191 10192 /** 10193 * Calculates the visual alpha of this view, which is a combination of the actual 10194 * alpha value and the transitionAlpha value (if set). 10195 */ 10196 private float getFinalAlpha() { 10197 if (mTransformationInfo != null) { 10198 return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha; 10199 } 10200 return 1; 10201 } 10202 10203 /** 10204 * This property is hidden and intended only for use by the Fade transition, which 10205 * animates it to produce a visual translucency that does not side-effect (or get 10206 * affected by) the real alpha property. This value is composited with the other 10207 * alpha value (and the AlphaAnimation value, when that is present) to produce 10208 * a final visual translucency result, which is what is passed into the DisplayList. 10209 * 10210 * @hide 10211 */ 10212 public float getTransitionAlpha() { 10213 return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1; 10214 } 10215 10216 /** 10217 * Top position of this view relative to its parent. 10218 * 10219 * @return The top of this view, in pixels. 10220 */ 10221 @ViewDebug.CapturedViewProperty 10222 public final int getTop() { 10223 return mTop; 10224 } 10225 10226 /** 10227 * Sets the top position of this view relative to its parent. This method is meant to be called 10228 * by the layout system and should not generally be called otherwise, because the property 10229 * may be changed at any time by the layout. 10230 * 10231 * @param top The top of this view, in pixels. 10232 */ 10233 public final void setTop(int top) { 10234 if (top != mTop) { 10235 final boolean matrixIsIdentity = hasIdentityMatrix(); 10236 if (matrixIsIdentity) { 10237 if (mAttachInfo != null) { 10238 int minTop; 10239 int yLoc; 10240 if (top < mTop) { 10241 minTop = top; 10242 yLoc = top - mTop; 10243 } else { 10244 minTop = mTop; 10245 yLoc = 0; 10246 } 10247 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 10248 } 10249 } else { 10250 // Double-invalidation is necessary to capture view's old and new areas 10251 invalidate(true); 10252 } 10253 10254 int width = mRight - mLeft; 10255 int oldHeight = mBottom - mTop; 10256 10257 mTop = top; 10258 mRenderNode.setTop(mTop); 10259 10260 sizeChange(width, mBottom - mTop, width, oldHeight); 10261 10262 if (!matrixIsIdentity) { 10263 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10264 invalidate(true); 10265 } 10266 mBackgroundSizeChanged = true; 10267 invalidateParentIfNeeded(); 10268 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10269 // View was rejected last time it was drawn by its parent; this may have changed 10270 invalidateParentIfNeeded(); 10271 } 10272 } 10273 } 10274 10275 /** 10276 * Bottom position of this view relative to its parent. 10277 * 10278 * @return The bottom of this view, in pixels. 10279 */ 10280 @ViewDebug.CapturedViewProperty 10281 public final int getBottom() { 10282 return mBottom; 10283 } 10284 10285 /** 10286 * True if this view has changed since the last time being drawn. 10287 * 10288 * @return The dirty state of this view. 10289 */ 10290 public boolean isDirty() { 10291 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 10292 } 10293 10294 /** 10295 * Sets the bottom position of this view relative to its parent. This method is meant to be 10296 * called by the layout system and should not generally be called otherwise, because the 10297 * property may be changed at any time by the layout. 10298 * 10299 * @param bottom The bottom of this view, in pixels. 10300 */ 10301 public final void setBottom(int bottom) { 10302 if (bottom != mBottom) { 10303 final boolean matrixIsIdentity = hasIdentityMatrix(); 10304 if (matrixIsIdentity) { 10305 if (mAttachInfo != null) { 10306 int maxBottom; 10307 if (bottom < mBottom) { 10308 maxBottom = mBottom; 10309 } else { 10310 maxBottom = bottom; 10311 } 10312 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 10313 } 10314 } else { 10315 // Double-invalidation is necessary to capture view's old and new areas 10316 invalidate(true); 10317 } 10318 10319 int width = mRight - mLeft; 10320 int oldHeight = mBottom - mTop; 10321 10322 mBottom = bottom; 10323 mRenderNode.setBottom(mBottom); 10324 10325 sizeChange(width, mBottom - mTop, width, oldHeight); 10326 10327 if (!matrixIsIdentity) { 10328 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10329 invalidate(true); 10330 } 10331 mBackgroundSizeChanged = true; 10332 invalidateParentIfNeeded(); 10333 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10334 // View was rejected last time it was drawn by its parent; this may have changed 10335 invalidateParentIfNeeded(); 10336 } 10337 } 10338 } 10339 10340 /** 10341 * Left position of this view relative to its parent. 10342 * 10343 * @return The left edge of this view, in pixels. 10344 */ 10345 @ViewDebug.CapturedViewProperty 10346 public final int getLeft() { 10347 return mLeft; 10348 } 10349 10350 /** 10351 * Sets the left position of this view relative to its parent. This method is meant to be called 10352 * by the layout system and should not generally be called otherwise, because the property 10353 * may be changed at any time by the layout. 10354 * 10355 * @param left The left of this view, in pixels. 10356 */ 10357 public final void setLeft(int left) { 10358 if (left != mLeft) { 10359 final boolean matrixIsIdentity = hasIdentityMatrix(); 10360 if (matrixIsIdentity) { 10361 if (mAttachInfo != null) { 10362 int minLeft; 10363 int xLoc; 10364 if (left < mLeft) { 10365 minLeft = left; 10366 xLoc = left - mLeft; 10367 } else { 10368 minLeft = mLeft; 10369 xLoc = 0; 10370 } 10371 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 10372 } 10373 } else { 10374 // Double-invalidation is necessary to capture view's old and new areas 10375 invalidate(true); 10376 } 10377 10378 int oldWidth = mRight - mLeft; 10379 int height = mBottom - mTop; 10380 10381 mLeft = left; 10382 mRenderNode.setLeft(left); 10383 10384 sizeChange(mRight - mLeft, height, oldWidth, height); 10385 10386 if (!matrixIsIdentity) { 10387 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10388 invalidate(true); 10389 } 10390 mBackgroundSizeChanged = true; 10391 invalidateParentIfNeeded(); 10392 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10393 // View was rejected last time it was drawn by its parent; this may have changed 10394 invalidateParentIfNeeded(); 10395 } 10396 } 10397 } 10398 10399 /** 10400 * Right position of this view relative to its parent. 10401 * 10402 * @return The right edge of this view, in pixels. 10403 */ 10404 @ViewDebug.CapturedViewProperty 10405 public final int getRight() { 10406 return mRight; 10407 } 10408 10409 /** 10410 * Sets the right position of this view relative to its parent. This method is meant to be called 10411 * by the layout system and should not generally be called otherwise, because the property 10412 * may be changed at any time by the layout. 10413 * 10414 * @param right The right of this view, in pixels. 10415 */ 10416 public final void setRight(int right) { 10417 if (right != mRight) { 10418 final boolean matrixIsIdentity = hasIdentityMatrix(); 10419 if (matrixIsIdentity) { 10420 if (mAttachInfo != null) { 10421 int maxRight; 10422 if (right < mRight) { 10423 maxRight = mRight; 10424 } else { 10425 maxRight = right; 10426 } 10427 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 10428 } 10429 } else { 10430 // Double-invalidation is necessary to capture view's old and new areas 10431 invalidate(true); 10432 } 10433 10434 int oldWidth = mRight - mLeft; 10435 int height = mBottom - mTop; 10436 10437 mRight = right; 10438 mRenderNode.setRight(mRight); 10439 10440 sizeChange(mRight - mLeft, height, oldWidth, height); 10441 10442 if (!matrixIsIdentity) { 10443 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10444 invalidate(true); 10445 } 10446 mBackgroundSizeChanged = true; 10447 invalidateParentIfNeeded(); 10448 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10449 // View was rejected last time it was drawn by its parent; this may have changed 10450 invalidateParentIfNeeded(); 10451 } 10452 } 10453 } 10454 10455 /** 10456 * The visual x position of this view, in pixels. This is equivalent to the 10457 * {@link #setTranslationX(float) translationX} property plus the current 10458 * {@link #getLeft() left} property. 10459 * 10460 * @return The visual x position of this view, in pixels. 10461 */ 10462 @ViewDebug.ExportedProperty(category = "drawing") 10463 public float getX() { 10464 return mLeft + getTranslationX(); 10465 } 10466 10467 /** 10468 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 10469 * {@link #setTranslationX(float) translationX} property to be the difference between 10470 * the x value passed in and the current {@link #getLeft() left} property. 10471 * 10472 * @param x The visual x position of this view, in pixels. 10473 */ 10474 public void setX(float x) { 10475 setTranslationX(x - mLeft); 10476 } 10477 10478 /** 10479 * The visual y position of this view, in pixels. This is equivalent to the 10480 * {@link #setTranslationY(float) translationY} property plus the current 10481 * {@link #getTop() top} property. 10482 * 10483 * @return The visual y position of this view, in pixels. 10484 */ 10485 @ViewDebug.ExportedProperty(category = "drawing") 10486 public float getY() { 10487 return mTop + getTranslationY(); 10488 } 10489 10490 /** 10491 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 10492 * {@link #setTranslationY(float) translationY} property to be the difference between 10493 * the y value passed in and the current {@link #getTop() top} property. 10494 * 10495 * @param y The visual y position of this view, in pixels. 10496 */ 10497 public void setY(float y) { 10498 setTranslationY(y - mTop); 10499 } 10500 10501 /** 10502 * The visual z position of this view, in pixels. This is equivalent to the 10503 * {@link #setTranslationZ(float) translationZ} property plus the current 10504 * {@link #getElevation() elevation} property. 10505 * 10506 * @return The visual z position of this view, in pixels. 10507 */ 10508 @ViewDebug.ExportedProperty(category = "drawing") 10509 public float getZ() { 10510 return getElevation() + getTranslationZ(); 10511 } 10512 10513 /** 10514 * Sets the visual z position of this view, in pixels. This is equivalent to setting the 10515 * {@link #setTranslationZ(float) translationZ} property to be the difference between 10516 * the x value passed in and the current {@link #getElevation() elevation} property. 10517 * 10518 * @param z The visual z position of this view, in pixels. 10519 */ 10520 public void setZ(float z) { 10521 setTranslationZ(z - getElevation()); 10522 } 10523 10524 @ViewDebug.ExportedProperty(category = "drawing") 10525 public float getElevation() { 10526 return mRenderNode.getElevation(); 10527 } 10528 10529 /** 10530 * Sets the base depth location of this view. 10531 * 10532 * @attr ref android.R.styleable#View_elevation 10533 */ 10534 public void setElevation(float elevation) { 10535 if (elevation != getElevation()) { 10536 invalidateViewProperty(true, false); 10537 mRenderNode.setElevation(elevation); 10538 invalidateViewProperty(false, true); 10539 10540 invalidateParentIfNeededAndWasQuickRejected(); 10541 } 10542 } 10543 10544 /** 10545 * The horizontal location of this view relative to its {@link #getLeft() left} position. 10546 * This position is post-layout, in addition to wherever the object's 10547 * layout placed it. 10548 * 10549 * @return The horizontal position of this view relative to its left position, in pixels. 10550 */ 10551 @ViewDebug.ExportedProperty(category = "drawing") 10552 public float getTranslationX() { 10553 return mRenderNode.getTranslationX(); 10554 } 10555 10556 /** 10557 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 10558 * This effectively positions the object post-layout, in addition to wherever the object's 10559 * layout placed it. 10560 * 10561 * @param translationX The horizontal position of this view relative to its left position, 10562 * in pixels. 10563 * 10564 * @attr ref android.R.styleable#View_translationX 10565 */ 10566 public void setTranslationX(float translationX) { 10567 if (translationX != getTranslationX()) { 10568 invalidateViewProperty(true, false); 10569 mRenderNode.setTranslationX(translationX); 10570 invalidateViewProperty(false, true); 10571 10572 invalidateParentIfNeededAndWasQuickRejected(); 10573 notifySubtreeAccessibilityStateChangedIfNeeded(); 10574 } 10575 } 10576 10577 /** 10578 * The vertical location of this view relative to its {@link #getTop() top} position. 10579 * This position is post-layout, in addition to wherever the object's 10580 * layout placed it. 10581 * 10582 * @return The vertical position of this view relative to its top position, 10583 * in pixels. 10584 */ 10585 @ViewDebug.ExportedProperty(category = "drawing") 10586 public float getTranslationY() { 10587 return mRenderNode.getTranslationY(); 10588 } 10589 10590 /** 10591 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 10592 * This effectively positions the object post-layout, in addition to wherever the object's 10593 * layout placed it. 10594 * 10595 * @param translationY The vertical position of this view relative to its top position, 10596 * in pixels. 10597 * 10598 * @attr ref android.R.styleable#View_translationY 10599 */ 10600 public void setTranslationY(float translationY) { 10601 if (translationY != getTranslationY()) { 10602 invalidateViewProperty(true, false); 10603 mRenderNode.setTranslationY(translationY); 10604 invalidateViewProperty(false, true); 10605 10606 invalidateParentIfNeededAndWasQuickRejected(); 10607 } 10608 } 10609 10610 /** 10611 * The depth location of this view relative to its {@link #getElevation() elevation}. 10612 * 10613 * @return The depth of this view relative to its elevation. 10614 */ 10615 @ViewDebug.ExportedProperty(category = "drawing") 10616 public float getTranslationZ() { 10617 return mRenderNode.getTranslationZ(); 10618 } 10619 10620 /** 10621 * Sets the depth location of this view relative to its {@link #getElevation() elevation}. 10622 * 10623 * @attr ref android.R.styleable#View_translationZ 10624 */ 10625 public void setTranslationZ(float translationZ) { 10626 if (translationZ != getTranslationZ()) { 10627 invalidateViewProperty(true, false); 10628 mRenderNode.setTranslationZ(translationZ); 10629 invalidateViewProperty(false, true); 10630 10631 invalidateParentIfNeededAndWasQuickRejected(); 10632 } 10633 } 10634 10635 /** 10636 * Returns a ValueAnimator which can animate a clearing circle. 10637 * <p> 10638 * The View is prevented from drawing within the circle, so the content 10639 * behind the View shows through. 10640 * 10641 * @param centerX The x coordinate of the center of the animating circle. 10642 * @param centerY The y coordinate of the center of the animating circle. 10643 * @param startRadius The starting radius of the animating circle. 10644 * @param endRadius The ending radius of the animating circle. 10645 * 10646 * @hide 10647 */ 10648 public final ValueAnimator createClearCircleAnimator(int centerX, int centerY, 10649 float startRadius, float endRadius) { 10650 return RevealAnimator.ofRevealCircle(this, centerX, centerY, 10651 startRadius, endRadius, true); 10652 } 10653 10654 /** 10655 * Returns the current StateListAnimator if exists. 10656 * 10657 * @return StateListAnimator or null if it does not exists 10658 * @see #setStateListAnimator(android.animation.StateListAnimator) 10659 */ 10660 public StateListAnimator getStateListAnimator() { 10661 return mStateListAnimator; 10662 } 10663 10664 /** 10665 * Attaches the provided StateListAnimator to this View. 10666 * <p> 10667 * Any previously attached StateListAnimator will be detached. 10668 * 10669 * @param stateListAnimator The StateListAnimator to update the view 10670 * @see {@link android.animation.StateListAnimator} 10671 */ 10672 public void setStateListAnimator(StateListAnimator stateListAnimator) { 10673 if (mStateListAnimator == stateListAnimator) { 10674 return; 10675 } 10676 if (mStateListAnimator != null) { 10677 mStateListAnimator.setTarget(null); 10678 } 10679 mStateListAnimator = stateListAnimator; 10680 if (stateListAnimator != null) { 10681 stateListAnimator.setTarget(this); 10682 if (isAttachedToWindow()) { 10683 stateListAnimator.setState(getDrawableState()); 10684 } 10685 } 10686 } 10687 10688 /** 10689 * Sets the {@link Outline} of the view, which defines the shape of the shadow it 10690 * casts, and enables outline clipping. 10691 * <p> 10692 * By default, a View queries its Outline from its background drawable, via 10693 * {@link Drawable#getOutline(Outline)}. Manually setting the Outline with this method allows 10694 * this behavior to be overridden. 10695 * <p> 10696 * If the outline is {@link Outline#isEmpty()} or is <code>null</code>, 10697 * shadows will not be cast. 10698 * <p> 10699 * Only outlines that return true from {@link Outline#canClip()} may be used for clipping. 10700 * 10701 * @param outline The new outline of the view. 10702 * 10703 * @see #setClipToOutline(boolean) 10704 * @see #getClipToOutline() 10705 */ 10706 public void setOutline(@Nullable Outline outline) { 10707 mPrivateFlags3 |= PFLAG3_OUTLINE_DEFINED; 10708 10709 if (outline == null || outline.isEmpty()) { 10710 if (mOutline != null) { 10711 mOutline.setEmpty(); 10712 } 10713 } else { 10714 // always copy the path since caller may reuse 10715 if (mOutline == null) { 10716 mOutline = new Outline(); 10717 } 10718 mOutline.set(outline); 10719 } 10720 mRenderNode.setOutline(mOutline); 10721 } 10722 10723 /** 10724 * Returns whether the Outline should be used to clip the contents of the View. 10725 * <p> 10726 * Note that this flag will only be respected if the View's Outline returns true from 10727 * {@link Outline#canClip()}. 10728 * 10729 * @see #setOutline(Outline) 10730 * @see #setClipToOutline(boolean) 10731 */ 10732 public final boolean getClipToOutline() { 10733 return mRenderNode.getClipToOutline(); 10734 } 10735 10736 /** 10737 * Sets whether the View's Outline should be used to clip the contents of the View. 10738 * <p> 10739 * Note that this flag will only be respected if the View's Outline returns true from 10740 * {@link Outline#canClip()}. 10741 * 10742 * @see #setOutline(Outline) 10743 * @see #getClipToOutline() 10744 */ 10745 public void setClipToOutline(boolean clipToOutline) { 10746 damageInParent(); 10747 if (getClipToOutline() != clipToOutline) { 10748 mRenderNode.setClipToOutline(clipToOutline); 10749 } 10750 } 10751 10752 private void queryOutlineFromBackgroundIfUndefined() { 10753 if ((mPrivateFlags3 & PFLAG3_OUTLINE_DEFINED) == 0) { 10754 // Outline not currently defined, query from background 10755 if (mOutline == null) { 10756 mOutline = new Outline(); 10757 } else { 10758 //invalidate outline, to ensure background calculates it 10759 mOutline.setEmpty(); 10760 } 10761 if (mBackground.getOutline(mOutline)) { 10762 if (mOutline.isEmpty()) { 10763 throw new IllegalStateException("Background drawable failed to build outline"); 10764 } 10765 mRenderNode.setOutline(mOutline); 10766 } else { 10767 mRenderNode.setOutline(null); 10768 } 10769 notifySubtreeAccessibilityStateChangedIfNeeded(); 10770 } 10771 } 10772 10773 /** 10774 * Private API to be used for reveal animation 10775 * 10776 * @hide 10777 */ 10778 public void setRevealClip(boolean shouldClip, boolean inverseClip, 10779 float x, float y, float radius) { 10780 mRenderNode.setRevealClip(shouldClip, inverseClip, x, y, radius); 10781 // TODO: Handle this invalidate in a better way, or purely in native. 10782 invalidate(); 10783 } 10784 10785 /** 10786 * Hit rectangle in parent's coordinates 10787 * 10788 * @param outRect The hit rectangle of the view. 10789 */ 10790 public void getHitRect(Rect outRect) { 10791 if (hasIdentityMatrix() || mAttachInfo == null) { 10792 outRect.set(mLeft, mTop, mRight, mBottom); 10793 } else { 10794 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 10795 tmpRect.set(0, 0, getWidth(), getHeight()); 10796 getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect) 10797 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 10798 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 10799 } 10800 } 10801 10802 /** 10803 * Determines whether the given point, in local coordinates is inside the view. 10804 */ 10805 /*package*/ final boolean pointInView(float localX, float localY) { 10806 return localX >= 0 && localX < (mRight - mLeft) 10807 && localY >= 0 && localY < (mBottom - mTop); 10808 } 10809 10810 /** 10811 * Utility method to determine whether the given point, in local coordinates, 10812 * is inside the view, where the area of the view is expanded by the slop factor. 10813 * This method is called while processing touch-move events to determine if the event 10814 * is still within the view. 10815 * 10816 * @hide 10817 */ 10818 public boolean pointInView(float localX, float localY, float slop) { 10819 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 10820 localY < ((mBottom - mTop) + slop); 10821 } 10822 10823 /** 10824 * When a view has focus and the user navigates away from it, the next view is searched for 10825 * starting from the rectangle filled in by this method. 10826 * 10827 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 10828 * of the view. However, if your view maintains some idea of internal selection, 10829 * such as a cursor, or a selected row or column, you should override this method and 10830 * fill in a more specific rectangle. 10831 * 10832 * @param r The rectangle to fill in, in this view's coordinates. 10833 */ 10834 public void getFocusedRect(Rect r) { 10835 getDrawingRect(r); 10836 } 10837 10838 /** 10839 * If some part of this view is not clipped by any of its parents, then 10840 * return that area in r in global (root) coordinates. To convert r to local 10841 * coordinates (without taking possible View rotations into account), offset 10842 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 10843 * If the view is completely clipped or translated out, return false. 10844 * 10845 * @param r If true is returned, r holds the global coordinates of the 10846 * visible portion of this view. 10847 * @param globalOffset If true is returned, globalOffset holds the dx,dy 10848 * between this view and its root. globalOffet may be null. 10849 * @return true if r is non-empty (i.e. part of the view is visible at the 10850 * root level. 10851 */ 10852 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 10853 int width = mRight - mLeft; 10854 int height = mBottom - mTop; 10855 if (width > 0 && height > 0) { 10856 r.set(0, 0, width, height); 10857 if (globalOffset != null) { 10858 globalOffset.set(-mScrollX, -mScrollY); 10859 } 10860 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 10861 } 10862 return false; 10863 } 10864 10865 public final boolean getGlobalVisibleRect(Rect r) { 10866 return getGlobalVisibleRect(r, null); 10867 } 10868 10869 public final boolean getLocalVisibleRect(Rect r) { 10870 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 10871 if (getGlobalVisibleRect(r, offset)) { 10872 r.offset(-offset.x, -offset.y); // make r local 10873 return true; 10874 } 10875 return false; 10876 } 10877 10878 /** 10879 * Offset this view's vertical location by the specified number of pixels. 10880 * 10881 * @param offset the number of pixels to offset the view by 10882 */ 10883 public void offsetTopAndBottom(int offset) { 10884 if (offset != 0) { 10885 final boolean matrixIsIdentity = hasIdentityMatrix(); 10886 if (matrixIsIdentity) { 10887 if (isHardwareAccelerated()) { 10888 invalidateViewProperty(false, false); 10889 } else { 10890 final ViewParent p = mParent; 10891 if (p != null && mAttachInfo != null) { 10892 final Rect r = mAttachInfo.mTmpInvalRect; 10893 int minTop; 10894 int maxBottom; 10895 int yLoc; 10896 if (offset < 0) { 10897 minTop = mTop + offset; 10898 maxBottom = mBottom; 10899 yLoc = offset; 10900 } else { 10901 minTop = mTop; 10902 maxBottom = mBottom + offset; 10903 yLoc = 0; 10904 } 10905 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 10906 p.invalidateChild(this, r); 10907 } 10908 } 10909 } else { 10910 invalidateViewProperty(false, false); 10911 } 10912 10913 mTop += offset; 10914 mBottom += offset; 10915 mRenderNode.offsetTopAndBottom(offset); 10916 if (isHardwareAccelerated()) { 10917 invalidateViewProperty(false, false); 10918 } else { 10919 if (!matrixIsIdentity) { 10920 invalidateViewProperty(false, true); 10921 } 10922 invalidateParentIfNeeded(); 10923 } 10924 notifySubtreeAccessibilityStateChangedIfNeeded(); 10925 } 10926 } 10927 10928 /** 10929 * Offset this view's horizontal location by the specified amount of pixels. 10930 * 10931 * @param offset the number of pixels to offset the view by 10932 */ 10933 public void offsetLeftAndRight(int offset) { 10934 if (offset != 0) { 10935 final boolean matrixIsIdentity = hasIdentityMatrix(); 10936 if (matrixIsIdentity) { 10937 if (isHardwareAccelerated()) { 10938 invalidateViewProperty(false, false); 10939 } else { 10940 final ViewParent p = mParent; 10941 if (p != null && mAttachInfo != null) { 10942 final Rect r = mAttachInfo.mTmpInvalRect; 10943 int minLeft; 10944 int maxRight; 10945 if (offset < 0) { 10946 minLeft = mLeft + offset; 10947 maxRight = mRight; 10948 } else { 10949 minLeft = mLeft; 10950 maxRight = mRight + offset; 10951 } 10952 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 10953 p.invalidateChild(this, r); 10954 } 10955 } 10956 } else { 10957 invalidateViewProperty(false, false); 10958 } 10959 10960 mLeft += offset; 10961 mRight += offset; 10962 mRenderNode.offsetLeftAndRight(offset); 10963 if (isHardwareAccelerated()) { 10964 invalidateViewProperty(false, false); 10965 } else { 10966 if (!matrixIsIdentity) { 10967 invalidateViewProperty(false, true); 10968 } 10969 invalidateParentIfNeeded(); 10970 } 10971 notifySubtreeAccessibilityStateChangedIfNeeded(); 10972 } 10973 } 10974 10975 /** 10976 * Get the LayoutParams associated with this view. All views should have 10977 * layout parameters. These supply parameters to the <i>parent</i> of this 10978 * view specifying how it should be arranged. There are many subclasses of 10979 * ViewGroup.LayoutParams, and these correspond to the different subclasses 10980 * of ViewGroup that are responsible for arranging their children. 10981 * 10982 * This method may return null if this View is not attached to a parent 10983 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 10984 * was not invoked successfully. When a View is attached to a parent 10985 * ViewGroup, this method must not return null. 10986 * 10987 * @return The LayoutParams associated with this view, or null if no 10988 * parameters have been set yet 10989 */ 10990 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 10991 public ViewGroup.LayoutParams getLayoutParams() { 10992 return mLayoutParams; 10993 } 10994 10995 /** 10996 * Set the layout parameters associated with this view. These supply 10997 * parameters to the <i>parent</i> of this view specifying how it should be 10998 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 10999 * correspond to the different subclasses of ViewGroup that are responsible 11000 * for arranging their children. 11001 * 11002 * @param params The layout parameters for this view, cannot be null 11003 */ 11004 public void setLayoutParams(ViewGroup.LayoutParams params) { 11005 if (params == null) { 11006 throw new NullPointerException("Layout parameters cannot be null"); 11007 } 11008 mLayoutParams = params; 11009 resolveLayoutParams(); 11010 if (mParent instanceof ViewGroup) { 11011 ((ViewGroup) mParent).onSetLayoutParams(this, params); 11012 } 11013 requestLayout(); 11014 } 11015 11016 /** 11017 * Resolve the layout parameters depending on the resolved layout direction 11018 * 11019 * @hide 11020 */ 11021 public void resolveLayoutParams() { 11022 if (mLayoutParams != null) { 11023 mLayoutParams.resolveLayoutDirection(getLayoutDirection()); 11024 } 11025 } 11026 11027 /** 11028 * Set the scrolled position of your view. This will cause a call to 11029 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11030 * invalidated. 11031 * @param x the x position to scroll to 11032 * @param y the y position to scroll to 11033 */ 11034 public void scrollTo(int x, int y) { 11035 if (mScrollX != x || mScrollY != y) { 11036 int oldX = mScrollX; 11037 int oldY = mScrollY; 11038 mScrollX = x; 11039 mScrollY = y; 11040 invalidateParentCaches(); 11041 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 11042 if (!awakenScrollBars()) { 11043 postInvalidateOnAnimation(); 11044 } 11045 } 11046 } 11047 11048 /** 11049 * Move the scrolled position of your view. This will cause a call to 11050 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11051 * invalidated. 11052 * @param x the amount of pixels to scroll by horizontally 11053 * @param y the amount of pixels to scroll by vertically 11054 */ 11055 public void scrollBy(int x, int y) { 11056 scrollTo(mScrollX + x, mScrollY + y); 11057 } 11058 11059 /** 11060 * <p>Trigger the scrollbars to draw. When invoked this method starts an 11061 * animation to fade the scrollbars out after a default delay. If a subclass 11062 * provides animated scrolling, the start delay should equal the duration 11063 * of the scrolling animation.</p> 11064 * 11065 * <p>The animation starts only if at least one of the scrollbars is 11066 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 11067 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11068 * this method returns true, and false otherwise. If the animation is 11069 * started, this method calls {@link #invalidate()}; in that case the 11070 * caller should not call {@link #invalidate()}.</p> 11071 * 11072 * <p>This method should be invoked every time a subclass directly updates 11073 * the scroll parameters.</p> 11074 * 11075 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 11076 * and {@link #scrollTo(int, int)}.</p> 11077 * 11078 * @return true if the animation is played, false otherwise 11079 * 11080 * @see #awakenScrollBars(int) 11081 * @see #scrollBy(int, int) 11082 * @see #scrollTo(int, int) 11083 * @see #isHorizontalScrollBarEnabled() 11084 * @see #isVerticalScrollBarEnabled() 11085 * @see #setHorizontalScrollBarEnabled(boolean) 11086 * @see #setVerticalScrollBarEnabled(boolean) 11087 */ 11088 protected boolean awakenScrollBars() { 11089 return mScrollCache != null && 11090 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 11091 } 11092 11093 /** 11094 * Trigger the scrollbars to draw. 11095 * This method differs from awakenScrollBars() only in its default duration. 11096 * initialAwakenScrollBars() will show the scroll bars for longer than 11097 * usual to give the user more of a chance to notice them. 11098 * 11099 * @return true if the animation is played, false otherwise. 11100 */ 11101 private boolean initialAwakenScrollBars() { 11102 return mScrollCache != null && 11103 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 11104 } 11105 11106 /** 11107 * <p> 11108 * Trigger the scrollbars to draw. When invoked this method starts an 11109 * animation to fade the scrollbars out after a fixed delay. If a subclass 11110 * provides animated scrolling, the start delay should equal the duration of 11111 * the scrolling animation. 11112 * </p> 11113 * 11114 * <p> 11115 * The animation starts only if at least one of the scrollbars is enabled, 11116 * as specified by {@link #isHorizontalScrollBarEnabled()} and 11117 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11118 * this method returns true, and false otherwise. If the animation is 11119 * started, this method calls {@link #invalidate()}; in that case the caller 11120 * should not call {@link #invalidate()}. 11121 * </p> 11122 * 11123 * <p> 11124 * This method should be invoked everytime a subclass directly updates the 11125 * scroll parameters. 11126 * </p> 11127 * 11128 * @param startDelay the delay, in milliseconds, after which the animation 11129 * should start; when the delay is 0, the animation starts 11130 * immediately 11131 * @return true if the animation is played, false otherwise 11132 * 11133 * @see #scrollBy(int, int) 11134 * @see #scrollTo(int, int) 11135 * @see #isHorizontalScrollBarEnabled() 11136 * @see #isVerticalScrollBarEnabled() 11137 * @see #setHorizontalScrollBarEnabled(boolean) 11138 * @see #setVerticalScrollBarEnabled(boolean) 11139 */ 11140 protected boolean awakenScrollBars(int startDelay) { 11141 return awakenScrollBars(startDelay, true); 11142 } 11143 11144 /** 11145 * <p> 11146 * Trigger the scrollbars to draw. When invoked this method starts an 11147 * animation to fade the scrollbars out after a fixed delay. If a subclass 11148 * provides animated scrolling, the start delay should equal the duration of 11149 * the scrolling animation. 11150 * </p> 11151 * 11152 * <p> 11153 * The animation starts only if at least one of the scrollbars is enabled, 11154 * as specified by {@link #isHorizontalScrollBarEnabled()} and 11155 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11156 * this method returns true, and false otherwise. If the animation is 11157 * started, this method calls {@link #invalidate()} if the invalidate parameter 11158 * is set to true; in that case the caller 11159 * should not call {@link #invalidate()}. 11160 * </p> 11161 * 11162 * <p> 11163 * This method should be invoked everytime a subclass directly updates the 11164 * scroll parameters. 11165 * </p> 11166 * 11167 * @param startDelay the delay, in milliseconds, after which the animation 11168 * should start; when the delay is 0, the animation starts 11169 * immediately 11170 * 11171 * @param invalidate Wheter this method should call invalidate 11172 * 11173 * @return true if the animation is played, false otherwise 11174 * 11175 * @see #scrollBy(int, int) 11176 * @see #scrollTo(int, int) 11177 * @see #isHorizontalScrollBarEnabled() 11178 * @see #isVerticalScrollBarEnabled() 11179 * @see #setHorizontalScrollBarEnabled(boolean) 11180 * @see #setVerticalScrollBarEnabled(boolean) 11181 */ 11182 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 11183 final ScrollabilityCache scrollCache = mScrollCache; 11184 11185 if (scrollCache == null || !scrollCache.fadeScrollBars) { 11186 return false; 11187 } 11188 11189 if (scrollCache.scrollBar == null) { 11190 scrollCache.scrollBar = new ScrollBarDrawable(); 11191 } 11192 11193 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 11194 11195 if (invalidate) { 11196 // Invalidate to show the scrollbars 11197 postInvalidateOnAnimation(); 11198 } 11199 11200 if (scrollCache.state == ScrollabilityCache.OFF) { 11201 // FIXME: this is copied from WindowManagerService. 11202 // We should get this value from the system when it 11203 // is possible to do so. 11204 final int KEY_REPEAT_FIRST_DELAY = 750; 11205 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 11206 } 11207 11208 // Tell mScrollCache when we should start fading. This may 11209 // extend the fade start time if one was already scheduled 11210 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 11211 scrollCache.fadeStartTime = fadeStartTime; 11212 scrollCache.state = ScrollabilityCache.ON; 11213 11214 // Schedule our fader to run, unscheduling any old ones first 11215 if (mAttachInfo != null) { 11216 mAttachInfo.mHandler.removeCallbacks(scrollCache); 11217 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 11218 } 11219 11220 return true; 11221 } 11222 11223 return false; 11224 } 11225 11226 /** 11227 * Do not invalidate views which are not visible and which are not running an animation. They 11228 * will not get drawn and they should not set dirty flags as if they will be drawn 11229 */ 11230 private boolean skipInvalidate() { 11231 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 11232 (!(mParent instanceof ViewGroup) || 11233 !((ViewGroup) mParent).isViewTransitioning(this)); 11234 } 11235 11236 /** 11237 * Mark the area defined by dirty as needing to be drawn. If the view is 11238 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 11239 * point in the future. 11240 * <p> 11241 * This must be called from a UI thread. To call from a non-UI thread, call 11242 * {@link #postInvalidate()}. 11243 * <p> 11244 * <b>WARNING:</b> In API 19 and below, this method may be destructive to 11245 * {@code dirty}. 11246 * 11247 * @param dirty the rectangle representing the bounds of the dirty region 11248 */ 11249 public void invalidate(Rect dirty) { 11250 final int scrollX = mScrollX; 11251 final int scrollY = mScrollY; 11252 invalidateInternal(dirty.left - scrollX, dirty.top - scrollY, 11253 dirty.right - scrollX, dirty.bottom - scrollY, true, false); 11254 } 11255 11256 /** 11257 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The 11258 * coordinates of the dirty rect are relative to the view. If the view is 11259 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 11260 * point in the future. 11261 * <p> 11262 * This must be called from a UI thread. To call from a non-UI thread, call 11263 * {@link #postInvalidate()}. 11264 * 11265 * @param l the left position of the dirty region 11266 * @param t the top position of the dirty region 11267 * @param r the right position of the dirty region 11268 * @param b the bottom position of the dirty region 11269 */ 11270 public void invalidate(int l, int t, int r, int b) { 11271 final int scrollX = mScrollX; 11272 final int scrollY = mScrollY; 11273 invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false); 11274 } 11275 11276 /** 11277 * Invalidate the whole view. If the view is visible, 11278 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 11279 * the future. 11280 * <p> 11281 * This must be called from a UI thread. To call from a non-UI thread, call 11282 * {@link #postInvalidate()}. 11283 */ 11284 public void invalidate() { 11285 invalidate(true); 11286 } 11287 11288 /** 11289 * This is where the invalidate() work actually happens. A full invalidate() 11290 * causes the drawing cache to be invalidated, but this function can be 11291 * called with invalidateCache set to false to skip that invalidation step 11292 * for cases that do not need it (for example, a component that remains at 11293 * the same dimensions with the same content). 11294 * 11295 * @param invalidateCache Whether the drawing cache for this view should be 11296 * invalidated as well. This is usually true for a full 11297 * invalidate, but may be set to false if the View's contents or 11298 * dimensions have not changed. 11299 */ 11300 void invalidate(boolean invalidateCache) { 11301 invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true); 11302 } 11303 11304 void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache, 11305 boolean fullInvalidate) { 11306 if (skipInvalidate()) { 11307 return; 11308 } 11309 11310 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) 11311 || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) 11312 || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED 11313 || (fullInvalidate && isOpaque() != mLastIsOpaque)) { 11314 if (fullInvalidate) { 11315 mLastIsOpaque = isOpaque(); 11316 mPrivateFlags &= ~PFLAG_DRAWN; 11317 } 11318 11319 mPrivateFlags |= PFLAG_DIRTY; 11320 11321 if (invalidateCache) { 11322 mPrivateFlags |= PFLAG_INVALIDATED; 11323 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 11324 } 11325 11326 // Propagate the damage rectangle to the parent view. 11327 final AttachInfo ai = mAttachInfo; 11328 final ViewParent p = mParent; 11329 if (p != null && ai != null && l < r && t < b) { 11330 final Rect damage = ai.mTmpInvalRect; 11331 damage.set(l, t, r, b); 11332 p.invalidateChild(this, damage); 11333 } 11334 11335 // Damage the entire projection receiver, if necessary. 11336 if (mBackground != null && mBackground.isProjected()) { 11337 final View receiver = getProjectionReceiver(); 11338 if (receiver != null) { 11339 receiver.damageInParent(); 11340 } 11341 } 11342 11343 // Damage the entire IsolatedZVolume recieving this view's shadow. 11344 if (isHardwareAccelerated() && getZ() != 0) { 11345 damageShadowReceiver(); 11346 } 11347 } 11348 } 11349 11350 /** 11351 * @return this view's projection receiver, or {@code null} if none exists 11352 */ 11353 private View getProjectionReceiver() { 11354 ViewParent p = getParent(); 11355 while (p != null && p instanceof View) { 11356 final View v = (View) p; 11357 if (v.isProjectionReceiver()) { 11358 return v; 11359 } 11360 p = p.getParent(); 11361 } 11362 11363 return null; 11364 } 11365 11366 /** 11367 * @return whether the view is a projection receiver 11368 */ 11369 private boolean isProjectionReceiver() { 11370 return mBackground != null; 11371 } 11372 11373 /** 11374 * Damage area of the screen that can be covered by this View's shadow. 11375 * 11376 * This method will guarantee that any changes to shadows cast by a View 11377 * are damaged on the screen for future redraw. 11378 */ 11379 private void damageShadowReceiver() { 11380 final AttachInfo ai = mAttachInfo; 11381 if (ai != null) { 11382 ViewParent p = getParent(); 11383 if (p != null && p instanceof ViewGroup) { 11384 final ViewGroup vg = (ViewGroup) p; 11385 vg.damageInParent(); 11386 } 11387 } 11388 } 11389 11390 /** 11391 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 11392 * set any flags or handle all of the cases handled by the default invalidation methods. 11393 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 11394 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 11395 * walk up the hierarchy, transforming the dirty rect as necessary. 11396 * 11397 * The method also handles normal invalidation logic if display list properties are not 11398 * being used in this view. The invalidateParent and forceRedraw flags are used by that 11399 * backup approach, to handle these cases used in the various property-setting methods. 11400 * 11401 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 11402 * are not being used in this view 11403 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 11404 * list properties are not being used in this view 11405 */ 11406 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 11407 if (!isHardwareAccelerated() 11408 || !mRenderNode.isValid() 11409 || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) { 11410 if (invalidateParent) { 11411 invalidateParentCaches(); 11412 } 11413 if (forceRedraw) { 11414 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 11415 } 11416 invalidate(false); 11417 } else { 11418 damageInParent(); 11419 } 11420 if (isHardwareAccelerated() && invalidateParent && getZ() != 0) { 11421 damageShadowReceiver(); 11422 } 11423 } 11424 11425 /** 11426 * Tells the parent view to damage this view's bounds. 11427 * 11428 * @hide 11429 */ 11430 protected void damageInParent() { 11431 final AttachInfo ai = mAttachInfo; 11432 final ViewParent p = mParent; 11433 if (p != null && ai != null) { 11434 final Rect r = ai.mTmpInvalRect; 11435 r.set(0, 0, mRight - mLeft, mBottom - mTop); 11436 if (mParent instanceof ViewGroup) { 11437 ((ViewGroup) mParent).damageChild(this, r); 11438 } else { 11439 mParent.invalidateChild(this, r); 11440 } 11441 } 11442 } 11443 11444 /** 11445 * Utility method to transform a given Rect by the current matrix of this view. 11446 */ 11447 void transformRect(final Rect rect) { 11448 if (!getMatrix().isIdentity()) { 11449 RectF boundingRect = mAttachInfo.mTmpTransformRect; 11450 boundingRect.set(rect); 11451 getMatrix().mapRect(boundingRect); 11452 rect.set((int) Math.floor(boundingRect.left), 11453 (int) Math.floor(boundingRect.top), 11454 (int) Math.ceil(boundingRect.right), 11455 (int) Math.ceil(boundingRect.bottom)); 11456 } 11457 } 11458 11459 /** 11460 * Used to indicate that the parent of this view should clear its caches. This functionality 11461 * is used to force the parent to rebuild its display list (when hardware-accelerated), 11462 * which is necessary when various parent-managed properties of the view change, such as 11463 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 11464 * clears the parent caches and does not causes an invalidate event. 11465 * 11466 * @hide 11467 */ 11468 protected void invalidateParentCaches() { 11469 if (mParent instanceof View) { 11470 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 11471 } 11472 } 11473 11474 /** 11475 * Used to indicate that the parent of this view should be invalidated. This functionality 11476 * is used to force the parent to rebuild its display list (when hardware-accelerated), 11477 * which is necessary when various parent-managed properties of the view change, such as 11478 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 11479 * an invalidation event to the parent. 11480 * 11481 * @hide 11482 */ 11483 protected void invalidateParentIfNeeded() { 11484 if (isHardwareAccelerated() && mParent instanceof View) { 11485 ((View) mParent).invalidate(true); 11486 } 11487 } 11488 11489 /** 11490 * @hide 11491 */ 11492 protected void invalidateParentIfNeededAndWasQuickRejected() { 11493 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) { 11494 // View was rejected last time it was drawn by its parent; this may have changed 11495 invalidateParentIfNeeded(); 11496 } 11497 } 11498 11499 /** 11500 * Indicates whether this View is opaque. An opaque View guarantees that it will 11501 * draw all the pixels overlapping its bounds using a fully opaque color. 11502 * 11503 * Subclasses of View should override this method whenever possible to indicate 11504 * whether an instance is opaque. Opaque Views are treated in a special way by 11505 * the View hierarchy, possibly allowing it to perform optimizations during 11506 * invalidate/draw passes. 11507 * 11508 * @return True if this View is guaranteed to be fully opaque, false otherwise. 11509 */ 11510 @ViewDebug.ExportedProperty(category = "drawing") 11511 public boolean isOpaque() { 11512 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 11513 getFinalAlpha() >= 1.0f; 11514 } 11515 11516 /** 11517 * @hide 11518 */ 11519 protected void computeOpaqueFlags() { 11520 // Opaque if: 11521 // - Has a background 11522 // - Background is opaque 11523 // - Doesn't have scrollbars or scrollbars overlay 11524 11525 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 11526 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 11527 } else { 11528 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 11529 } 11530 11531 final int flags = mViewFlags; 11532 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 11533 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY || 11534 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) { 11535 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 11536 } else { 11537 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 11538 } 11539 } 11540 11541 /** 11542 * @hide 11543 */ 11544 protected boolean hasOpaqueScrollbars() { 11545 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 11546 } 11547 11548 /** 11549 * @return A handler associated with the thread running the View. This 11550 * handler can be used to pump events in the UI events queue. 11551 */ 11552 public Handler getHandler() { 11553 final AttachInfo attachInfo = mAttachInfo; 11554 if (attachInfo != null) { 11555 return attachInfo.mHandler; 11556 } 11557 return null; 11558 } 11559 11560 /** 11561 * Gets the view root associated with the View. 11562 * @return The view root, or null if none. 11563 * @hide 11564 */ 11565 public ViewRootImpl getViewRootImpl() { 11566 if (mAttachInfo != null) { 11567 return mAttachInfo.mViewRootImpl; 11568 } 11569 return null; 11570 } 11571 11572 /** 11573 * @hide 11574 */ 11575 public HardwareRenderer getHardwareRenderer() { 11576 return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null; 11577 } 11578 11579 /** 11580 * <p>Causes the Runnable to be added to the message queue. 11581 * The runnable will be run on the user interface thread.</p> 11582 * 11583 * @param action The Runnable that will be executed. 11584 * 11585 * @return Returns true if the Runnable was successfully placed in to the 11586 * message queue. Returns false on failure, usually because the 11587 * looper processing the message queue is exiting. 11588 * 11589 * @see #postDelayed 11590 * @see #removeCallbacks 11591 */ 11592 public boolean post(Runnable action) { 11593 final AttachInfo attachInfo = mAttachInfo; 11594 if (attachInfo != null) { 11595 return attachInfo.mHandler.post(action); 11596 } 11597 // Assume that post will succeed later 11598 ViewRootImpl.getRunQueue().post(action); 11599 return true; 11600 } 11601 11602 /** 11603 * <p>Causes the Runnable to be added to the message queue, to be run 11604 * after the specified amount of time elapses. 11605 * The runnable will be run on the user interface thread.</p> 11606 * 11607 * @param action The Runnable that will be executed. 11608 * @param delayMillis The delay (in milliseconds) until the Runnable 11609 * will be executed. 11610 * 11611 * @return true if the Runnable was successfully placed in to the 11612 * message queue. Returns false on failure, usually because the 11613 * looper processing the message queue is exiting. Note that a 11614 * result of true does not mean the Runnable will be processed -- 11615 * if the looper is quit before the delivery time of the message 11616 * occurs then the message will be dropped. 11617 * 11618 * @see #post 11619 * @see #removeCallbacks 11620 */ 11621 public boolean postDelayed(Runnable action, long delayMillis) { 11622 final AttachInfo attachInfo = mAttachInfo; 11623 if (attachInfo != null) { 11624 return attachInfo.mHandler.postDelayed(action, delayMillis); 11625 } 11626 // Assume that post will succeed later 11627 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 11628 return true; 11629 } 11630 11631 /** 11632 * <p>Causes the Runnable to execute on the next animation time step. 11633 * The runnable will be run on the user interface thread.</p> 11634 * 11635 * @param action The Runnable that will be executed. 11636 * 11637 * @see #postOnAnimationDelayed 11638 * @see #removeCallbacks 11639 */ 11640 public void postOnAnimation(Runnable action) { 11641 final AttachInfo attachInfo = mAttachInfo; 11642 if (attachInfo != null) { 11643 attachInfo.mViewRootImpl.mChoreographer.postCallback( 11644 Choreographer.CALLBACK_ANIMATION, action, null); 11645 } else { 11646 // Assume that post will succeed later 11647 ViewRootImpl.getRunQueue().post(action); 11648 } 11649 } 11650 11651 /** 11652 * <p>Causes the Runnable to execute on the next animation time step, 11653 * after the specified amount of time elapses. 11654 * The runnable will be run on the user interface thread.</p> 11655 * 11656 * @param action The Runnable that will be executed. 11657 * @param delayMillis The delay (in milliseconds) until the Runnable 11658 * will be executed. 11659 * 11660 * @see #postOnAnimation 11661 * @see #removeCallbacks 11662 */ 11663 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 11664 final AttachInfo attachInfo = mAttachInfo; 11665 if (attachInfo != null) { 11666 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 11667 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 11668 } else { 11669 // Assume that post will succeed later 11670 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 11671 } 11672 } 11673 11674 /** 11675 * <p>Removes the specified Runnable from the message queue.</p> 11676 * 11677 * @param action The Runnable to remove from the message handling queue 11678 * 11679 * @return true if this view could ask the Handler to remove the Runnable, 11680 * false otherwise. When the returned value is true, the Runnable 11681 * may or may not have been actually removed from the message queue 11682 * (for instance, if the Runnable was not in the queue already.) 11683 * 11684 * @see #post 11685 * @see #postDelayed 11686 * @see #postOnAnimation 11687 * @see #postOnAnimationDelayed 11688 */ 11689 public boolean removeCallbacks(Runnable action) { 11690 if (action != null) { 11691 final AttachInfo attachInfo = mAttachInfo; 11692 if (attachInfo != null) { 11693 attachInfo.mHandler.removeCallbacks(action); 11694 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 11695 Choreographer.CALLBACK_ANIMATION, action, null); 11696 } 11697 // Assume that post will succeed later 11698 ViewRootImpl.getRunQueue().removeCallbacks(action); 11699 } 11700 return true; 11701 } 11702 11703 /** 11704 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 11705 * Use this to invalidate the View from a non-UI thread.</p> 11706 * 11707 * <p>This method can be invoked from outside of the UI thread 11708 * only when this View is attached to a window.</p> 11709 * 11710 * @see #invalidate() 11711 * @see #postInvalidateDelayed(long) 11712 */ 11713 public void postInvalidate() { 11714 postInvalidateDelayed(0); 11715 } 11716 11717 /** 11718 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 11719 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 11720 * 11721 * <p>This method can be invoked from outside of the UI thread 11722 * only when this View is attached to a window.</p> 11723 * 11724 * @param left The left coordinate of the rectangle to invalidate. 11725 * @param top The top coordinate of the rectangle to invalidate. 11726 * @param right The right coordinate of the rectangle to invalidate. 11727 * @param bottom The bottom coordinate of the rectangle to invalidate. 11728 * 11729 * @see #invalidate(int, int, int, int) 11730 * @see #invalidate(Rect) 11731 * @see #postInvalidateDelayed(long, int, int, int, int) 11732 */ 11733 public void postInvalidate(int left, int top, int right, int bottom) { 11734 postInvalidateDelayed(0, left, top, right, bottom); 11735 } 11736 11737 /** 11738 * <p>Cause an invalidate to happen on a subsequent cycle through the event 11739 * loop. Waits for the specified amount of time.</p> 11740 * 11741 * <p>This method can be invoked from outside of the UI thread 11742 * only when this View is attached to a window.</p> 11743 * 11744 * @param delayMilliseconds the duration in milliseconds to delay the 11745 * invalidation by 11746 * 11747 * @see #invalidate() 11748 * @see #postInvalidate() 11749 */ 11750 public void postInvalidateDelayed(long delayMilliseconds) { 11751 // We try only with the AttachInfo because there's no point in invalidating 11752 // if we are not attached to our window 11753 final AttachInfo attachInfo = mAttachInfo; 11754 if (attachInfo != null) { 11755 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 11756 } 11757 } 11758 11759 /** 11760 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 11761 * through the event loop. Waits for the specified amount of time.</p> 11762 * 11763 * <p>This method can be invoked from outside of the UI thread 11764 * only when this View is attached to a window.</p> 11765 * 11766 * @param delayMilliseconds the duration in milliseconds to delay the 11767 * invalidation by 11768 * @param left The left coordinate of the rectangle to invalidate. 11769 * @param top The top coordinate of the rectangle to invalidate. 11770 * @param right The right coordinate of the rectangle to invalidate. 11771 * @param bottom The bottom coordinate of the rectangle to invalidate. 11772 * 11773 * @see #invalidate(int, int, int, int) 11774 * @see #invalidate(Rect) 11775 * @see #postInvalidate(int, int, int, int) 11776 */ 11777 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 11778 int right, int bottom) { 11779 11780 // We try only with the AttachInfo because there's no point in invalidating 11781 // if we are not attached to our window 11782 final AttachInfo attachInfo = mAttachInfo; 11783 if (attachInfo != null) { 11784 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 11785 info.target = this; 11786 info.left = left; 11787 info.top = top; 11788 info.right = right; 11789 info.bottom = bottom; 11790 11791 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 11792 } 11793 } 11794 11795 /** 11796 * <p>Cause an invalidate to happen on the next animation time step, typically the 11797 * next display frame.</p> 11798 * 11799 * <p>This method can be invoked from outside of the UI thread 11800 * only when this View is attached to a window.</p> 11801 * 11802 * @see #invalidate() 11803 */ 11804 public void postInvalidateOnAnimation() { 11805 // We try only with the AttachInfo because there's no point in invalidating 11806 // if we are not attached to our window 11807 final AttachInfo attachInfo = mAttachInfo; 11808 if (attachInfo != null) { 11809 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 11810 } 11811 } 11812 11813 /** 11814 * <p>Cause an invalidate of the specified area to happen on the next animation 11815 * time step, typically the next display frame.</p> 11816 * 11817 * <p>This method can be invoked from outside of the UI thread 11818 * only when this View is attached to a window.</p> 11819 * 11820 * @param left The left coordinate of the rectangle to invalidate. 11821 * @param top The top coordinate of the rectangle to invalidate. 11822 * @param right The right coordinate of the rectangle to invalidate. 11823 * @param bottom The bottom coordinate of the rectangle to invalidate. 11824 * 11825 * @see #invalidate(int, int, int, int) 11826 * @see #invalidate(Rect) 11827 */ 11828 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 11829 // We try only with the AttachInfo because there's no point in invalidating 11830 // if we are not attached to our window 11831 final AttachInfo attachInfo = mAttachInfo; 11832 if (attachInfo != null) { 11833 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 11834 info.target = this; 11835 info.left = left; 11836 info.top = top; 11837 info.right = right; 11838 info.bottom = bottom; 11839 11840 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 11841 } 11842 } 11843 11844 /** 11845 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 11846 * This event is sent at most once every 11847 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 11848 */ 11849 private void postSendViewScrolledAccessibilityEventCallback() { 11850 if (mSendViewScrolledAccessibilityEvent == null) { 11851 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 11852 } 11853 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 11854 mSendViewScrolledAccessibilityEvent.mIsPending = true; 11855 postDelayed(mSendViewScrolledAccessibilityEvent, 11856 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 11857 } 11858 } 11859 11860 /** 11861 * Called by a parent to request that a child update its values for mScrollX 11862 * and mScrollY if necessary. This will typically be done if the child is 11863 * animating a scroll using a {@link android.widget.Scroller Scroller} 11864 * object. 11865 */ 11866 public void computeScroll() { 11867 } 11868 11869 /** 11870 * <p>Indicate whether the horizontal edges are faded when the view is 11871 * scrolled horizontally.</p> 11872 * 11873 * @return true if the horizontal edges should are faded on scroll, false 11874 * otherwise 11875 * 11876 * @see #setHorizontalFadingEdgeEnabled(boolean) 11877 * 11878 * @attr ref android.R.styleable#View_requiresFadingEdge 11879 */ 11880 public boolean isHorizontalFadingEdgeEnabled() { 11881 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 11882 } 11883 11884 /** 11885 * <p>Define whether the horizontal edges should be faded when this view 11886 * is scrolled horizontally.</p> 11887 * 11888 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 11889 * be faded when the view is scrolled 11890 * horizontally 11891 * 11892 * @see #isHorizontalFadingEdgeEnabled() 11893 * 11894 * @attr ref android.R.styleable#View_requiresFadingEdge 11895 */ 11896 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 11897 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 11898 if (horizontalFadingEdgeEnabled) { 11899 initScrollCache(); 11900 } 11901 11902 mViewFlags ^= FADING_EDGE_HORIZONTAL; 11903 } 11904 } 11905 11906 /** 11907 * <p>Indicate whether the vertical edges are faded when the view is 11908 * scrolled horizontally.</p> 11909 * 11910 * @return true if the vertical edges should are faded on scroll, false 11911 * otherwise 11912 * 11913 * @see #setVerticalFadingEdgeEnabled(boolean) 11914 * 11915 * @attr ref android.R.styleable#View_requiresFadingEdge 11916 */ 11917 public boolean isVerticalFadingEdgeEnabled() { 11918 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 11919 } 11920 11921 /** 11922 * <p>Define whether the vertical edges should be faded when this view 11923 * is scrolled vertically.</p> 11924 * 11925 * @param verticalFadingEdgeEnabled true if the vertical edges should 11926 * be faded when the view is scrolled 11927 * vertically 11928 * 11929 * @see #isVerticalFadingEdgeEnabled() 11930 * 11931 * @attr ref android.R.styleable#View_requiresFadingEdge 11932 */ 11933 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 11934 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 11935 if (verticalFadingEdgeEnabled) { 11936 initScrollCache(); 11937 } 11938 11939 mViewFlags ^= FADING_EDGE_VERTICAL; 11940 } 11941 } 11942 11943 /** 11944 * Returns the strength, or intensity, of the top faded edge. The strength is 11945 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11946 * returns 0.0 or 1.0 but no value in between. 11947 * 11948 * Subclasses should override this method to provide a smoother fade transition 11949 * when scrolling occurs. 11950 * 11951 * @return the intensity of the top fade as a float between 0.0f and 1.0f 11952 */ 11953 protected float getTopFadingEdgeStrength() { 11954 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 11955 } 11956 11957 /** 11958 * Returns the strength, or intensity, of the bottom faded edge. The strength is 11959 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11960 * returns 0.0 or 1.0 but no value in between. 11961 * 11962 * Subclasses should override this method to provide a smoother fade transition 11963 * when scrolling occurs. 11964 * 11965 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 11966 */ 11967 protected float getBottomFadingEdgeStrength() { 11968 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 11969 computeVerticalScrollRange() ? 1.0f : 0.0f; 11970 } 11971 11972 /** 11973 * Returns the strength, or intensity, of the left faded edge. The strength is 11974 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11975 * returns 0.0 or 1.0 but no value in between. 11976 * 11977 * Subclasses should override this method to provide a smoother fade transition 11978 * when scrolling occurs. 11979 * 11980 * @return the intensity of the left fade as a float between 0.0f and 1.0f 11981 */ 11982 protected float getLeftFadingEdgeStrength() { 11983 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 11984 } 11985 11986 /** 11987 * Returns the strength, or intensity, of the right faded edge. The strength is 11988 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11989 * returns 0.0 or 1.0 but no value in between. 11990 * 11991 * Subclasses should override this method to provide a smoother fade transition 11992 * when scrolling occurs. 11993 * 11994 * @return the intensity of the right fade as a float between 0.0f and 1.0f 11995 */ 11996 protected float getRightFadingEdgeStrength() { 11997 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 11998 computeHorizontalScrollRange() ? 1.0f : 0.0f; 11999 } 12000 12001 /** 12002 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 12003 * scrollbar is not drawn by default.</p> 12004 * 12005 * @return true if the horizontal scrollbar should be painted, false 12006 * otherwise 12007 * 12008 * @see #setHorizontalScrollBarEnabled(boolean) 12009 */ 12010 public boolean isHorizontalScrollBarEnabled() { 12011 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 12012 } 12013 12014 /** 12015 * <p>Define whether the horizontal scrollbar should be drawn or not. The 12016 * scrollbar is not drawn by default.</p> 12017 * 12018 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 12019 * be painted 12020 * 12021 * @see #isHorizontalScrollBarEnabled() 12022 */ 12023 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 12024 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 12025 mViewFlags ^= SCROLLBARS_HORIZONTAL; 12026 computeOpaqueFlags(); 12027 resolvePadding(); 12028 } 12029 } 12030 12031 /** 12032 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 12033 * scrollbar is not drawn by default.</p> 12034 * 12035 * @return true if the vertical scrollbar should be painted, false 12036 * otherwise 12037 * 12038 * @see #setVerticalScrollBarEnabled(boolean) 12039 */ 12040 public boolean isVerticalScrollBarEnabled() { 12041 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 12042 } 12043 12044 /** 12045 * <p>Define whether the vertical scrollbar should be drawn or not. The 12046 * scrollbar is not drawn by default.</p> 12047 * 12048 * @param verticalScrollBarEnabled true if the vertical scrollbar should 12049 * be painted 12050 * 12051 * @see #isVerticalScrollBarEnabled() 12052 */ 12053 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 12054 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 12055 mViewFlags ^= SCROLLBARS_VERTICAL; 12056 computeOpaqueFlags(); 12057 resolvePadding(); 12058 } 12059 } 12060 12061 /** 12062 * @hide 12063 */ 12064 protected void recomputePadding() { 12065 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 12066 } 12067 12068 /** 12069 * Define whether scrollbars will fade when the view is not scrolling. 12070 * 12071 * @param fadeScrollbars wheter to enable fading 12072 * 12073 * @attr ref android.R.styleable#View_fadeScrollbars 12074 */ 12075 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 12076 initScrollCache(); 12077 final ScrollabilityCache scrollabilityCache = mScrollCache; 12078 scrollabilityCache.fadeScrollBars = fadeScrollbars; 12079 if (fadeScrollbars) { 12080 scrollabilityCache.state = ScrollabilityCache.OFF; 12081 } else { 12082 scrollabilityCache.state = ScrollabilityCache.ON; 12083 } 12084 } 12085 12086 /** 12087 * 12088 * Returns true if scrollbars will fade when this view is not scrolling 12089 * 12090 * @return true if scrollbar fading is enabled 12091 * 12092 * @attr ref android.R.styleable#View_fadeScrollbars 12093 */ 12094 public boolean isScrollbarFadingEnabled() { 12095 return mScrollCache != null && mScrollCache.fadeScrollBars; 12096 } 12097 12098 /** 12099 * 12100 * Returns the delay before scrollbars fade. 12101 * 12102 * @return the delay before scrollbars fade 12103 * 12104 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 12105 */ 12106 public int getScrollBarDefaultDelayBeforeFade() { 12107 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 12108 mScrollCache.scrollBarDefaultDelayBeforeFade; 12109 } 12110 12111 /** 12112 * Define the delay before scrollbars fade. 12113 * 12114 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 12115 * 12116 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 12117 */ 12118 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 12119 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 12120 } 12121 12122 /** 12123 * 12124 * Returns the scrollbar fade duration. 12125 * 12126 * @return the scrollbar fade duration 12127 * 12128 * @attr ref android.R.styleable#View_scrollbarFadeDuration 12129 */ 12130 public int getScrollBarFadeDuration() { 12131 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 12132 mScrollCache.scrollBarFadeDuration; 12133 } 12134 12135 /** 12136 * Define the scrollbar fade duration. 12137 * 12138 * @param scrollBarFadeDuration - the scrollbar fade duration 12139 * 12140 * @attr ref android.R.styleable#View_scrollbarFadeDuration 12141 */ 12142 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 12143 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 12144 } 12145 12146 /** 12147 * 12148 * Returns the scrollbar size. 12149 * 12150 * @return the scrollbar size 12151 * 12152 * @attr ref android.R.styleable#View_scrollbarSize 12153 */ 12154 public int getScrollBarSize() { 12155 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 12156 mScrollCache.scrollBarSize; 12157 } 12158 12159 /** 12160 * Define the scrollbar size. 12161 * 12162 * @param scrollBarSize - the scrollbar size 12163 * 12164 * @attr ref android.R.styleable#View_scrollbarSize 12165 */ 12166 public void setScrollBarSize(int scrollBarSize) { 12167 getScrollCache().scrollBarSize = scrollBarSize; 12168 } 12169 12170 /** 12171 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 12172 * inset. When inset, they add to the padding of the view. And the scrollbars 12173 * can be drawn inside the padding area or on the edge of the view. For example, 12174 * if a view has a background drawable and you want to draw the scrollbars 12175 * inside the padding specified by the drawable, you can use 12176 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 12177 * appear at the edge of the view, ignoring the padding, then you can use 12178 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 12179 * @param style the style of the scrollbars. Should be one of 12180 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 12181 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 12182 * @see #SCROLLBARS_INSIDE_OVERLAY 12183 * @see #SCROLLBARS_INSIDE_INSET 12184 * @see #SCROLLBARS_OUTSIDE_OVERLAY 12185 * @see #SCROLLBARS_OUTSIDE_INSET 12186 * 12187 * @attr ref android.R.styleable#View_scrollbarStyle 12188 */ 12189 public void setScrollBarStyle(@ScrollBarStyle int style) { 12190 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 12191 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 12192 computeOpaqueFlags(); 12193 resolvePadding(); 12194 } 12195 } 12196 12197 /** 12198 * <p>Returns the current scrollbar style.</p> 12199 * @return the current scrollbar style 12200 * @see #SCROLLBARS_INSIDE_OVERLAY 12201 * @see #SCROLLBARS_INSIDE_INSET 12202 * @see #SCROLLBARS_OUTSIDE_OVERLAY 12203 * @see #SCROLLBARS_OUTSIDE_INSET 12204 * 12205 * @attr ref android.R.styleable#View_scrollbarStyle 12206 */ 12207 @ViewDebug.ExportedProperty(mapping = { 12208 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 12209 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 12210 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 12211 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 12212 }) 12213 @ScrollBarStyle 12214 public int getScrollBarStyle() { 12215 return mViewFlags & SCROLLBARS_STYLE_MASK; 12216 } 12217 12218 /** 12219 * <p>Compute the horizontal range that the horizontal scrollbar 12220 * represents.</p> 12221 * 12222 * <p>The range is expressed in arbitrary units that must be the same as the 12223 * units used by {@link #computeHorizontalScrollExtent()} and 12224 * {@link #computeHorizontalScrollOffset()}.</p> 12225 * 12226 * <p>The default range is the drawing width of this view.</p> 12227 * 12228 * @return the total horizontal range represented by the horizontal 12229 * scrollbar 12230 * 12231 * @see #computeHorizontalScrollExtent() 12232 * @see #computeHorizontalScrollOffset() 12233 * @see android.widget.ScrollBarDrawable 12234 */ 12235 protected int computeHorizontalScrollRange() { 12236 return getWidth(); 12237 } 12238 12239 /** 12240 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 12241 * within the horizontal range. This value is used to compute the position 12242 * of the thumb within the scrollbar's track.</p> 12243 * 12244 * <p>The range is expressed in arbitrary units that must be the same as the 12245 * units used by {@link #computeHorizontalScrollRange()} and 12246 * {@link #computeHorizontalScrollExtent()}.</p> 12247 * 12248 * <p>The default offset is the scroll offset of this view.</p> 12249 * 12250 * @return the horizontal offset of the scrollbar's thumb 12251 * 12252 * @see #computeHorizontalScrollRange() 12253 * @see #computeHorizontalScrollExtent() 12254 * @see android.widget.ScrollBarDrawable 12255 */ 12256 protected int computeHorizontalScrollOffset() { 12257 return mScrollX; 12258 } 12259 12260 /** 12261 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 12262 * within the horizontal range. This value is used to compute the length 12263 * of the thumb within the scrollbar's track.</p> 12264 * 12265 * <p>The range is expressed in arbitrary units that must be the same as the 12266 * units used by {@link #computeHorizontalScrollRange()} and 12267 * {@link #computeHorizontalScrollOffset()}.</p> 12268 * 12269 * <p>The default extent is the drawing width of this view.</p> 12270 * 12271 * @return the horizontal extent of the scrollbar's thumb 12272 * 12273 * @see #computeHorizontalScrollRange() 12274 * @see #computeHorizontalScrollOffset() 12275 * @see android.widget.ScrollBarDrawable 12276 */ 12277 protected int computeHorizontalScrollExtent() { 12278 return getWidth(); 12279 } 12280 12281 /** 12282 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 12283 * 12284 * <p>The range is expressed in arbitrary units that must be the same as the 12285 * units used by {@link #computeVerticalScrollExtent()} and 12286 * {@link #computeVerticalScrollOffset()}.</p> 12287 * 12288 * @return the total vertical range represented by the vertical scrollbar 12289 * 12290 * <p>The default range is the drawing height of this view.</p> 12291 * 12292 * @see #computeVerticalScrollExtent() 12293 * @see #computeVerticalScrollOffset() 12294 * @see android.widget.ScrollBarDrawable 12295 */ 12296 protected int computeVerticalScrollRange() { 12297 return getHeight(); 12298 } 12299 12300 /** 12301 * <p>Compute the vertical offset of the vertical scrollbar's thumb 12302 * within the horizontal range. This value is used to compute the position 12303 * of the thumb within the scrollbar's track.</p> 12304 * 12305 * <p>The range is expressed in arbitrary units that must be the same as the 12306 * units used by {@link #computeVerticalScrollRange()} and 12307 * {@link #computeVerticalScrollExtent()}.</p> 12308 * 12309 * <p>The default offset is the scroll offset of this view.</p> 12310 * 12311 * @return the vertical offset of the scrollbar's thumb 12312 * 12313 * @see #computeVerticalScrollRange() 12314 * @see #computeVerticalScrollExtent() 12315 * @see android.widget.ScrollBarDrawable 12316 */ 12317 protected int computeVerticalScrollOffset() { 12318 return mScrollY; 12319 } 12320 12321 /** 12322 * <p>Compute the vertical extent of the vertical scrollbar's thumb 12323 * within the vertical range. This value is used to compute the length 12324 * of the thumb within the scrollbar's track.</p> 12325 * 12326 * <p>The range is expressed in arbitrary units that must be the same as the 12327 * units used by {@link #computeVerticalScrollRange()} and 12328 * {@link #computeVerticalScrollOffset()}.</p> 12329 * 12330 * <p>The default extent is the drawing height of this view.</p> 12331 * 12332 * @return the vertical extent of the scrollbar's thumb 12333 * 12334 * @see #computeVerticalScrollRange() 12335 * @see #computeVerticalScrollOffset() 12336 * @see android.widget.ScrollBarDrawable 12337 */ 12338 protected int computeVerticalScrollExtent() { 12339 return getHeight(); 12340 } 12341 12342 /** 12343 * Check if this view can be scrolled horizontally in a certain direction. 12344 * 12345 * @param direction Negative to check scrolling left, positive to check scrolling right. 12346 * @return true if this view can be scrolled in the specified direction, false otherwise. 12347 */ 12348 public boolean canScrollHorizontally(int direction) { 12349 final int offset = computeHorizontalScrollOffset(); 12350 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 12351 if (range == 0) return false; 12352 if (direction < 0) { 12353 return offset > 0; 12354 } else { 12355 return offset < range - 1; 12356 } 12357 } 12358 12359 /** 12360 * Check if this view can be scrolled vertically in a certain direction. 12361 * 12362 * @param direction Negative to check scrolling up, positive to check scrolling down. 12363 * @return true if this view can be scrolled in the specified direction, false otherwise. 12364 */ 12365 public boolean canScrollVertically(int direction) { 12366 final int offset = computeVerticalScrollOffset(); 12367 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 12368 if (range == 0) return false; 12369 if (direction < 0) { 12370 return offset > 0; 12371 } else { 12372 return offset < range - 1; 12373 } 12374 } 12375 12376 /** 12377 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 12378 * scrollbars are painted only if they have been awakened first.</p> 12379 * 12380 * @param canvas the canvas on which to draw the scrollbars 12381 * 12382 * @see #awakenScrollBars(int) 12383 */ 12384 protected final void onDrawScrollBars(Canvas canvas) { 12385 // scrollbars are drawn only when the animation is running 12386 final ScrollabilityCache cache = mScrollCache; 12387 if (cache != null) { 12388 12389 int state = cache.state; 12390 12391 if (state == ScrollabilityCache.OFF) { 12392 return; 12393 } 12394 12395 boolean invalidate = false; 12396 12397 if (state == ScrollabilityCache.FADING) { 12398 // We're fading -- get our fade interpolation 12399 if (cache.interpolatorValues == null) { 12400 cache.interpolatorValues = new float[1]; 12401 } 12402 12403 float[] values = cache.interpolatorValues; 12404 12405 // Stops the animation if we're done 12406 if (cache.scrollBarInterpolator.timeToValues(values) == 12407 Interpolator.Result.FREEZE_END) { 12408 cache.state = ScrollabilityCache.OFF; 12409 } else { 12410 cache.scrollBar.setAlpha(Math.round(values[0])); 12411 } 12412 12413 // This will make the scroll bars inval themselves after 12414 // drawing. We only want this when we're fading so that 12415 // we prevent excessive redraws 12416 invalidate = true; 12417 } else { 12418 // We're just on -- but we may have been fading before so 12419 // reset alpha 12420 cache.scrollBar.setAlpha(255); 12421 } 12422 12423 12424 final int viewFlags = mViewFlags; 12425 12426 final boolean drawHorizontalScrollBar = 12427 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 12428 final boolean drawVerticalScrollBar = 12429 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 12430 && !isVerticalScrollBarHidden(); 12431 12432 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 12433 final int width = mRight - mLeft; 12434 final int height = mBottom - mTop; 12435 12436 final ScrollBarDrawable scrollBar = cache.scrollBar; 12437 12438 final int scrollX = mScrollX; 12439 final int scrollY = mScrollY; 12440 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 12441 12442 int left; 12443 int top; 12444 int right; 12445 int bottom; 12446 12447 if (drawHorizontalScrollBar) { 12448 int size = scrollBar.getSize(false); 12449 if (size <= 0) { 12450 size = cache.scrollBarSize; 12451 } 12452 12453 scrollBar.setParameters(computeHorizontalScrollRange(), 12454 computeHorizontalScrollOffset(), 12455 computeHorizontalScrollExtent(), false); 12456 final int verticalScrollBarGap = drawVerticalScrollBar ? 12457 getVerticalScrollbarWidth() : 0; 12458 top = scrollY + height - size - (mUserPaddingBottom & inside); 12459 left = scrollX + (mPaddingLeft & inside); 12460 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 12461 bottom = top + size; 12462 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 12463 if (invalidate) { 12464 invalidate(left, top, right, bottom); 12465 } 12466 } 12467 12468 if (drawVerticalScrollBar) { 12469 int size = scrollBar.getSize(true); 12470 if (size <= 0) { 12471 size = cache.scrollBarSize; 12472 } 12473 12474 scrollBar.setParameters(computeVerticalScrollRange(), 12475 computeVerticalScrollOffset(), 12476 computeVerticalScrollExtent(), true); 12477 int verticalScrollbarPosition = mVerticalScrollbarPosition; 12478 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 12479 verticalScrollbarPosition = isLayoutRtl() ? 12480 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 12481 } 12482 switch (verticalScrollbarPosition) { 12483 default: 12484 case SCROLLBAR_POSITION_RIGHT: 12485 left = scrollX + width - size - (mUserPaddingRight & inside); 12486 break; 12487 case SCROLLBAR_POSITION_LEFT: 12488 left = scrollX + (mUserPaddingLeft & inside); 12489 break; 12490 } 12491 top = scrollY + (mPaddingTop & inside); 12492 right = left + size; 12493 bottom = scrollY + height - (mUserPaddingBottom & inside); 12494 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 12495 if (invalidate) { 12496 invalidate(left, top, right, bottom); 12497 } 12498 } 12499 } 12500 } 12501 } 12502 12503 /** 12504 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 12505 * FastScroller is visible. 12506 * @return whether to temporarily hide the vertical scrollbar 12507 * @hide 12508 */ 12509 protected boolean isVerticalScrollBarHidden() { 12510 return false; 12511 } 12512 12513 /** 12514 * <p>Draw the horizontal scrollbar if 12515 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 12516 * 12517 * @param canvas the canvas on which to draw the scrollbar 12518 * @param scrollBar the scrollbar's drawable 12519 * 12520 * @see #isHorizontalScrollBarEnabled() 12521 * @see #computeHorizontalScrollRange() 12522 * @see #computeHorizontalScrollExtent() 12523 * @see #computeHorizontalScrollOffset() 12524 * @see android.widget.ScrollBarDrawable 12525 * @hide 12526 */ 12527 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 12528 int l, int t, int r, int b) { 12529 scrollBar.setBounds(l, t, r, b); 12530 scrollBar.draw(canvas); 12531 } 12532 12533 /** 12534 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 12535 * returns true.</p> 12536 * 12537 * @param canvas the canvas on which to draw the scrollbar 12538 * @param scrollBar the scrollbar's drawable 12539 * 12540 * @see #isVerticalScrollBarEnabled() 12541 * @see #computeVerticalScrollRange() 12542 * @see #computeVerticalScrollExtent() 12543 * @see #computeVerticalScrollOffset() 12544 * @see android.widget.ScrollBarDrawable 12545 * @hide 12546 */ 12547 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 12548 int l, int t, int r, int b) { 12549 scrollBar.setBounds(l, t, r, b); 12550 scrollBar.draw(canvas); 12551 } 12552 12553 /** 12554 * Implement this to do your drawing. 12555 * 12556 * @param canvas the canvas on which the background will be drawn 12557 */ 12558 protected void onDraw(Canvas canvas) { 12559 } 12560 12561 /* 12562 * Caller is responsible for calling requestLayout if necessary. 12563 * (This allows addViewInLayout to not request a new layout.) 12564 */ 12565 void assignParent(ViewParent parent) { 12566 if (mParent == null) { 12567 mParent = parent; 12568 } else if (parent == null) { 12569 mParent = null; 12570 } else { 12571 throw new RuntimeException("view " + this + " being added, but" 12572 + " it already has a parent"); 12573 } 12574 } 12575 12576 /** 12577 * This is called when the view is attached to a window. At this point it 12578 * has a Surface and will start drawing. Note that this function is 12579 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 12580 * however it may be called any time before the first onDraw -- including 12581 * before or after {@link #onMeasure(int, int)}. 12582 * 12583 * @see #onDetachedFromWindow() 12584 */ 12585 protected void onAttachedToWindow() { 12586 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 12587 mParent.requestTransparentRegion(this); 12588 } 12589 12590 if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 12591 initialAwakenScrollBars(); 12592 mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 12593 } 12594 12595 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 12596 12597 jumpDrawablesToCurrentState(); 12598 12599 resetSubtreeAccessibilityStateChanged(); 12600 12601 if (isFocused()) { 12602 InputMethodManager imm = InputMethodManager.peekInstance(); 12603 imm.focusIn(this); 12604 } 12605 } 12606 12607 /** 12608 * Resolve all RTL related properties. 12609 * 12610 * @return true if resolution of RTL properties has been done 12611 * 12612 * @hide 12613 */ 12614 public boolean resolveRtlPropertiesIfNeeded() { 12615 if (!needRtlPropertiesResolution()) return false; 12616 12617 // Order is important here: LayoutDirection MUST be resolved first 12618 if (!isLayoutDirectionResolved()) { 12619 resolveLayoutDirection(); 12620 resolveLayoutParams(); 12621 } 12622 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 12623 if (!isTextDirectionResolved()) { 12624 resolveTextDirection(); 12625 } 12626 if (!isTextAlignmentResolved()) { 12627 resolveTextAlignment(); 12628 } 12629 // Should resolve Drawables before Padding because we need the layout direction of the 12630 // Drawable to correctly resolve Padding. 12631 if (!isDrawablesResolved()) { 12632 resolveDrawables(); 12633 } 12634 if (!isPaddingResolved()) { 12635 resolvePadding(); 12636 } 12637 onRtlPropertiesChanged(getLayoutDirection()); 12638 return true; 12639 } 12640 12641 /** 12642 * Reset resolution of all RTL related properties. 12643 * 12644 * @hide 12645 */ 12646 public void resetRtlProperties() { 12647 resetResolvedLayoutDirection(); 12648 resetResolvedTextDirection(); 12649 resetResolvedTextAlignment(); 12650 resetResolvedPadding(); 12651 resetResolvedDrawables(); 12652 } 12653 12654 /** 12655 * @see #onScreenStateChanged(int) 12656 */ 12657 void dispatchScreenStateChanged(int screenState) { 12658 onScreenStateChanged(screenState); 12659 } 12660 12661 /** 12662 * This method is called whenever the state of the screen this view is 12663 * attached to changes. A state change will usually occurs when the screen 12664 * turns on or off (whether it happens automatically or the user does it 12665 * manually.) 12666 * 12667 * @param screenState The new state of the screen. Can be either 12668 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 12669 */ 12670 public void onScreenStateChanged(int screenState) { 12671 } 12672 12673 /** 12674 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 12675 */ 12676 private boolean hasRtlSupport() { 12677 return mContext.getApplicationInfo().hasRtlSupport(); 12678 } 12679 12680 /** 12681 * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or 12682 * RTL not supported) 12683 */ 12684 private boolean isRtlCompatibilityMode() { 12685 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 12686 return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport(); 12687 } 12688 12689 /** 12690 * @return true if RTL properties need resolution. 12691 * 12692 */ 12693 private boolean needRtlPropertiesResolution() { 12694 return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED; 12695 } 12696 12697 /** 12698 * Called when any RTL property (layout direction or text direction or text alignment) has 12699 * been changed. 12700 * 12701 * Subclasses need to override this method to take care of cached information that depends on the 12702 * resolved layout direction, or to inform child views that inherit their layout direction. 12703 * 12704 * The default implementation does nothing. 12705 * 12706 * @param layoutDirection the direction of the layout 12707 * 12708 * @see #LAYOUT_DIRECTION_LTR 12709 * @see #LAYOUT_DIRECTION_RTL 12710 */ 12711 public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) { 12712 } 12713 12714 /** 12715 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 12716 * that the parent directionality can and will be resolved before its children. 12717 * 12718 * @return true if resolution has been done, false otherwise. 12719 * 12720 * @hide 12721 */ 12722 public boolean resolveLayoutDirection() { 12723 // Clear any previous layout direction resolution 12724 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 12725 12726 if (hasRtlSupport()) { 12727 // Set resolved depending on layout direction 12728 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 12729 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 12730 case LAYOUT_DIRECTION_INHERIT: 12731 // We cannot resolve yet. LTR is by default and let the resolution happen again 12732 // later to get the correct resolved value 12733 if (!canResolveLayoutDirection()) return false; 12734 12735 // Parent has not yet resolved, LTR is still the default 12736 try { 12737 if (!mParent.isLayoutDirectionResolved()) return false; 12738 12739 if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 12740 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12741 } 12742 } catch (AbstractMethodError e) { 12743 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 12744 " does not fully implement ViewParent", e); 12745 } 12746 break; 12747 case LAYOUT_DIRECTION_RTL: 12748 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12749 break; 12750 case LAYOUT_DIRECTION_LOCALE: 12751 if((LAYOUT_DIRECTION_RTL == 12752 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) { 12753 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12754 } 12755 break; 12756 default: 12757 // Nothing to do, LTR by default 12758 } 12759 } 12760 12761 // Set to resolved 12762 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 12763 return true; 12764 } 12765 12766 /** 12767 * Check if layout direction resolution can be done. 12768 * 12769 * @return true if layout direction resolution can be done otherwise return false. 12770 */ 12771 public boolean canResolveLayoutDirection() { 12772 switch (getRawLayoutDirection()) { 12773 case LAYOUT_DIRECTION_INHERIT: 12774 if (mParent != null) { 12775 try { 12776 return mParent.canResolveLayoutDirection(); 12777 } catch (AbstractMethodError e) { 12778 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 12779 " does not fully implement ViewParent", e); 12780 } 12781 } 12782 return false; 12783 12784 default: 12785 return true; 12786 } 12787 } 12788 12789 /** 12790 * Reset the resolved layout direction. Layout direction will be resolved during a call to 12791 * {@link #onMeasure(int, int)}. 12792 * 12793 * @hide 12794 */ 12795 public void resetResolvedLayoutDirection() { 12796 // Reset the current resolved bits 12797 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 12798 } 12799 12800 /** 12801 * @return true if the layout direction is inherited. 12802 * 12803 * @hide 12804 */ 12805 public boolean isLayoutDirectionInherited() { 12806 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT); 12807 } 12808 12809 /** 12810 * @return true if layout direction has been resolved. 12811 */ 12812 public boolean isLayoutDirectionResolved() { 12813 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED; 12814 } 12815 12816 /** 12817 * Return if padding has been resolved 12818 * 12819 * @hide 12820 */ 12821 boolean isPaddingResolved() { 12822 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED; 12823 } 12824 12825 /** 12826 * Resolves padding depending on layout direction, if applicable, and 12827 * recomputes internal padding values to adjust for scroll bars. 12828 * 12829 * @hide 12830 */ 12831 public void resolvePadding() { 12832 final int resolvedLayoutDirection = getLayoutDirection(); 12833 12834 if (!isRtlCompatibilityMode()) { 12835 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 12836 // If start / end padding are defined, they will be resolved (hence overriding) to 12837 // left / right or right / left depending on the resolved layout direction. 12838 // If start / end padding are not defined, use the left / right ones. 12839 if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) { 12840 Rect padding = sThreadLocal.get(); 12841 if (padding == null) { 12842 padding = new Rect(); 12843 sThreadLocal.set(padding); 12844 } 12845 mBackground.getPadding(padding); 12846 if (!mLeftPaddingDefined) { 12847 mUserPaddingLeftInitial = padding.left; 12848 } 12849 if (!mRightPaddingDefined) { 12850 mUserPaddingRightInitial = padding.right; 12851 } 12852 } 12853 switch (resolvedLayoutDirection) { 12854 case LAYOUT_DIRECTION_RTL: 12855 if (mUserPaddingStart != UNDEFINED_PADDING) { 12856 mUserPaddingRight = mUserPaddingStart; 12857 } else { 12858 mUserPaddingRight = mUserPaddingRightInitial; 12859 } 12860 if (mUserPaddingEnd != UNDEFINED_PADDING) { 12861 mUserPaddingLeft = mUserPaddingEnd; 12862 } else { 12863 mUserPaddingLeft = mUserPaddingLeftInitial; 12864 } 12865 break; 12866 case LAYOUT_DIRECTION_LTR: 12867 default: 12868 if (mUserPaddingStart != UNDEFINED_PADDING) { 12869 mUserPaddingLeft = mUserPaddingStart; 12870 } else { 12871 mUserPaddingLeft = mUserPaddingLeftInitial; 12872 } 12873 if (mUserPaddingEnd != UNDEFINED_PADDING) { 12874 mUserPaddingRight = mUserPaddingEnd; 12875 } else { 12876 mUserPaddingRight = mUserPaddingRightInitial; 12877 } 12878 } 12879 12880 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 12881 } 12882 12883 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 12884 onRtlPropertiesChanged(resolvedLayoutDirection); 12885 12886 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 12887 } 12888 12889 /** 12890 * Reset the resolved layout direction. 12891 * 12892 * @hide 12893 */ 12894 public void resetResolvedPadding() { 12895 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 12896 } 12897 12898 /** 12899 * This is called when the view is detached from a window. At this point it 12900 * no longer has a surface for drawing. 12901 * 12902 * @see #onAttachedToWindow() 12903 */ 12904 protected void onDetachedFromWindow() { 12905 } 12906 12907 /** 12908 * This is a framework-internal mirror of onDetachedFromWindow() that's called 12909 * after onDetachedFromWindow(). 12910 * 12911 * If you override this you *MUST* call super.onDetachedFromWindowInternal()! 12912 * The super method should be called at the end of the overriden method to ensure 12913 * subclasses are destroyed first 12914 * 12915 * @hide 12916 */ 12917 protected void onDetachedFromWindowInternal() { 12918 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 12919 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 12920 12921 removeUnsetPressCallback(); 12922 removeLongPressCallback(); 12923 removePerformClickCallback(); 12924 removeSendViewScrolledAccessibilityEventCallback(); 12925 stopNestedScroll(); 12926 12927 destroyDrawingCache(); 12928 destroyLayer(false); 12929 12930 cleanupDraw(); 12931 mCurrentAnimation = null; 12932 } 12933 12934 private void cleanupDraw() { 12935 resetDisplayList(); 12936 if (mAttachInfo != null) { 12937 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 12938 } 12939 } 12940 12941 /** 12942 * This method ensures the hardware renderer is in a valid state 12943 * before executing the specified action. 12944 * 12945 * This method will attempt to set a valid state even if the window 12946 * the renderer is attached to was destroyed. 12947 * 12948 * This method is not guaranteed to work. If the hardware renderer 12949 * does not exist or cannot be put in a valid state, this method 12950 * will not executed the specified action. 12951 * 12952 * The specified action is executed synchronously. 12953 * 12954 * @param action The action to execute after the renderer is in a valid state 12955 * 12956 * @return True if the specified Runnable was executed, false otherwise 12957 * 12958 * @hide 12959 */ 12960 public boolean executeHardwareAction(Runnable action) { 12961 //noinspection SimplifiableIfStatement 12962 if (mAttachInfo != null && mAttachInfo.mHardwareRenderer != null) { 12963 return mAttachInfo.mHardwareRenderer.safelyRun(action); 12964 } 12965 return false; 12966 } 12967 12968 void invalidateInheritedLayoutMode(int layoutModeOfRoot) { 12969 } 12970 12971 /** 12972 * @return The number of times this view has been attached to a window 12973 */ 12974 protected int getWindowAttachCount() { 12975 return mWindowAttachCount; 12976 } 12977 12978 /** 12979 * Retrieve a unique token identifying the window this view is attached to. 12980 * @return Return the window's token for use in 12981 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 12982 */ 12983 public IBinder getWindowToken() { 12984 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 12985 } 12986 12987 /** 12988 * Retrieve the {@link WindowId} for the window this view is 12989 * currently attached to. 12990 */ 12991 public WindowId getWindowId() { 12992 if (mAttachInfo == null) { 12993 return null; 12994 } 12995 if (mAttachInfo.mWindowId == null) { 12996 try { 12997 mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId( 12998 mAttachInfo.mWindowToken); 12999 mAttachInfo.mWindowId = new WindowId( 13000 mAttachInfo.mIWindowId); 13001 } catch (RemoteException e) { 13002 } 13003 } 13004 return mAttachInfo.mWindowId; 13005 } 13006 13007 /** 13008 * Retrieve a unique token identifying the top-level "real" window of 13009 * the window that this view is attached to. That is, this is like 13010 * {@link #getWindowToken}, except if the window this view in is a panel 13011 * window (attached to another containing window), then the token of 13012 * the containing window is returned instead. 13013 * 13014 * @return Returns the associated window token, either 13015 * {@link #getWindowToken()} or the containing window's token. 13016 */ 13017 public IBinder getApplicationWindowToken() { 13018 AttachInfo ai = mAttachInfo; 13019 if (ai != null) { 13020 IBinder appWindowToken = ai.mPanelParentWindowToken; 13021 if (appWindowToken == null) { 13022 appWindowToken = ai.mWindowToken; 13023 } 13024 return appWindowToken; 13025 } 13026 return null; 13027 } 13028 13029 /** 13030 * Gets the logical display to which the view's window has been attached. 13031 * 13032 * @return The logical display, or null if the view is not currently attached to a window. 13033 */ 13034 public Display getDisplay() { 13035 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 13036 } 13037 13038 /** 13039 * Retrieve private session object this view hierarchy is using to 13040 * communicate with the window manager. 13041 * @return the session object to communicate with the window manager 13042 */ 13043 /*package*/ IWindowSession getWindowSession() { 13044 return mAttachInfo != null ? mAttachInfo.mSession : null; 13045 } 13046 13047 /** 13048 * @param info the {@link android.view.View.AttachInfo} to associated with 13049 * this view 13050 */ 13051 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 13052 //System.out.println("Attached! " + this); 13053 mAttachInfo = info; 13054 if (mOverlay != null) { 13055 mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility); 13056 } 13057 mWindowAttachCount++; 13058 // We will need to evaluate the drawable state at least once. 13059 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 13060 if (mFloatingTreeObserver != null) { 13061 info.mTreeObserver.merge(mFloatingTreeObserver); 13062 mFloatingTreeObserver = null; 13063 } 13064 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 13065 mAttachInfo.mScrollContainers.add(this); 13066 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 13067 } 13068 performCollectViewAttributes(mAttachInfo, visibility); 13069 onAttachedToWindow(); 13070 13071 ListenerInfo li = mListenerInfo; 13072 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 13073 li != null ? li.mOnAttachStateChangeListeners : null; 13074 if (listeners != null && listeners.size() > 0) { 13075 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 13076 // perform the dispatching. The iterator is a safe guard against listeners that 13077 // could mutate the list by calling the various add/remove methods. This prevents 13078 // the array from being modified while we iterate it. 13079 for (OnAttachStateChangeListener listener : listeners) { 13080 listener.onViewAttachedToWindow(this); 13081 } 13082 } 13083 13084 int vis = info.mWindowVisibility; 13085 if (vis != GONE) { 13086 onWindowVisibilityChanged(vis); 13087 } 13088 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 13089 // If nobody has evaluated the drawable state yet, then do it now. 13090 refreshDrawableState(); 13091 } 13092 needGlobalAttributesUpdate(false); 13093 } 13094 13095 void dispatchDetachedFromWindow() { 13096 AttachInfo info = mAttachInfo; 13097 if (info != null) { 13098 int vis = info.mWindowVisibility; 13099 if (vis != GONE) { 13100 onWindowVisibilityChanged(GONE); 13101 } 13102 } 13103 13104 onDetachedFromWindow(); 13105 onDetachedFromWindowInternal(); 13106 13107 ListenerInfo li = mListenerInfo; 13108 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 13109 li != null ? li.mOnAttachStateChangeListeners : null; 13110 if (listeners != null && listeners.size() > 0) { 13111 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 13112 // perform the dispatching. The iterator is a safe guard against listeners that 13113 // could mutate the list by calling the various add/remove methods. This prevents 13114 // the array from being modified while we iterate it. 13115 for (OnAttachStateChangeListener listener : listeners) { 13116 listener.onViewDetachedFromWindow(this); 13117 } 13118 } 13119 13120 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 13121 mAttachInfo.mScrollContainers.remove(this); 13122 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 13123 } 13124 13125 mAttachInfo = null; 13126 if (mOverlay != null) { 13127 mOverlay.getOverlayView().dispatchDetachedFromWindow(); 13128 } 13129 } 13130 13131 /** 13132 * Cancel any deferred high-level input events that were previously posted to the event queue. 13133 * 13134 * <p>Many views post high-level events such as click handlers to the event queue 13135 * to run deferred in order to preserve a desired user experience - clearing visible 13136 * pressed states before executing, etc. This method will abort any events of this nature 13137 * that are currently in flight.</p> 13138 * 13139 * <p>Custom views that generate their own high-level deferred input events should override 13140 * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p> 13141 * 13142 * <p>This will also cancel pending input events for any child views.</p> 13143 * 13144 * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases. 13145 * This will not impact newer events posted after this call that may occur as a result of 13146 * lower-level input events still waiting in the queue. If you are trying to prevent 13147 * double-submitted events for the duration of some sort of asynchronous transaction 13148 * you should also take other steps to protect against unexpected double inputs e.g. calling 13149 * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when 13150 * the transaction completes, tracking already submitted transaction IDs, etc.</p> 13151 */ 13152 public final void cancelPendingInputEvents() { 13153 dispatchCancelPendingInputEvents(); 13154 } 13155 13156 /** 13157 * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight. 13158 * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling. 13159 */ 13160 void dispatchCancelPendingInputEvents() { 13161 mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER; 13162 onCancelPendingInputEvents(); 13163 if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) { 13164 throw new SuperNotCalledException("View " + getClass().getSimpleName() + 13165 " did not call through to super.onCancelPendingInputEvents()"); 13166 } 13167 } 13168 13169 /** 13170 * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or 13171 * a parent view. 13172 * 13173 * <p>This method is responsible for removing any pending high-level input events that were 13174 * posted to the event queue to run later. Custom view classes that post their own deferred 13175 * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or 13176 * {@link android.os.Handler} should override this method, call 13177 * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate. 13178 * </p> 13179 */ 13180 public void onCancelPendingInputEvents() { 13181 removePerformClickCallback(); 13182 cancelLongPress(); 13183 mPrivateFlags3 |= PFLAG3_CALLED_SUPER; 13184 } 13185 13186 /** 13187 * Store this view hierarchy's frozen state into the given container. 13188 * 13189 * @param container The SparseArray in which to save the view's state. 13190 * 13191 * @see #restoreHierarchyState(android.util.SparseArray) 13192 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13193 * @see #onSaveInstanceState() 13194 */ 13195 public void saveHierarchyState(SparseArray<Parcelable> container) { 13196 dispatchSaveInstanceState(container); 13197 } 13198 13199 /** 13200 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 13201 * this view and its children. May be overridden to modify how freezing happens to a 13202 * view's children; for example, some views may want to not store state for their children. 13203 * 13204 * @param container The SparseArray in which to save the view's state. 13205 * 13206 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13207 * @see #saveHierarchyState(android.util.SparseArray) 13208 * @see #onSaveInstanceState() 13209 */ 13210 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 13211 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 13212 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 13213 Parcelable state = onSaveInstanceState(); 13214 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 13215 throw new IllegalStateException( 13216 "Derived class did not call super.onSaveInstanceState()"); 13217 } 13218 if (state != null) { 13219 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 13220 // + ": " + state); 13221 container.put(mID, state); 13222 } 13223 } 13224 } 13225 13226 /** 13227 * Hook allowing a view to generate a representation of its internal state 13228 * that can later be used to create a new instance with that same state. 13229 * This state should only contain information that is not persistent or can 13230 * not be reconstructed later. For example, you will never store your 13231 * current position on screen because that will be computed again when a 13232 * new instance of the view is placed in its view hierarchy. 13233 * <p> 13234 * Some examples of things you may store here: the current cursor position 13235 * in a text view (but usually not the text itself since that is stored in a 13236 * content provider or other persistent storage), the currently selected 13237 * item in a list view. 13238 * 13239 * @return Returns a Parcelable object containing the view's current dynamic 13240 * state, or null if there is nothing interesting to save. The 13241 * default implementation returns null. 13242 * @see #onRestoreInstanceState(android.os.Parcelable) 13243 * @see #saveHierarchyState(android.util.SparseArray) 13244 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13245 * @see #setSaveEnabled(boolean) 13246 */ 13247 protected Parcelable onSaveInstanceState() { 13248 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 13249 return BaseSavedState.EMPTY_STATE; 13250 } 13251 13252 /** 13253 * Restore this view hierarchy's frozen state from the given container. 13254 * 13255 * @param container The SparseArray which holds previously frozen states. 13256 * 13257 * @see #saveHierarchyState(android.util.SparseArray) 13258 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13259 * @see #onRestoreInstanceState(android.os.Parcelable) 13260 */ 13261 public void restoreHierarchyState(SparseArray<Parcelable> container) { 13262 dispatchRestoreInstanceState(container); 13263 } 13264 13265 /** 13266 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 13267 * state for this view and its children. May be overridden to modify how restoring 13268 * happens to a view's children; for example, some views may want to not store state 13269 * for their children. 13270 * 13271 * @param container The SparseArray which holds previously saved state. 13272 * 13273 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13274 * @see #restoreHierarchyState(android.util.SparseArray) 13275 * @see #onRestoreInstanceState(android.os.Parcelable) 13276 */ 13277 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 13278 if (mID != NO_ID) { 13279 Parcelable state = container.get(mID); 13280 if (state != null) { 13281 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 13282 // + ": " + state); 13283 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 13284 onRestoreInstanceState(state); 13285 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 13286 throw new IllegalStateException( 13287 "Derived class did not call super.onRestoreInstanceState()"); 13288 } 13289 } 13290 } 13291 } 13292 13293 /** 13294 * Hook allowing a view to re-apply a representation of its internal state that had previously 13295 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 13296 * null state. 13297 * 13298 * @param state The frozen state that had previously been returned by 13299 * {@link #onSaveInstanceState}. 13300 * 13301 * @see #onSaveInstanceState() 13302 * @see #restoreHierarchyState(android.util.SparseArray) 13303 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13304 */ 13305 protected void onRestoreInstanceState(Parcelable state) { 13306 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 13307 if (state != BaseSavedState.EMPTY_STATE && state != null) { 13308 throw new IllegalArgumentException("Wrong state class, expecting View State but " 13309 + "received " + state.getClass().toString() + " instead. This usually happens " 13310 + "when two views of different type have the same id in the same hierarchy. " 13311 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 13312 + "other views do not use the same id."); 13313 } 13314 } 13315 13316 /** 13317 * <p>Return the time at which the drawing of the view hierarchy started.</p> 13318 * 13319 * @return the drawing start time in milliseconds 13320 */ 13321 public long getDrawingTime() { 13322 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 13323 } 13324 13325 /** 13326 * <p>Enables or disables the duplication of the parent's state into this view. When 13327 * duplication is enabled, this view gets its drawable state from its parent rather 13328 * than from its own internal properties.</p> 13329 * 13330 * <p>Note: in the current implementation, setting this property to true after the 13331 * view was added to a ViewGroup might have no effect at all. This property should 13332 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 13333 * 13334 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 13335 * property is enabled, an exception will be thrown.</p> 13336 * 13337 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 13338 * parent, these states should not be affected by this method.</p> 13339 * 13340 * @param enabled True to enable duplication of the parent's drawable state, false 13341 * to disable it. 13342 * 13343 * @see #getDrawableState() 13344 * @see #isDuplicateParentStateEnabled() 13345 */ 13346 public void setDuplicateParentStateEnabled(boolean enabled) { 13347 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 13348 } 13349 13350 /** 13351 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 13352 * 13353 * @return True if this view's drawable state is duplicated from the parent, 13354 * false otherwise 13355 * 13356 * @see #getDrawableState() 13357 * @see #setDuplicateParentStateEnabled(boolean) 13358 */ 13359 public boolean isDuplicateParentStateEnabled() { 13360 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 13361 } 13362 13363 /** 13364 * <p>Specifies the type of layer backing this view. The layer can be 13365 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13366 * {@link #LAYER_TYPE_HARDWARE}.</p> 13367 * 13368 * <p>A layer is associated with an optional {@link android.graphics.Paint} 13369 * instance that controls how the layer is composed on screen. The following 13370 * properties of the paint are taken into account when composing the layer:</p> 13371 * <ul> 13372 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 13373 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 13374 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 13375 * </ul> 13376 * 13377 * <p>If this view has an alpha value set to < 1.0 by calling 13378 * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded 13379 * by this view's alpha value.</p> 13380 * 13381 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE}, 13382 * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE} 13383 * for more information on when and how to use layers.</p> 13384 * 13385 * @param layerType The type of layer to use with this view, must be one of 13386 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13387 * {@link #LAYER_TYPE_HARDWARE} 13388 * @param paint The paint used to compose the layer. This argument is optional 13389 * and can be null. It is ignored when the layer type is 13390 * {@link #LAYER_TYPE_NONE} 13391 * 13392 * @see #getLayerType() 13393 * @see #LAYER_TYPE_NONE 13394 * @see #LAYER_TYPE_SOFTWARE 13395 * @see #LAYER_TYPE_HARDWARE 13396 * @see #setAlpha(float) 13397 * 13398 * @attr ref android.R.styleable#View_layerType 13399 */ 13400 public void setLayerType(int layerType, Paint paint) { 13401 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 13402 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 13403 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 13404 } 13405 13406 if (layerType == mLayerType) { 13407 setLayerPaint(paint); 13408 return; 13409 } 13410 13411 // Destroy any previous software drawing cache if needed 13412 switch (mLayerType) { 13413 case LAYER_TYPE_HARDWARE: 13414 destroyLayer(false); 13415 // fall through - non-accelerated views may use software layer mechanism instead 13416 case LAYER_TYPE_SOFTWARE: 13417 destroyDrawingCache(); 13418 break; 13419 default: 13420 break; 13421 } 13422 13423 mLayerType = layerType; 13424 final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE; 13425 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 13426 mLocalDirtyRect = layerDisabled ? null : new Rect(); 13427 13428 invalidateParentCaches(); 13429 invalidate(true); 13430 } 13431 13432 /** 13433 * Updates the {@link Paint} object used with the current layer (used only if the current 13434 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 13435 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 13436 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 13437 * ensure that the view gets redrawn immediately. 13438 * 13439 * <p>A layer is associated with an optional {@link android.graphics.Paint} 13440 * instance that controls how the layer is composed on screen. The following 13441 * properties of the paint are taken into account when composing the layer:</p> 13442 * <ul> 13443 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 13444 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 13445 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 13446 * </ul> 13447 * 13448 * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the 13449 * alpha value of the layer's paint is superceded by this view's alpha value.</p> 13450 * 13451 * @param paint The paint used to compose the layer. This argument is optional 13452 * and can be null. It is ignored when the layer type is 13453 * {@link #LAYER_TYPE_NONE} 13454 * 13455 * @see #setLayerType(int, android.graphics.Paint) 13456 */ 13457 public void setLayerPaint(Paint paint) { 13458 int layerType = getLayerType(); 13459 if (layerType != LAYER_TYPE_NONE) { 13460 mLayerPaint = paint == null ? new Paint() : paint; 13461 if (layerType == LAYER_TYPE_HARDWARE) { 13462 HardwareLayer layer = getHardwareLayer(); 13463 if (layer != null) { 13464 layer.setLayerPaint(mLayerPaint); 13465 } 13466 invalidateViewProperty(false, false); 13467 } else { 13468 invalidate(); 13469 } 13470 } 13471 } 13472 13473 /** 13474 * Indicates whether this view has a static layer. A view with layer type 13475 * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are 13476 * dynamic. 13477 */ 13478 boolean hasStaticLayer() { 13479 return true; 13480 } 13481 13482 /** 13483 * Indicates what type of layer is currently associated with this view. By default 13484 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 13485 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 13486 * for more information on the different types of layers. 13487 * 13488 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13489 * {@link #LAYER_TYPE_HARDWARE} 13490 * 13491 * @see #setLayerType(int, android.graphics.Paint) 13492 * @see #buildLayer() 13493 * @see #LAYER_TYPE_NONE 13494 * @see #LAYER_TYPE_SOFTWARE 13495 * @see #LAYER_TYPE_HARDWARE 13496 */ 13497 public int getLayerType() { 13498 return mLayerType; 13499 } 13500 13501 /** 13502 * Forces this view's layer to be created and this view to be rendered 13503 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 13504 * invoking this method will have no effect. 13505 * 13506 * This method can for instance be used to render a view into its layer before 13507 * starting an animation. If this view is complex, rendering into the layer 13508 * before starting the animation will avoid skipping frames. 13509 * 13510 * @throws IllegalStateException If this view is not attached to a window 13511 * 13512 * @see #setLayerType(int, android.graphics.Paint) 13513 */ 13514 public void buildLayer() { 13515 if (mLayerType == LAYER_TYPE_NONE) return; 13516 13517 final AttachInfo attachInfo = mAttachInfo; 13518 if (attachInfo == null) { 13519 throw new IllegalStateException("This view must be attached to a window first"); 13520 } 13521 13522 switch (mLayerType) { 13523 case LAYER_TYPE_HARDWARE: 13524 getHardwareLayer(); 13525 // TODO: We need a better way to handle this case 13526 // If views have registered pre-draw listeners they need 13527 // to be notified before we build the layer. Those listeners 13528 // may however rely on other events to happen first so we 13529 // cannot just invoke them here until they don't cancel the 13530 // current frame 13531 if (!attachInfo.mTreeObserver.hasOnPreDrawListeners()) { 13532 attachInfo.mViewRootImpl.dispatchFlushHardwareLayerUpdates(); 13533 } 13534 break; 13535 case LAYER_TYPE_SOFTWARE: 13536 buildDrawingCache(true); 13537 break; 13538 } 13539 } 13540 13541 /** 13542 * <p>Returns a hardware layer that can be used to draw this view again 13543 * without executing its draw method.</p> 13544 * 13545 * @return A HardwareLayer ready to render, or null if an error occurred. 13546 */ 13547 HardwareLayer getHardwareLayer() { 13548 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null || 13549 !mAttachInfo.mHardwareRenderer.isEnabled()) { 13550 return null; 13551 } 13552 13553 final int width = mRight - mLeft; 13554 final int height = mBottom - mTop; 13555 13556 if (width == 0 || height == 0) { 13557 return null; 13558 } 13559 13560 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) { 13561 if (mHardwareLayer == null) { 13562 mHardwareLayer = mAttachInfo.mHardwareRenderer.createDisplayListLayer( 13563 width, height); 13564 mLocalDirtyRect.set(0, 0, width, height); 13565 } else if (mHardwareLayer.isValid()) { 13566 // This should not be necessary but applications that change 13567 // the parameters of their background drawable without calling 13568 // this.setBackground(Drawable) can leave the view in a bad state 13569 // (for instance isOpaque() returns true, but the background is 13570 // not opaque.) 13571 computeOpaqueFlags(); 13572 13573 if (mHardwareLayer.prepare(width, height, isOpaque())) { 13574 mLocalDirtyRect.set(0, 0, width, height); 13575 } 13576 } 13577 13578 mHardwareLayer.setLayerPaint(mLayerPaint); 13579 RenderNode displayList = mHardwareLayer.startRecording(); 13580 updateDisplayListIfDirty(displayList, true); 13581 mHardwareLayer.endRecording(mLocalDirtyRect); 13582 mLocalDirtyRect.setEmpty(); 13583 } 13584 13585 return mHardwareLayer; 13586 } 13587 13588 /** 13589 * Destroys this View's hardware layer if possible. 13590 * 13591 * @return True if the layer was destroyed, false otherwise. 13592 * 13593 * @see #setLayerType(int, android.graphics.Paint) 13594 * @see #LAYER_TYPE_HARDWARE 13595 */ 13596 boolean destroyLayer(boolean valid) { 13597 if (mHardwareLayer != null) { 13598 mHardwareLayer.destroy(); 13599 mHardwareLayer = null; 13600 13601 invalidate(true); 13602 invalidateParentCaches(); 13603 return true; 13604 } 13605 return false; 13606 } 13607 13608 /** 13609 * Destroys all hardware rendering resources. This method is invoked 13610 * when the system needs to reclaim resources. Upon execution of this 13611 * method, you should free any OpenGL resources created by the view. 13612 * 13613 * Note: you <strong>must</strong> call 13614 * <code>super.destroyHardwareResources()</code> when overriding 13615 * this method. 13616 * 13617 * @hide 13618 */ 13619 protected void destroyHardwareResources() { 13620 resetDisplayList(); 13621 destroyLayer(true); 13622 } 13623 13624 /** 13625 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 13626 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 13627 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 13628 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 13629 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 13630 * null.</p> 13631 * 13632 * <p>Enabling the drawing cache is similar to 13633 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 13634 * acceleration is turned off. When hardware acceleration is turned on, enabling the 13635 * drawing cache has no effect on rendering because the system uses a different mechanism 13636 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 13637 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 13638 * for information on how to enable software and hardware layers.</p> 13639 * 13640 * <p>This API can be used to manually generate 13641 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 13642 * {@link #getDrawingCache()}.</p> 13643 * 13644 * @param enabled true to enable the drawing cache, false otherwise 13645 * 13646 * @see #isDrawingCacheEnabled() 13647 * @see #getDrawingCache() 13648 * @see #buildDrawingCache() 13649 * @see #setLayerType(int, android.graphics.Paint) 13650 */ 13651 public void setDrawingCacheEnabled(boolean enabled) { 13652 mCachingFailed = false; 13653 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 13654 } 13655 13656 /** 13657 * <p>Indicates whether the drawing cache is enabled for this view.</p> 13658 * 13659 * @return true if the drawing cache is enabled 13660 * 13661 * @see #setDrawingCacheEnabled(boolean) 13662 * @see #getDrawingCache() 13663 */ 13664 @ViewDebug.ExportedProperty(category = "drawing") 13665 public boolean isDrawingCacheEnabled() { 13666 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 13667 } 13668 13669 /** 13670 * Debugging utility which recursively outputs the dirty state of a view and its 13671 * descendants. 13672 * 13673 * @hide 13674 */ 13675 @SuppressWarnings({"UnusedDeclaration"}) 13676 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 13677 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 13678 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 13679 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 13680 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 13681 if (clear) { 13682 mPrivateFlags &= clearMask; 13683 } 13684 if (this instanceof ViewGroup) { 13685 ViewGroup parent = (ViewGroup) this; 13686 final int count = parent.getChildCount(); 13687 for (int i = 0; i < count; i++) { 13688 final View child = parent.getChildAt(i); 13689 child.outputDirtyFlags(indent + " ", clear, clearMask); 13690 } 13691 } 13692 } 13693 13694 /** 13695 * This method is used by ViewGroup to cause its children to restore or recreate their 13696 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 13697 * to recreate its own display list, which would happen if it went through the normal 13698 * draw/dispatchDraw mechanisms. 13699 * 13700 * @hide 13701 */ 13702 protected void dispatchGetDisplayList() {} 13703 13704 /** 13705 * A view that is not attached or hardware accelerated cannot create a display list. 13706 * This method checks these conditions and returns the appropriate result. 13707 * 13708 * @return true if view has the ability to create a display list, false otherwise. 13709 * 13710 * @hide 13711 */ 13712 public boolean canHaveDisplayList() { 13713 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 13714 } 13715 13716 /** 13717 * Returns a DisplayList. If the incoming displayList is null, one will be created. 13718 * Otherwise, the same display list will be returned (after having been rendered into 13719 * along the way, depending on the invalidation state of the view). 13720 * 13721 * @param renderNode The previous version of this displayList, could be null. 13722 * @param isLayer Whether the requester of the display list is a layer. If so, 13723 * the view will avoid creating a layer inside the resulting display list. 13724 * @return A new or reused DisplayList object. 13725 */ 13726 private void updateDisplayListIfDirty(@NonNull RenderNode renderNode, boolean isLayer) { 13727 if (renderNode == null) { 13728 throw new IllegalArgumentException("RenderNode must not be null"); 13729 } 13730 if (!canHaveDisplayList()) { 13731 // can't populate RenderNode, don't try 13732 return; 13733 } 13734 13735 renderNode.setScrollPosition(mScrollX, mScrollY); 13736 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 13737 || !renderNode.isValid() 13738 || (!isLayer && mRecreateDisplayList)) { 13739 // Don't need to recreate the display list, just need to tell our 13740 // children to restore/recreate theirs 13741 if (renderNode.isValid() 13742 && !isLayer 13743 && !mRecreateDisplayList) { 13744 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13745 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13746 dispatchGetDisplayList(); 13747 13748 return; // no work needed 13749 } 13750 13751 if (!isLayer) { 13752 // If we got here, we're recreating it. Mark it as such to ensure that 13753 // we copy in child display lists into ours in drawChild() 13754 mRecreateDisplayList = true; 13755 } 13756 13757 boolean caching = false; 13758 int width = mRight - mLeft; 13759 int height = mBottom - mTop; 13760 int layerType = getLayerType(); 13761 13762 final HardwareCanvas canvas = renderNode.start(width, height); 13763 13764 try { 13765 if (!isLayer && layerType != LAYER_TYPE_NONE) { 13766 if (layerType == LAYER_TYPE_HARDWARE) { 13767 final HardwareLayer layer = getHardwareLayer(); 13768 if (layer != null && layer.isValid()) { 13769 canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint); 13770 } else { 13771 canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint, 13772 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | 13773 Canvas.CLIP_TO_LAYER_SAVE_FLAG); 13774 } 13775 caching = true; 13776 } else { 13777 buildDrawingCache(true); 13778 Bitmap cache = getDrawingCache(true); 13779 if (cache != null) { 13780 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 13781 caching = true; 13782 } 13783 } 13784 } else { 13785 13786 computeScroll(); 13787 13788 canvas.translate(-mScrollX, -mScrollY); 13789 if (!isLayer) { 13790 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13791 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13792 } 13793 13794 // Fast path for layouts with no backgrounds 13795 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 13796 dispatchDraw(canvas); 13797 if (mOverlay != null && !mOverlay.isEmpty()) { 13798 mOverlay.getOverlayView().draw(canvas); 13799 } 13800 } else { 13801 draw(canvas); 13802 } 13803 } 13804 } finally { 13805 renderNode.end(canvas); 13806 renderNode.setCaching(caching); 13807 if (isLayer) { 13808 renderNode.setLeftTopRightBottom(0, 0, width, height); 13809 } else { 13810 setDisplayListProperties(renderNode); 13811 } 13812 } 13813 } else if (!isLayer) { 13814 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13815 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13816 } 13817 } 13818 13819 /** 13820 * Returns a RenderNode with View draw content recorded, which can be 13821 * used to draw this view again without executing its draw method. 13822 * 13823 * @return A RenderNode ready to replay, or null if caching is not enabled. 13824 * 13825 * @hide 13826 */ 13827 public RenderNode getDisplayList() { 13828 updateDisplayListIfDirty(mRenderNode, false); 13829 return mRenderNode; 13830 } 13831 13832 private void resetDisplayList() { 13833 if (mRenderNode.isValid()) { 13834 mRenderNode.destroyDisplayListData(); 13835 } 13836 13837 if (mBackgroundDisplayList != null && mBackgroundDisplayList.isValid()) { 13838 mBackgroundDisplayList.destroyDisplayListData(); 13839 } 13840 } 13841 13842 /** 13843 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 13844 * 13845 * @return A non-scaled bitmap representing this view or null if cache is disabled. 13846 * 13847 * @see #getDrawingCache(boolean) 13848 */ 13849 public Bitmap getDrawingCache() { 13850 return getDrawingCache(false); 13851 } 13852 13853 /** 13854 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 13855 * is null when caching is disabled. If caching is enabled and the cache is not ready, 13856 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 13857 * draw from the cache when the cache is enabled. To benefit from the cache, you must 13858 * request the drawing cache by calling this method and draw it on screen if the 13859 * returned bitmap is not null.</p> 13860 * 13861 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 13862 * this method will create a bitmap of the same size as this view. Because this bitmap 13863 * will be drawn scaled by the parent ViewGroup, the result on screen might show 13864 * scaling artifacts. To avoid such artifacts, you should call this method by setting 13865 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 13866 * size than the view. This implies that your application must be able to handle this 13867 * size.</p> 13868 * 13869 * @param autoScale Indicates whether the generated bitmap should be scaled based on 13870 * the current density of the screen when the application is in compatibility 13871 * mode. 13872 * 13873 * @return A bitmap representing this view or null if cache is disabled. 13874 * 13875 * @see #setDrawingCacheEnabled(boolean) 13876 * @see #isDrawingCacheEnabled() 13877 * @see #buildDrawingCache(boolean) 13878 * @see #destroyDrawingCache() 13879 */ 13880 public Bitmap getDrawingCache(boolean autoScale) { 13881 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 13882 return null; 13883 } 13884 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 13885 buildDrawingCache(autoScale); 13886 } 13887 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 13888 } 13889 13890 /** 13891 * <p>Frees the resources used by the drawing cache. If you call 13892 * {@link #buildDrawingCache()} manually without calling 13893 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 13894 * should cleanup the cache with this method afterwards.</p> 13895 * 13896 * @see #setDrawingCacheEnabled(boolean) 13897 * @see #buildDrawingCache() 13898 * @see #getDrawingCache() 13899 */ 13900 public void destroyDrawingCache() { 13901 if (mDrawingCache != null) { 13902 mDrawingCache.recycle(); 13903 mDrawingCache = null; 13904 } 13905 if (mUnscaledDrawingCache != null) { 13906 mUnscaledDrawingCache.recycle(); 13907 mUnscaledDrawingCache = null; 13908 } 13909 } 13910 13911 /** 13912 * Setting a solid background color for the drawing cache's bitmaps will improve 13913 * performance and memory usage. Note, though that this should only be used if this 13914 * view will always be drawn on top of a solid color. 13915 * 13916 * @param color The background color to use for the drawing cache's bitmap 13917 * 13918 * @see #setDrawingCacheEnabled(boolean) 13919 * @see #buildDrawingCache() 13920 * @see #getDrawingCache() 13921 */ 13922 public void setDrawingCacheBackgroundColor(int color) { 13923 if (color != mDrawingCacheBackgroundColor) { 13924 mDrawingCacheBackgroundColor = color; 13925 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 13926 } 13927 } 13928 13929 /** 13930 * @see #setDrawingCacheBackgroundColor(int) 13931 * 13932 * @return The background color to used for the drawing cache's bitmap 13933 */ 13934 public int getDrawingCacheBackgroundColor() { 13935 return mDrawingCacheBackgroundColor; 13936 } 13937 13938 /** 13939 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 13940 * 13941 * @see #buildDrawingCache(boolean) 13942 */ 13943 public void buildDrawingCache() { 13944 buildDrawingCache(false); 13945 } 13946 13947 /** 13948 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 13949 * 13950 * <p>If you call {@link #buildDrawingCache()} manually without calling 13951 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 13952 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 13953 * 13954 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 13955 * this method will create a bitmap of the same size as this view. Because this bitmap 13956 * will be drawn scaled by the parent ViewGroup, the result on screen might show 13957 * scaling artifacts. To avoid such artifacts, you should call this method by setting 13958 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 13959 * size than the view. This implies that your application must be able to handle this 13960 * size.</p> 13961 * 13962 * <p>You should avoid calling this method when hardware acceleration is enabled. If 13963 * you do not need the drawing cache bitmap, calling this method will increase memory 13964 * usage and cause the view to be rendered in software once, thus negatively impacting 13965 * performance.</p> 13966 * 13967 * @see #getDrawingCache() 13968 * @see #destroyDrawingCache() 13969 */ 13970 public void buildDrawingCache(boolean autoScale) { 13971 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 13972 mDrawingCache == null : mUnscaledDrawingCache == null)) { 13973 mCachingFailed = false; 13974 13975 int width = mRight - mLeft; 13976 int height = mBottom - mTop; 13977 13978 final AttachInfo attachInfo = mAttachInfo; 13979 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 13980 13981 if (autoScale && scalingRequired) { 13982 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 13983 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 13984 } 13985 13986 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 13987 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 13988 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 13989 13990 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 13991 final long drawingCacheSize = 13992 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 13993 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 13994 if (width > 0 && height > 0) { 13995 Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs " 13996 + projectedBitmapSize + " bytes, only " 13997 + drawingCacheSize + " available"); 13998 } 13999 destroyDrawingCache(); 14000 mCachingFailed = true; 14001 return; 14002 } 14003 14004 boolean clear = true; 14005 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 14006 14007 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 14008 Bitmap.Config quality; 14009 if (!opaque) { 14010 // Never pick ARGB_4444 because it looks awful 14011 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 14012 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 14013 case DRAWING_CACHE_QUALITY_AUTO: 14014 case DRAWING_CACHE_QUALITY_LOW: 14015 case DRAWING_CACHE_QUALITY_HIGH: 14016 default: 14017 quality = Bitmap.Config.ARGB_8888; 14018 break; 14019 } 14020 } else { 14021 // Optimization for translucent windows 14022 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 14023 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 14024 } 14025 14026 // Try to cleanup memory 14027 if (bitmap != null) bitmap.recycle(); 14028 14029 try { 14030 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 14031 width, height, quality); 14032 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 14033 if (autoScale) { 14034 mDrawingCache = bitmap; 14035 } else { 14036 mUnscaledDrawingCache = bitmap; 14037 } 14038 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 14039 } catch (OutOfMemoryError e) { 14040 // If there is not enough memory to create the bitmap cache, just 14041 // ignore the issue as bitmap caches are not required to draw the 14042 // view hierarchy 14043 if (autoScale) { 14044 mDrawingCache = null; 14045 } else { 14046 mUnscaledDrawingCache = null; 14047 } 14048 mCachingFailed = true; 14049 return; 14050 } 14051 14052 clear = drawingCacheBackgroundColor != 0; 14053 } 14054 14055 Canvas canvas; 14056 if (attachInfo != null) { 14057 canvas = attachInfo.mCanvas; 14058 if (canvas == null) { 14059 canvas = new Canvas(); 14060 } 14061 canvas.setBitmap(bitmap); 14062 // Temporarily clobber the cached Canvas in case one of our children 14063 // is also using a drawing cache. Without this, the children would 14064 // steal the canvas by attaching their own bitmap to it and bad, bad 14065 // thing would happen (invisible views, corrupted drawings, etc.) 14066 attachInfo.mCanvas = null; 14067 } else { 14068 // This case should hopefully never or seldom happen 14069 canvas = new Canvas(bitmap); 14070 } 14071 14072 if (clear) { 14073 bitmap.eraseColor(drawingCacheBackgroundColor); 14074 } 14075 14076 computeScroll(); 14077 final int restoreCount = canvas.save(); 14078 14079 if (autoScale && scalingRequired) { 14080 final float scale = attachInfo.mApplicationScale; 14081 canvas.scale(scale, scale); 14082 } 14083 14084 canvas.translate(-mScrollX, -mScrollY); 14085 14086 mPrivateFlags |= PFLAG_DRAWN; 14087 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 14088 mLayerType != LAYER_TYPE_NONE) { 14089 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 14090 } 14091 14092 // Fast path for layouts with no backgrounds 14093 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14094 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14095 dispatchDraw(canvas); 14096 if (mOverlay != null && !mOverlay.isEmpty()) { 14097 mOverlay.getOverlayView().draw(canvas); 14098 } 14099 } else { 14100 draw(canvas); 14101 } 14102 14103 canvas.restoreToCount(restoreCount); 14104 canvas.setBitmap(null); 14105 14106 if (attachInfo != null) { 14107 // Restore the cached Canvas for our siblings 14108 attachInfo.mCanvas = canvas; 14109 } 14110 } 14111 } 14112 14113 /** 14114 * Create a snapshot of the view into a bitmap. We should probably make 14115 * some form of this public, but should think about the API. 14116 */ 14117 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 14118 int width = mRight - mLeft; 14119 int height = mBottom - mTop; 14120 14121 final AttachInfo attachInfo = mAttachInfo; 14122 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 14123 width = (int) ((width * scale) + 0.5f); 14124 height = (int) ((height * scale) + 0.5f); 14125 14126 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 14127 width > 0 ? width : 1, height > 0 ? height : 1, quality); 14128 if (bitmap == null) { 14129 throw new OutOfMemoryError(); 14130 } 14131 14132 Resources resources = getResources(); 14133 if (resources != null) { 14134 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 14135 } 14136 14137 Canvas canvas; 14138 if (attachInfo != null) { 14139 canvas = attachInfo.mCanvas; 14140 if (canvas == null) { 14141 canvas = new Canvas(); 14142 } 14143 canvas.setBitmap(bitmap); 14144 // Temporarily clobber the cached Canvas in case one of our children 14145 // is also using a drawing cache. Without this, the children would 14146 // steal the canvas by attaching their own bitmap to it and bad, bad 14147 // things would happen (invisible views, corrupted drawings, etc.) 14148 attachInfo.mCanvas = null; 14149 } else { 14150 // This case should hopefully never or seldom happen 14151 canvas = new Canvas(bitmap); 14152 } 14153 14154 if ((backgroundColor & 0xff000000) != 0) { 14155 bitmap.eraseColor(backgroundColor); 14156 } 14157 14158 computeScroll(); 14159 final int restoreCount = canvas.save(); 14160 canvas.scale(scale, scale); 14161 canvas.translate(-mScrollX, -mScrollY); 14162 14163 // Temporarily remove the dirty mask 14164 int flags = mPrivateFlags; 14165 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14166 14167 // Fast path for layouts with no backgrounds 14168 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14169 dispatchDraw(canvas); 14170 if (mOverlay != null && !mOverlay.isEmpty()) { 14171 mOverlay.getOverlayView().draw(canvas); 14172 } 14173 } else { 14174 draw(canvas); 14175 } 14176 14177 mPrivateFlags = flags; 14178 14179 canvas.restoreToCount(restoreCount); 14180 canvas.setBitmap(null); 14181 14182 if (attachInfo != null) { 14183 // Restore the cached Canvas for our siblings 14184 attachInfo.mCanvas = canvas; 14185 } 14186 14187 return bitmap; 14188 } 14189 14190 /** 14191 * Indicates whether this View is currently in edit mode. A View is usually 14192 * in edit mode when displayed within a developer tool. For instance, if 14193 * this View is being drawn by a visual user interface builder, this method 14194 * should return true. 14195 * 14196 * Subclasses should check the return value of this method to provide 14197 * different behaviors if their normal behavior might interfere with the 14198 * host environment. For instance: the class spawns a thread in its 14199 * constructor, the drawing code relies on device-specific features, etc. 14200 * 14201 * This method is usually checked in the drawing code of custom widgets. 14202 * 14203 * @return True if this View is in edit mode, false otherwise. 14204 */ 14205 public boolean isInEditMode() { 14206 return false; 14207 } 14208 14209 /** 14210 * If the View draws content inside its padding and enables fading edges, 14211 * it needs to support padding offsets. Padding offsets are added to the 14212 * fading edges to extend the length of the fade so that it covers pixels 14213 * drawn inside the padding. 14214 * 14215 * Subclasses of this class should override this method if they need 14216 * to draw content inside the padding. 14217 * 14218 * @return True if padding offset must be applied, false otherwise. 14219 * 14220 * @see #getLeftPaddingOffset() 14221 * @see #getRightPaddingOffset() 14222 * @see #getTopPaddingOffset() 14223 * @see #getBottomPaddingOffset() 14224 * 14225 * @since CURRENT 14226 */ 14227 protected boolean isPaddingOffsetRequired() { 14228 return false; 14229 } 14230 14231 /** 14232 * Amount by which to extend the left fading region. Called only when 14233 * {@link #isPaddingOffsetRequired()} returns true. 14234 * 14235 * @return The left padding offset in pixels. 14236 * 14237 * @see #isPaddingOffsetRequired() 14238 * 14239 * @since CURRENT 14240 */ 14241 protected int getLeftPaddingOffset() { 14242 return 0; 14243 } 14244 14245 /** 14246 * Amount by which to extend the right fading region. Called only when 14247 * {@link #isPaddingOffsetRequired()} returns true. 14248 * 14249 * @return The right padding offset in pixels. 14250 * 14251 * @see #isPaddingOffsetRequired() 14252 * 14253 * @since CURRENT 14254 */ 14255 protected int getRightPaddingOffset() { 14256 return 0; 14257 } 14258 14259 /** 14260 * Amount by which to extend the top fading region. Called only when 14261 * {@link #isPaddingOffsetRequired()} returns true. 14262 * 14263 * @return The top padding offset in pixels. 14264 * 14265 * @see #isPaddingOffsetRequired() 14266 * 14267 * @since CURRENT 14268 */ 14269 protected int getTopPaddingOffset() { 14270 return 0; 14271 } 14272 14273 /** 14274 * Amount by which to extend the bottom fading region. Called only when 14275 * {@link #isPaddingOffsetRequired()} returns true. 14276 * 14277 * @return The bottom padding offset in pixels. 14278 * 14279 * @see #isPaddingOffsetRequired() 14280 * 14281 * @since CURRENT 14282 */ 14283 protected int getBottomPaddingOffset() { 14284 return 0; 14285 } 14286 14287 /** 14288 * @hide 14289 * @param offsetRequired 14290 */ 14291 protected int getFadeTop(boolean offsetRequired) { 14292 int top = mPaddingTop; 14293 if (offsetRequired) top += getTopPaddingOffset(); 14294 return top; 14295 } 14296 14297 /** 14298 * @hide 14299 * @param offsetRequired 14300 */ 14301 protected int getFadeHeight(boolean offsetRequired) { 14302 int padding = mPaddingTop; 14303 if (offsetRequired) padding += getTopPaddingOffset(); 14304 return mBottom - mTop - mPaddingBottom - padding; 14305 } 14306 14307 /** 14308 * <p>Indicates whether this view is attached to a hardware accelerated 14309 * window or not.</p> 14310 * 14311 * <p>Even if this method returns true, it does not mean that every call 14312 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 14313 * accelerated {@link android.graphics.Canvas}. For instance, if this view 14314 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 14315 * window is hardware accelerated, 14316 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 14317 * return false, and this method will return true.</p> 14318 * 14319 * @return True if the view is attached to a window and the window is 14320 * hardware accelerated; false in any other case. 14321 */ 14322 public boolean isHardwareAccelerated() { 14323 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14324 } 14325 14326 /** 14327 * Sets a rectangular area on this view to which the view will be clipped 14328 * when it is drawn. Setting the value to null will remove the clip bounds 14329 * and the view will draw normally, using its full bounds. 14330 * 14331 * @param clipBounds The rectangular area, in the local coordinates of 14332 * this view, to which future drawing operations will be clipped. 14333 */ 14334 public void setClipBounds(Rect clipBounds) { 14335 if (clipBounds != null) { 14336 if (clipBounds.equals(mClipBounds)) { 14337 return; 14338 } 14339 if (mClipBounds == null) { 14340 invalidate(); 14341 mClipBounds = new Rect(clipBounds); 14342 } else { 14343 invalidate(Math.min(mClipBounds.left, clipBounds.left), 14344 Math.min(mClipBounds.top, clipBounds.top), 14345 Math.max(mClipBounds.right, clipBounds.right), 14346 Math.max(mClipBounds.bottom, clipBounds.bottom)); 14347 mClipBounds.set(clipBounds); 14348 } 14349 } else { 14350 if (mClipBounds != null) { 14351 invalidate(); 14352 mClipBounds = null; 14353 } 14354 } 14355 } 14356 14357 /** 14358 * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}. 14359 * 14360 * @return A copy of the current clip bounds if clip bounds are set, 14361 * otherwise null. 14362 */ 14363 public Rect getClipBounds() { 14364 return (mClipBounds != null) ? new Rect(mClipBounds) : null; 14365 } 14366 14367 /** 14368 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 14369 * case of an active Animation being run on the view. 14370 */ 14371 private boolean drawAnimation(ViewGroup parent, long drawingTime, 14372 Animation a, boolean scalingRequired) { 14373 Transformation invalidationTransform; 14374 final int flags = parent.mGroupFlags; 14375 final boolean initialized = a.isInitialized(); 14376 if (!initialized) { 14377 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 14378 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 14379 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 14380 onAnimationStart(); 14381 } 14382 14383 final Transformation t = parent.getChildTransformation(); 14384 boolean more = a.getTransformation(drawingTime, t, 1f); 14385 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 14386 if (parent.mInvalidationTransformation == null) { 14387 parent.mInvalidationTransformation = new Transformation(); 14388 } 14389 invalidationTransform = parent.mInvalidationTransformation; 14390 a.getTransformation(drawingTime, invalidationTransform, 1f); 14391 } else { 14392 invalidationTransform = t; 14393 } 14394 14395 if (more) { 14396 if (!a.willChangeBounds()) { 14397 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 14398 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 14399 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 14400 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 14401 // The child need to draw an animation, potentially offscreen, so 14402 // make sure we do not cancel invalidate requests 14403 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14404 parent.invalidate(mLeft, mTop, mRight, mBottom); 14405 } 14406 } else { 14407 if (parent.mInvalidateRegion == null) { 14408 parent.mInvalidateRegion = new RectF(); 14409 } 14410 final RectF region = parent.mInvalidateRegion; 14411 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 14412 invalidationTransform); 14413 14414 // The child need to draw an animation, potentially offscreen, so 14415 // make sure we do not cancel invalidate requests 14416 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14417 14418 final int left = mLeft + (int) region.left; 14419 final int top = mTop + (int) region.top; 14420 parent.invalidate(left, top, left + (int) (region.width() + .5f), 14421 top + (int) (region.height() + .5f)); 14422 } 14423 } 14424 return more; 14425 } 14426 14427 /** 14428 * This method is called by getDisplayList() when a display list is recorded for a View. 14429 * It pushes any properties to the RenderNode that aren't managed by the RenderNode. 14430 */ 14431 void setDisplayListProperties(RenderNode renderNode) { 14432 if (renderNode != null) { 14433 renderNode.setHasOverlappingRendering(hasOverlappingRendering()); 14434 if (mParent instanceof ViewGroup) { 14435 renderNode.setClipToBounds( 14436 (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0); 14437 } 14438 float alpha = 1; 14439 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 14440 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14441 ViewGroup parentVG = (ViewGroup) mParent; 14442 final Transformation t = parentVG.getChildTransformation(); 14443 if (parentVG.getChildStaticTransformation(this, t)) { 14444 final int transformType = t.getTransformationType(); 14445 if (transformType != Transformation.TYPE_IDENTITY) { 14446 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 14447 alpha = t.getAlpha(); 14448 } 14449 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 14450 renderNode.setStaticMatrix(t.getMatrix()); 14451 } 14452 } 14453 } 14454 } 14455 if (mTransformationInfo != null) { 14456 alpha *= getFinalAlpha(); 14457 if (alpha < 1) { 14458 final int multipliedAlpha = (int) (255 * alpha); 14459 if (onSetAlpha(multipliedAlpha)) { 14460 alpha = 1; 14461 } 14462 } 14463 renderNode.setAlpha(alpha); 14464 } else if (alpha < 1) { 14465 renderNode.setAlpha(alpha); 14466 } 14467 } 14468 } 14469 14470 /** 14471 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 14472 * This draw() method is an implementation detail and is not intended to be overridden or 14473 * to be called from anywhere else other than ViewGroup.drawChild(). 14474 */ 14475 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 14476 boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14477 boolean more = false; 14478 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 14479 final int flags = parent.mGroupFlags; 14480 14481 if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) { 14482 parent.getChildTransformation().clear(); 14483 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14484 } 14485 14486 Transformation transformToApply = null; 14487 boolean concatMatrix = false; 14488 14489 boolean scalingRequired = false; 14490 boolean caching; 14491 int layerType = getLayerType(); 14492 14493 final boolean hardwareAccelerated = canvas.isHardwareAccelerated(); 14494 if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 || 14495 (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) { 14496 caching = true; 14497 // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList 14498 if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired; 14499 } else { 14500 caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated; 14501 } 14502 14503 final Animation a = getAnimation(); 14504 if (a != null) { 14505 more = drawAnimation(parent, drawingTime, a, scalingRequired); 14506 concatMatrix = a.willChangeTransformationMatrix(); 14507 if (concatMatrix) { 14508 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14509 } 14510 transformToApply = parent.getChildTransformation(); 14511 } else { 14512 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) { 14513 // No longer animating: clear out old animation matrix 14514 mRenderNode.setAnimationMatrix(null); 14515 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14516 } 14517 if (!useDisplayListProperties && 14518 (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14519 final Transformation t = parent.getChildTransformation(); 14520 final boolean hasTransform = parent.getChildStaticTransformation(this, t); 14521 if (hasTransform) { 14522 final int transformType = t.getTransformationType(); 14523 transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null; 14524 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 14525 } 14526 } 14527 } 14528 14529 concatMatrix |= !childHasIdentityMatrix; 14530 14531 // Sets the flag as early as possible to allow draw() implementations 14532 // to call invalidate() successfully when doing animations 14533 mPrivateFlags |= PFLAG_DRAWN; 14534 14535 if (!concatMatrix && 14536 (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 14537 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 14538 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 14539 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 14540 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 14541 return more; 14542 } 14543 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 14544 14545 if (hardwareAccelerated) { 14546 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 14547 // retain the flag's value temporarily in the mRecreateDisplayList flag 14548 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED; 14549 mPrivateFlags &= ~PFLAG_INVALIDATED; 14550 } 14551 14552 RenderNode displayList = null; 14553 Bitmap cache = null; 14554 boolean hasDisplayList = false; 14555 if (caching) { 14556 if (!hardwareAccelerated) { 14557 if (layerType != LAYER_TYPE_NONE) { 14558 layerType = LAYER_TYPE_SOFTWARE; 14559 buildDrawingCache(true); 14560 } 14561 cache = getDrawingCache(true); 14562 } else { 14563 switch (layerType) { 14564 case LAYER_TYPE_SOFTWARE: 14565 if (useDisplayListProperties) { 14566 hasDisplayList = canHaveDisplayList(); 14567 } else { 14568 buildDrawingCache(true); 14569 cache = getDrawingCache(true); 14570 } 14571 break; 14572 case LAYER_TYPE_HARDWARE: 14573 if (useDisplayListProperties) { 14574 hasDisplayList = canHaveDisplayList(); 14575 } 14576 break; 14577 case LAYER_TYPE_NONE: 14578 // Delay getting the display list until animation-driven alpha values are 14579 // set up and possibly passed on to the view 14580 hasDisplayList = canHaveDisplayList(); 14581 break; 14582 } 14583 } 14584 } 14585 useDisplayListProperties &= hasDisplayList; 14586 if (useDisplayListProperties) { 14587 displayList = getDisplayList(); 14588 if (!displayList.isValid()) { 14589 // Uncommon, but possible. If a view is removed from the hierarchy during the call 14590 // to getDisplayList(), the display list will be marked invalid and we should not 14591 // try to use it again. 14592 displayList = null; 14593 hasDisplayList = false; 14594 useDisplayListProperties = false; 14595 } 14596 } 14597 14598 int sx = 0; 14599 int sy = 0; 14600 if (!hasDisplayList) { 14601 computeScroll(); 14602 sx = mScrollX; 14603 sy = mScrollY; 14604 } 14605 14606 final boolean hasNoCache = cache == null || hasDisplayList; 14607 final boolean offsetForScroll = cache == null && !hasDisplayList && 14608 layerType != LAYER_TYPE_HARDWARE; 14609 14610 int restoreTo = -1; 14611 if (!useDisplayListProperties || transformToApply != null) { 14612 restoreTo = canvas.save(); 14613 } 14614 if (offsetForScroll) { 14615 canvas.translate(mLeft - sx, mTop - sy); 14616 } else { 14617 if (!useDisplayListProperties) { 14618 canvas.translate(mLeft, mTop); 14619 } 14620 if (scalingRequired) { 14621 if (useDisplayListProperties) { 14622 // TODO: Might not need this if we put everything inside the DL 14623 restoreTo = canvas.save(); 14624 } 14625 // mAttachInfo cannot be null, otherwise scalingRequired == false 14626 final float scale = 1.0f / mAttachInfo.mApplicationScale; 14627 canvas.scale(scale, scale); 14628 } 14629 } 14630 14631 float alpha = useDisplayListProperties ? 1 : (getAlpha() * getTransitionAlpha()); 14632 if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() || 14633 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 14634 if (transformToApply != null || !childHasIdentityMatrix) { 14635 int transX = 0; 14636 int transY = 0; 14637 14638 if (offsetForScroll) { 14639 transX = -sx; 14640 transY = -sy; 14641 } 14642 14643 if (transformToApply != null) { 14644 if (concatMatrix) { 14645 if (useDisplayListProperties) { 14646 displayList.setAnimationMatrix(transformToApply.getMatrix()); 14647 } else { 14648 // Undo the scroll translation, apply the transformation matrix, 14649 // then redo the scroll translate to get the correct result. 14650 canvas.translate(-transX, -transY); 14651 canvas.concat(transformToApply.getMatrix()); 14652 canvas.translate(transX, transY); 14653 } 14654 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14655 } 14656 14657 float transformAlpha = transformToApply.getAlpha(); 14658 if (transformAlpha < 1) { 14659 alpha *= transformAlpha; 14660 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14661 } 14662 } 14663 14664 if (!childHasIdentityMatrix && !useDisplayListProperties) { 14665 canvas.translate(-transX, -transY); 14666 canvas.concat(getMatrix()); 14667 canvas.translate(transX, transY); 14668 } 14669 } 14670 14671 // Deal with alpha if it is or used to be <1 14672 if (alpha < 1 || 14673 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 14674 if (alpha < 1) { 14675 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 14676 } else { 14677 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 14678 } 14679 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14680 if (hasNoCache) { 14681 final int multipliedAlpha = (int) (255 * alpha); 14682 if (!onSetAlpha(multipliedAlpha)) { 14683 int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 14684 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 || 14685 layerType != LAYER_TYPE_NONE) { 14686 layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG; 14687 } 14688 if (useDisplayListProperties) { 14689 displayList.setAlpha(alpha * getAlpha() * getTransitionAlpha()); 14690 } else if (layerType == LAYER_TYPE_NONE) { 14691 final int scrollX = hasDisplayList ? 0 : sx; 14692 final int scrollY = hasDisplayList ? 0 : sy; 14693 canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft, 14694 scrollY + mBottom - mTop, multipliedAlpha, layerFlags); 14695 } 14696 } else { 14697 // Alpha is handled by the child directly, clobber the layer's alpha 14698 mPrivateFlags |= PFLAG_ALPHA_SET; 14699 } 14700 } 14701 } 14702 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 14703 onSetAlpha(255); 14704 mPrivateFlags &= ~PFLAG_ALPHA_SET; 14705 } 14706 14707 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN && 14708 !useDisplayListProperties && cache == null) { 14709 if (offsetForScroll) { 14710 canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop)); 14711 } else { 14712 if (!scalingRequired || cache == null) { 14713 canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop); 14714 } else { 14715 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 14716 } 14717 } 14718 } 14719 14720 if (!useDisplayListProperties && hasDisplayList) { 14721 displayList = getDisplayList(); 14722 if (!displayList.isValid()) { 14723 // Uncommon, but possible. If a view is removed from the hierarchy during the call 14724 // to getDisplayList(), the display list will be marked invalid and we should not 14725 // try to use it again. 14726 displayList = null; 14727 hasDisplayList = false; 14728 } 14729 } 14730 14731 if (hasNoCache) { 14732 boolean layerRendered = false; 14733 if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) { 14734 final HardwareLayer layer = getHardwareLayer(); 14735 if (layer != null && layer.isValid()) { 14736 mLayerPaint.setAlpha((int) (alpha * 255)); 14737 ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint); 14738 layerRendered = true; 14739 } else { 14740 final int scrollX = hasDisplayList ? 0 : sx; 14741 final int scrollY = hasDisplayList ? 0 : sy; 14742 canvas.saveLayer(scrollX, scrollY, 14743 scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint, 14744 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG); 14745 } 14746 } 14747 14748 if (!layerRendered) { 14749 if (!hasDisplayList) { 14750 // Fast path for layouts with no backgrounds 14751 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14752 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14753 dispatchDraw(canvas); 14754 } else { 14755 draw(canvas); 14756 } 14757 } else { 14758 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14759 ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags); 14760 } 14761 } 14762 } else if (cache != null) { 14763 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14764 Paint cachePaint; 14765 14766 if (layerType == LAYER_TYPE_NONE) { 14767 cachePaint = parent.mCachePaint; 14768 if (cachePaint == null) { 14769 cachePaint = new Paint(); 14770 cachePaint.setDither(false); 14771 parent.mCachePaint = cachePaint; 14772 } 14773 if (alpha < 1) { 14774 cachePaint.setAlpha((int) (alpha * 255)); 14775 parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 14776 } else if ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) { 14777 cachePaint.setAlpha(255); 14778 parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 14779 } 14780 } else { 14781 cachePaint = mLayerPaint; 14782 cachePaint.setAlpha((int) (alpha * 255)); 14783 } 14784 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 14785 } 14786 14787 if (restoreTo >= 0) { 14788 canvas.restoreToCount(restoreTo); 14789 } 14790 14791 if (a != null && !more) { 14792 if (!hardwareAccelerated && !a.getFillAfter()) { 14793 onSetAlpha(255); 14794 } 14795 parent.finishAnimatingView(this, a); 14796 } 14797 14798 if (more && hardwareAccelerated) { 14799 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 14800 // alpha animations should cause the child to recreate its display list 14801 invalidate(true); 14802 } 14803 } 14804 14805 mRecreateDisplayList = false; 14806 14807 return more; 14808 } 14809 14810 /** 14811 * Manually render this view (and all of its children) to the given Canvas. 14812 * The view must have already done a full layout before this function is 14813 * called. When implementing a view, implement 14814 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 14815 * If you do need to override this method, call the superclass version. 14816 * 14817 * @param canvas The Canvas to which the View is rendered. 14818 */ 14819 public void draw(Canvas canvas) { 14820 if (mClipBounds != null) { 14821 canvas.clipRect(mClipBounds); 14822 } 14823 final int privateFlags = mPrivateFlags; 14824 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 14825 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 14826 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 14827 14828 /* 14829 * Draw traversal performs several drawing steps which must be executed 14830 * in the appropriate order: 14831 * 14832 * 1. Draw the background 14833 * 2. If necessary, save the canvas' layers to prepare for fading 14834 * 3. Draw view's content 14835 * 4. Draw children 14836 * 5. If necessary, draw the fading edges and restore layers 14837 * 6. Draw decorations (scrollbars for instance) 14838 */ 14839 14840 // Step 1, draw the background, if needed 14841 int saveCount; 14842 14843 if (!dirtyOpaque) { 14844 drawBackground(canvas); 14845 } 14846 14847 // skip step 2 & 5 if possible (common case) 14848 final int viewFlags = mViewFlags; 14849 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 14850 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 14851 if (!verticalEdges && !horizontalEdges) { 14852 // Step 3, draw the content 14853 if (!dirtyOpaque) onDraw(canvas); 14854 14855 // Step 4, draw the children 14856 dispatchDraw(canvas); 14857 14858 // Step 6, draw decorations (scrollbars) 14859 onDrawScrollBars(canvas); 14860 14861 if (mOverlay != null && !mOverlay.isEmpty()) { 14862 mOverlay.getOverlayView().dispatchDraw(canvas); 14863 } 14864 14865 // we're done... 14866 return; 14867 } 14868 14869 /* 14870 * Here we do the full fledged routine... 14871 * (this is an uncommon case where speed matters less, 14872 * this is why we repeat some of the tests that have been 14873 * done above) 14874 */ 14875 14876 boolean drawTop = false; 14877 boolean drawBottom = false; 14878 boolean drawLeft = false; 14879 boolean drawRight = false; 14880 14881 float topFadeStrength = 0.0f; 14882 float bottomFadeStrength = 0.0f; 14883 float leftFadeStrength = 0.0f; 14884 float rightFadeStrength = 0.0f; 14885 14886 // Step 2, save the canvas' layers 14887 int paddingLeft = mPaddingLeft; 14888 14889 final boolean offsetRequired = isPaddingOffsetRequired(); 14890 if (offsetRequired) { 14891 paddingLeft += getLeftPaddingOffset(); 14892 } 14893 14894 int left = mScrollX + paddingLeft; 14895 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 14896 int top = mScrollY + getFadeTop(offsetRequired); 14897 int bottom = top + getFadeHeight(offsetRequired); 14898 14899 if (offsetRequired) { 14900 right += getRightPaddingOffset(); 14901 bottom += getBottomPaddingOffset(); 14902 } 14903 14904 final ScrollabilityCache scrollabilityCache = mScrollCache; 14905 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 14906 int length = (int) fadeHeight; 14907 14908 // clip the fade length if top and bottom fades overlap 14909 // overlapping fades produce odd-looking artifacts 14910 if (verticalEdges && (top + length > bottom - length)) { 14911 length = (bottom - top) / 2; 14912 } 14913 14914 // also clip horizontal fades if necessary 14915 if (horizontalEdges && (left + length > right - length)) { 14916 length = (right - left) / 2; 14917 } 14918 14919 if (verticalEdges) { 14920 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 14921 drawTop = topFadeStrength * fadeHeight > 1.0f; 14922 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 14923 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 14924 } 14925 14926 if (horizontalEdges) { 14927 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 14928 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 14929 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 14930 drawRight = rightFadeStrength * fadeHeight > 1.0f; 14931 } 14932 14933 saveCount = canvas.getSaveCount(); 14934 14935 int solidColor = getSolidColor(); 14936 if (solidColor == 0) { 14937 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 14938 14939 if (drawTop) { 14940 canvas.saveLayer(left, top, right, top + length, null, flags); 14941 } 14942 14943 if (drawBottom) { 14944 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 14945 } 14946 14947 if (drawLeft) { 14948 canvas.saveLayer(left, top, left + length, bottom, null, flags); 14949 } 14950 14951 if (drawRight) { 14952 canvas.saveLayer(right - length, top, right, bottom, null, flags); 14953 } 14954 } else { 14955 scrollabilityCache.setFadeColor(solidColor); 14956 } 14957 14958 // Step 3, draw the content 14959 if (!dirtyOpaque) onDraw(canvas); 14960 14961 // Step 4, draw the children 14962 dispatchDraw(canvas); 14963 14964 // Step 5, draw the fade effect and restore layers 14965 final Paint p = scrollabilityCache.paint; 14966 final Matrix matrix = scrollabilityCache.matrix; 14967 final Shader fade = scrollabilityCache.shader; 14968 14969 if (drawTop) { 14970 matrix.setScale(1, fadeHeight * topFadeStrength); 14971 matrix.postTranslate(left, top); 14972 fade.setLocalMatrix(matrix); 14973 canvas.drawRect(left, top, right, top + length, p); 14974 } 14975 14976 if (drawBottom) { 14977 matrix.setScale(1, fadeHeight * bottomFadeStrength); 14978 matrix.postRotate(180); 14979 matrix.postTranslate(left, bottom); 14980 fade.setLocalMatrix(matrix); 14981 canvas.drawRect(left, bottom - length, right, bottom, p); 14982 } 14983 14984 if (drawLeft) { 14985 matrix.setScale(1, fadeHeight * leftFadeStrength); 14986 matrix.postRotate(-90); 14987 matrix.postTranslate(left, top); 14988 fade.setLocalMatrix(matrix); 14989 canvas.drawRect(left, top, left + length, bottom, p); 14990 } 14991 14992 if (drawRight) { 14993 matrix.setScale(1, fadeHeight * rightFadeStrength); 14994 matrix.postRotate(90); 14995 matrix.postTranslate(right, top); 14996 fade.setLocalMatrix(matrix); 14997 canvas.drawRect(right - length, top, right, bottom, p); 14998 } 14999 15000 canvas.restoreToCount(saveCount); 15001 15002 // Step 6, draw decorations (scrollbars) 15003 onDrawScrollBars(canvas); 15004 15005 if (mOverlay != null && !mOverlay.isEmpty()) { 15006 mOverlay.getOverlayView().dispatchDraw(canvas); 15007 } 15008 } 15009 15010 /** 15011 * Draws the background onto the specified canvas. 15012 * 15013 * @param canvas Canvas on which to draw the background 15014 */ 15015 private void drawBackground(Canvas canvas) { 15016 final Drawable background = mBackground; 15017 if (background == null) { 15018 return; 15019 } 15020 15021 if (mBackgroundSizeChanged) { 15022 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 15023 mBackgroundSizeChanged = false; 15024 queryOutlineFromBackgroundIfUndefined(); 15025 } 15026 15027 // Attempt to use a display list if requested. 15028 if (canvas.isHardwareAccelerated() && mAttachInfo != null 15029 && mAttachInfo.mHardwareRenderer != null) { 15030 mBackgroundDisplayList = getDrawableDisplayList(background, mBackgroundDisplayList); 15031 15032 final RenderNode displayList = mBackgroundDisplayList; 15033 if (displayList != null && displayList.isValid()) { 15034 setBackgroundDisplayListProperties(displayList); 15035 ((HardwareCanvas) canvas).drawDisplayList(displayList); 15036 return; 15037 } 15038 } 15039 15040 final int scrollX = mScrollX; 15041 final int scrollY = mScrollY; 15042 if ((scrollX | scrollY) == 0) { 15043 background.draw(canvas); 15044 } else { 15045 canvas.translate(scrollX, scrollY); 15046 background.draw(canvas); 15047 canvas.translate(-scrollX, -scrollY); 15048 } 15049 } 15050 15051 /** 15052 * Set up background drawable display list properties. 15053 * 15054 * @param displayList Valid display list for the background drawable 15055 */ 15056 private void setBackgroundDisplayListProperties(RenderNode displayList) { 15057 displayList.setTranslationX(mScrollX); 15058 displayList.setTranslationY(mScrollY); 15059 } 15060 15061 /** 15062 * Creates a new display list or updates the existing display list for the 15063 * specified Drawable. 15064 * 15065 * @param drawable Drawable for which to create a display list 15066 * @param displayList Existing display list, or {@code null} 15067 * @return A valid display list for the specified drawable 15068 */ 15069 private RenderNode getDrawableDisplayList(Drawable drawable, RenderNode displayList) { 15070 if (displayList == null) { 15071 displayList = RenderNode.create(drawable.getClass().getName()); 15072 } 15073 15074 final Rect bounds = drawable.getBounds(); 15075 final int width = bounds.width(); 15076 final int height = bounds.height(); 15077 final HardwareCanvas canvas = displayList.start(width, height); 15078 try { 15079 drawable.draw(canvas); 15080 } finally { 15081 displayList.end(canvas); 15082 } 15083 15084 // Set up drawable properties that are view-independent. 15085 displayList.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom); 15086 displayList.setProjectBackwards(drawable.isProjected()); 15087 displayList.setProjectionReceiver(true); 15088 displayList.setClipToBounds(false); 15089 return displayList; 15090 } 15091 15092 /** 15093 * Returns the overlay for this view, creating it if it does not yet exist. 15094 * Adding drawables to the overlay will cause them to be displayed whenever 15095 * the view itself is redrawn. Objects in the overlay should be actively 15096 * managed: remove them when they should not be displayed anymore. The 15097 * overlay will always have the same size as its host view. 15098 * 15099 * <p>Note: Overlays do not currently work correctly with {@link 15100 * SurfaceView} or {@link TextureView}; contents in overlays for these 15101 * types of views may not display correctly.</p> 15102 * 15103 * @return The ViewOverlay object for this view. 15104 * @see ViewOverlay 15105 */ 15106 public ViewOverlay getOverlay() { 15107 if (mOverlay == null) { 15108 mOverlay = new ViewOverlay(mContext, this); 15109 } 15110 return mOverlay; 15111 } 15112 15113 /** 15114 * Override this if your view is known to always be drawn on top of a solid color background, 15115 * and needs to draw fading edges. Returning a non-zero color enables the view system to 15116 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 15117 * should be set to 0xFF. 15118 * 15119 * @see #setVerticalFadingEdgeEnabled(boolean) 15120 * @see #setHorizontalFadingEdgeEnabled(boolean) 15121 * 15122 * @return The known solid color background for this view, or 0 if the color may vary 15123 */ 15124 @ViewDebug.ExportedProperty(category = "drawing") 15125 public int getSolidColor() { 15126 return 0; 15127 } 15128 15129 /** 15130 * Build a human readable string representation of the specified view flags. 15131 * 15132 * @param flags the view flags to convert to a string 15133 * @return a String representing the supplied flags 15134 */ 15135 private static String printFlags(int flags) { 15136 String output = ""; 15137 int numFlags = 0; 15138 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 15139 output += "TAKES_FOCUS"; 15140 numFlags++; 15141 } 15142 15143 switch (flags & VISIBILITY_MASK) { 15144 case INVISIBLE: 15145 if (numFlags > 0) { 15146 output += " "; 15147 } 15148 output += "INVISIBLE"; 15149 // USELESS HERE numFlags++; 15150 break; 15151 case GONE: 15152 if (numFlags > 0) { 15153 output += " "; 15154 } 15155 output += "GONE"; 15156 // USELESS HERE numFlags++; 15157 break; 15158 default: 15159 break; 15160 } 15161 return output; 15162 } 15163 15164 /** 15165 * Build a human readable string representation of the specified private 15166 * view flags. 15167 * 15168 * @param privateFlags the private view flags to convert to a string 15169 * @return a String representing the supplied flags 15170 */ 15171 private static String printPrivateFlags(int privateFlags) { 15172 String output = ""; 15173 int numFlags = 0; 15174 15175 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 15176 output += "WANTS_FOCUS"; 15177 numFlags++; 15178 } 15179 15180 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 15181 if (numFlags > 0) { 15182 output += " "; 15183 } 15184 output += "FOCUSED"; 15185 numFlags++; 15186 } 15187 15188 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 15189 if (numFlags > 0) { 15190 output += " "; 15191 } 15192 output += "SELECTED"; 15193 numFlags++; 15194 } 15195 15196 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 15197 if (numFlags > 0) { 15198 output += " "; 15199 } 15200 output += "IS_ROOT_NAMESPACE"; 15201 numFlags++; 15202 } 15203 15204 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 15205 if (numFlags > 0) { 15206 output += " "; 15207 } 15208 output += "HAS_BOUNDS"; 15209 numFlags++; 15210 } 15211 15212 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 15213 if (numFlags > 0) { 15214 output += " "; 15215 } 15216 output += "DRAWN"; 15217 // USELESS HERE numFlags++; 15218 } 15219 return output; 15220 } 15221 15222 /** 15223 * <p>Indicates whether or not this view's layout will be requested during 15224 * the next hierarchy layout pass.</p> 15225 * 15226 * @return true if the layout will be forced during next layout pass 15227 */ 15228 public boolean isLayoutRequested() { 15229 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 15230 } 15231 15232 /** 15233 * Return true if o is a ViewGroup that is laying out using optical bounds. 15234 * @hide 15235 */ 15236 public static boolean isLayoutModeOptical(Object o) { 15237 return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical(); 15238 } 15239 15240 private boolean setOpticalFrame(int left, int top, int right, int bottom) { 15241 Insets parentInsets = mParent instanceof View ? 15242 ((View) mParent).getOpticalInsets() : Insets.NONE; 15243 Insets childInsets = getOpticalInsets(); 15244 return setFrame( 15245 left + parentInsets.left - childInsets.left, 15246 top + parentInsets.top - childInsets.top, 15247 right + parentInsets.left + childInsets.right, 15248 bottom + parentInsets.top + childInsets.bottom); 15249 } 15250 15251 /** 15252 * Assign a size and position to a view and all of its 15253 * descendants 15254 * 15255 * <p>This is the second phase of the layout mechanism. 15256 * (The first is measuring). In this phase, each parent calls 15257 * layout on all of its children to position them. 15258 * This is typically done using the child measurements 15259 * that were stored in the measure pass().</p> 15260 * 15261 * <p>Derived classes should not override this method. 15262 * Derived classes with children should override 15263 * onLayout. In that method, they should 15264 * call layout on each of their children.</p> 15265 * 15266 * @param l Left position, relative to parent 15267 * @param t Top position, relative to parent 15268 * @param r Right position, relative to parent 15269 * @param b Bottom position, relative to parent 15270 */ 15271 @SuppressWarnings({"unchecked"}) 15272 public void layout(int l, int t, int r, int b) { 15273 if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) { 15274 onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec); 15275 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 15276 } 15277 15278 int oldL = mLeft; 15279 int oldT = mTop; 15280 int oldB = mBottom; 15281 int oldR = mRight; 15282 15283 boolean changed = isLayoutModeOptical(mParent) ? 15284 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); 15285 15286 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 15287 onLayout(changed, l, t, r, b); 15288 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 15289 15290 ListenerInfo li = mListenerInfo; 15291 if (li != null && li.mOnLayoutChangeListeners != null) { 15292 ArrayList<OnLayoutChangeListener> listenersCopy = 15293 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 15294 int numListeners = listenersCopy.size(); 15295 for (int i = 0; i < numListeners; ++i) { 15296 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 15297 } 15298 } 15299 } 15300 15301 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 15302 mPrivateFlags3 |= PFLAG3_IS_LAID_OUT; 15303 } 15304 15305 /** 15306 * Called from layout when this view should 15307 * assign a size and position to each of its children. 15308 * 15309 * Derived classes with children should override 15310 * this method and call layout on each of 15311 * their children. 15312 * @param changed This is a new size or position for this view 15313 * @param left Left position, relative to parent 15314 * @param top Top position, relative to parent 15315 * @param right Right position, relative to parent 15316 * @param bottom Bottom position, relative to parent 15317 */ 15318 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 15319 } 15320 15321 /** 15322 * Assign a size and position to this view. 15323 * 15324 * This is called from layout. 15325 * 15326 * @param left Left position, relative to parent 15327 * @param top Top position, relative to parent 15328 * @param right Right position, relative to parent 15329 * @param bottom Bottom position, relative to parent 15330 * @return true if the new size and position are different than the 15331 * previous ones 15332 * {@hide} 15333 */ 15334 protected boolean setFrame(int left, int top, int right, int bottom) { 15335 boolean changed = false; 15336 15337 if (DBG) { 15338 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 15339 + right + "," + bottom + ")"); 15340 } 15341 15342 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 15343 changed = true; 15344 15345 // Remember our drawn bit 15346 int drawn = mPrivateFlags & PFLAG_DRAWN; 15347 15348 int oldWidth = mRight - mLeft; 15349 int oldHeight = mBottom - mTop; 15350 int newWidth = right - left; 15351 int newHeight = bottom - top; 15352 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 15353 15354 // Invalidate our old position 15355 invalidate(sizeChanged); 15356 15357 mLeft = left; 15358 mTop = top; 15359 mRight = right; 15360 mBottom = bottom; 15361 mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 15362 15363 mPrivateFlags |= PFLAG_HAS_BOUNDS; 15364 15365 15366 if (sizeChanged) { 15367 sizeChange(newWidth, newHeight, oldWidth, oldHeight); 15368 } 15369 15370 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 15371 // If we are visible, force the DRAWN bit to on so that 15372 // this invalidate will go through (at least to our parent). 15373 // This is because someone may have invalidated this view 15374 // before this call to setFrame came in, thereby clearing 15375 // the DRAWN bit. 15376 mPrivateFlags |= PFLAG_DRAWN; 15377 invalidate(sizeChanged); 15378 // parent display list may need to be recreated based on a change in the bounds 15379 // of any child 15380 invalidateParentCaches(); 15381 } 15382 15383 // Reset drawn bit to original value (invalidate turns it off) 15384 mPrivateFlags |= drawn; 15385 15386 mBackgroundSizeChanged = true; 15387 15388 notifySubtreeAccessibilityStateChangedIfNeeded(); 15389 } 15390 return changed; 15391 } 15392 15393 private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) { 15394 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 15395 if (mOverlay != null) { 15396 mOverlay.getOverlayView().setRight(newWidth); 15397 mOverlay.getOverlayView().setBottom(newHeight); 15398 } 15399 } 15400 15401 /** 15402 * Finalize inflating a view from XML. This is called as the last phase 15403 * of inflation, after all child views have been added. 15404 * 15405 * <p>Even if the subclass overrides onFinishInflate, they should always be 15406 * sure to call the super method, so that we get called. 15407 */ 15408 protected void onFinishInflate() { 15409 } 15410 15411 /** 15412 * Returns the resources associated with this view. 15413 * 15414 * @return Resources object. 15415 */ 15416 public Resources getResources() { 15417 return mResources; 15418 } 15419 15420 /** 15421 * Invalidates the specified Drawable. 15422 * 15423 * @param drawable the drawable to invalidate 15424 */ 15425 @Override 15426 public void invalidateDrawable(@NonNull Drawable drawable) { 15427 if (verifyDrawable(drawable)) { 15428 final Rect dirty = drawable.getDirtyBounds(); 15429 final int scrollX = mScrollX; 15430 final int scrollY = mScrollY; 15431 15432 invalidate(dirty.left + scrollX, dirty.top + scrollY, 15433 dirty.right + scrollX, dirty.bottom + scrollY); 15434 15435 if (drawable == mBackground) { 15436 queryOutlineFromBackgroundIfUndefined(); 15437 } 15438 } 15439 } 15440 15441 /** 15442 * Schedules an action on a drawable to occur at a specified time. 15443 * 15444 * @param who the recipient of the action 15445 * @param what the action to run on the drawable 15446 * @param when the time at which the action must occur. Uses the 15447 * {@link SystemClock#uptimeMillis} timebase. 15448 */ 15449 @Override 15450 public void scheduleDrawable(Drawable who, Runnable what, long when) { 15451 if (verifyDrawable(who) && what != null) { 15452 final long delay = when - SystemClock.uptimeMillis(); 15453 if (mAttachInfo != null) { 15454 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 15455 Choreographer.CALLBACK_ANIMATION, what, who, 15456 Choreographer.subtractFrameDelay(delay)); 15457 } else { 15458 ViewRootImpl.getRunQueue().postDelayed(what, delay); 15459 } 15460 } 15461 } 15462 15463 /** 15464 * Cancels a scheduled action on a drawable. 15465 * 15466 * @param who the recipient of the action 15467 * @param what the action to cancel 15468 */ 15469 @Override 15470 public void unscheduleDrawable(Drawable who, Runnable what) { 15471 if (verifyDrawable(who) && what != null) { 15472 if (mAttachInfo != null) { 15473 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15474 Choreographer.CALLBACK_ANIMATION, what, who); 15475 } 15476 ViewRootImpl.getRunQueue().removeCallbacks(what); 15477 } 15478 } 15479 15480 /** 15481 * Unschedule any events associated with the given Drawable. This can be 15482 * used when selecting a new Drawable into a view, so that the previous 15483 * one is completely unscheduled. 15484 * 15485 * @param who The Drawable to unschedule. 15486 * 15487 * @see #drawableStateChanged 15488 */ 15489 public void unscheduleDrawable(Drawable who) { 15490 if (mAttachInfo != null && who != null) { 15491 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15492 Choreographer.CALLBACK_ANIMATION, null, who); 15493 } 15494 } 15495 15496 /** 15497 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 15498 * that the View directionality can and will be resolved before its Drawables. 15499 * 15500 * Will call {@link View#onResolveDrawables} when resolution is done. 15501 * 15502 * @hide 15503 */ 15504 protected void resolveDrawables() { 15505 // Drawables resolution may need to happen before resolving the layout direction (which is 15506 // done only during the measure() call). 15507 // If the layout direction is not resolved yet, we cannot resolve the Drawables except in 15508 // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT. 15509 // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or 15510 // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout 15511 // direction to be resolved as its resolved value will be the same as its raw value. 15512 if (!isLayoutDirectionResolved() && 15513 getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) { 15514 return; 15515 } 15516 15517 final int layoutDirection = isLayoutDirectionResolved() ? 15518 getLayoutDirection() : getRawLayoutDirection(); 15519 15520 if (mBackground != null) { 15521 mBackground.setLayoutDirection(layoutDirection); 15522 } 15523 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED; 15524 onResolveDrawables(layoutDirection); 15525 } 15526 15527 /** 15528 * Called when layout direction has been resolved. 15529 * 15530 * The default implementation does nothing. 15531 * 15532 * @param layoutDirection The resolved layout direction. 15533 * 15534 * @see #LAYOUT_DIRECTION_LTR 15535 * @see #LAYOUT_DIRECTION_RTL 15536 * 15537 * @hide 15538 */ 15539 public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) { 15540 } 15541 15542 /** 15543 * @hide 15544 */ 15545 protected void resetResolvedDrawables() { 15546 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED; 15547 } 15548 15549 private boolean isDrawablesResolved() { 15550 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED; 15551 } 15552 15553 /** 15554 * If your view subclass is displaying its own Drawable objects, it should 15555 * override this function and return true for any Drawable it is 15556 * displaying. This allows animations for those drawables to be 15557 * scheduled. 15558 * 15559 * <p>Be sure to call through to the super class when overriding this 15560 * function. 15561 * 15562 * @param who The Drawable to verify. Return true if it is one you are 15563 * displaying, else return the result of calling through to the 15564 * super class. 15565 * 15566 * @return boolean If true than the Drawable is being displayed in the 15567 * view; else false and it is not allowed to animate. 15568 * 15569 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 15570 * @see #drawableStateChanged() 15571 */ 15572 protected boolean verifyDrawable(Drawable who) { 15573 return who == mBackground; 15574 } 15575 15576 /** 15577 * This function is called whenever the state of the view changes in such 15578 * a way that it impacts the state of drawables being shown. 15579 * <p> 15580 * If the View has a StateListAnimator, it will also be called to run necessary state 15581 * change animations. 15582 * <p> 15583 * Be sure to call through to the superclass when overriding this function. 15584 * 15585 * @see Drawable#setState(int[]) 15586 */ 15587 protected void drawableStateChanged() { 15588 final Drawable d = mBackground; 15589 if (d != null && d.isStateful()) { 15590 d.setState(getDrawableState()); 15591 } 15592 15593 if (mStateListAnimator != null) { 15594 mStateListAnimator.setState(getDrawableState()); 15595 } 15596 } 15597 15598 /** 15599 * Call this to force a view to update its drawable state. This will cause 15600 * drawableStateChanged to be called on this view. Views that are interested 15601 * in the new state should call getDrawableState. 15602 * 15603 * @see #drawableStateChanged 15604 * @see #getDrawableState 15605 */ 15606 public void refreshDrawableState() { 15607 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 15608 drawableStateChanged(); 15609 15610 ViewParent parent = mParent; 15611 if (parent != null) { 15612 parent.childDrawableStateChanged(this); 15613 } 15614 } 15615 15616 /** 15617 * Return an array of resource IDs of the drawable states representing the 15618 * current state of the view. 15619 * 15620 * @return The current drawable state 15621 * 15622 * @see Drawable#setState(int[]) 15623 * @see #drawableStateChanged() 15624 * @see #onCreateDrawableState(int) 15625 */ 15626 public final int[] getDrawableState() { 15627 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 15628 return mDrawableState; 15629 } else { 15630 mDrawableState = onCreateDrawableState(0); 15631 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 15632 return mDrawableState; 15633 } 15634 } 15635 15636 /** 15637 * Generate the new {@link android.graphics.drawable.Drawable} state for 15638 * this view. This is called by the view 15639 * system when the cached Drawable state is determined to be invalid. To 15640 * retrieve the current state, you should use {@link #getDrawableState}. 15641 * 15642 * @param extraSpace if non-zero, this is the number of extra entries you 15643 * would like in the returned array in which you can place your own 15644 * states. 15645 * 15646 * @return Returns an array holding the current {@link Drawable} state of 15647 * the view. 15648 * 15649 * @see #mergeDrawableStates(int[], int[]) 15650 */ 15651 protected int[] onCreateDrawableState(int extraSpace) { 15652 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 15653 mParent instanceof View) { 15654 return ((View) mParent).onCreateDrawableState(extraSpace); 15655 } 15656 15657 int[] drawableState; 15658 15659 int privateFlags = mPrivateFlags; 15660 15661 int viewStateIndex = 0; 15662 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 15663 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 15664 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 15665 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 15666 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 15667 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 15668 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 15669 HardwareRenderer.isAvailable()) { 15670 // This is set if HW acceleration is requested, even if the current 15671 // process doesn't allow it. This is just to allow app preview 15672 // windows to better match their app. 15673 viewStateIndex |= VIEW_STATE_ACCELERATED; 15674 } 15675 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 15676 15677 final int privateFlags2 = mPrivateFlags2; 15678 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 15679 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 15680 15681 drawableState = VIEW_STATE_SETS[viewStateIndex]; 15682 15683 //noinspection ConstantIfStatement 15684 if (false) { 15685 Log.i("View", "drawableStateIndex=" + viewStateIndex); 15686 Log.i("View", toString() 15687 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 15688 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 15689 + " fo=" + hasFocus() 15690 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 15691 + " wf=" + hasWindowFocus() 15692 + ": " + Arrays.toString(drawableState)); 15693 } 15694 15695 if (extraSpace == 0) { 15696 return drawableState; 15697 } 15698 15699 final int[] fullState; 15700 if (drawableState != null) { 15701 fullState = new int[drawableState.length + extraSpace]; 15702 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 15703 } else { 15704 fullState = new int[extraSpace]; 15705 } 15706 15707 return fullState; 15708 } 15709 15710 /** 15711 * Merge your own state values in <var>additionalState</var> into the base 15712 * state values <var>baseState</var> that were returned by 15713 * {@link #onCreateDrawableState(int)}. 15714 * 15715 * @param baseState The base state values returned by 15716 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 15717 * own additional state values. 15718 * 15719 * @param additionalState The additional state values you would like 15720 * added to <var>baseState</var>; this array is not modified. 15721 * 15722 * @return As a convenience, the <var>baseState</var> array you originally 15723 * passed into the function is returned. 15724 * 15725 * @see #onCreateDrawableState(int) 15726 */ 15727 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 15728 final int N = baseState.length; 15729 int i = N - 1; 15730 while (i >= 0 && baseState[i] == 0) { 15731 i--; 15732 } 15733 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 15734 return baseState; 15735 } 15736 15737 /** 15738 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 15739 * on all Drawable objects associated with this view. 15740 * <p> 15741 * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator 15742 * attached to this view. 15743 */ 15744 public void jumpDrawablesToCurrentState() { 15745 if (mBackground != null) { 15746 mBackground.jumpToCurrentState(); 15747 } 15748 if (mStateListAnimator != null) { 15749 mStateListAnimator.jumpToCurrentState(); 15750 } 15751 } 15752 15753 /** 15754 * Sets the background color for this view. 15755 * @param color the color of the background 15756 */ 15757 @RemotableViewMethod 15758 public void setBackgroundColor(int color) { 15759 if (mBackground instanceof ColorDrawable) { 15760 ((ColorDrawable) mBackground.mutate()).setColor(color); 15761 computeOpaqueFlags(); 15762 mBackgroundResource = 0; 15763 } else { 15764 setBackground(new ColorDrawable(color)); 15765 } 15766 } 15767 15768 /** 15769 * Set the background to a given resource. The resource should refer to 15770 * a Drawable object or 0 to remove the background. 15771 * @param resid The identifier of the resource. 15772 * 15773 * @attr ref android.R.styleable#View_background 15774 */ 15775 @RemotableViewMethod 15776 public void setBackgroundResource(int resid) { 15777 if (resid != 0 && resid == mBackgroundResource) { 15778 return; 15779 } 15780 15781 Drawable d= null; 15782 if (resid != 0) { 15783 d = mContext.getDrawable(resid); 15784 } 15785 setBackground(d); 15786 15787 mBackgroundResource = resid; 15788 } 15789 15790 /** 15791 * Set the background to a given Drawable, or remove the background. If the 15792 * background has padding, this View's padding is set to the background's 15793 * padding. However, when a background is removed, this View's padding isn't 15794 * touched. If setting the padding is desired, please use 15795 * {@link #setPadding(int, int, int, int)}. 15796 * 15797 * @param background The Drawable to use as the background, or null to remove the 15798 * background 15799 */ 15800 public void setBackground(Drawable background) { 15801 //noinspection deprecation 15802 setBackgroundDrawable(background); 15803 } 15804 15805 /** 15806 * @deprecated use {@link #setBackground(Drawable)} instead 15807 */ 15808 @Deprecated 15809 public void setBackgroundDrawable(Drawable background) { 15810 computeOpaqueFlags(); 15811 15812 if (background == mBackground) { 15813 return; 15814 } 15815 15816 boolean requestLayout = false; 15817 15818 mBackgroundResource = 0; 15819 15820 /* 15821 * Regardless of whether we're setting a new background or not, we want 15822 * to clear the previous drawable. 15823 */ 15824 if (mBackground != null) { 15825 mBackground.setCallback(null); 15826 unscheduleDrawable(mBackground); 15827 } 15828 15829 if (background != null) { 15830 Rect padding = sThreadLocal.get(); 15831 if (padding == null) { 15832 padding = new Rect(); 15833 sThreadLocal.set(padding); 15834 } 15835 resetResolvedDrawables(); 15836 background.setLayoutDirection(getLayoutDirection()); 15837 if (background.getPadding(padding)) { 15838 resetResolvedPadding(); 15839 switch (background.getLayoutDirection()) { 15840 case LAYOUT_DIRECTION_RTL: 15841 mUserPaddingLeftInitial = padding.right; 15842 mUserPaddingRightInitial = padding.left; 15843 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 15844 break; 15845 case LAYOUT_DIRECTION_LTR: 15846 default: 15847 mUserPaddingLeftInitial = padding.left; 15848 mUserPaddingRightInitial = padding.right; 15849 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 15850 } 15851 mLeftPaddingDefined = false; 15852 mRightPaddingDefined = false; 15853 } 15854 15855 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 15856 // if it has a different minimum size, we should layout again 15857 if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() || 15858 mBackground.getMinimumWidth() != background.getMinimumWidth()) { 15859 requestLayout = true; 15860 } 15861 15862 background.setCallback(this); 15863 if (background.isStateful()) { 15864 background.setState(getDrawableState()); 15865 } 15866 background.setVisible(getVisibility() == VISIBLE, false); 15867 mBackground = background; 15868 15869 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 15870 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 15871 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 15872 requestLayout = true; 15873 } 15874 } else { 15875 /* Remove the background */ 15876 mBackground = null; 15877 15878 if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) { 15879 /* 15880 * This view ONLY drew the background before and we're removing 15881 * the background, so now it won't draw anything 15882 * (hence we SKIP_DRAW) 15883 */ 15884 mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND; 15885 mPrivateFlags |= PFLAG_SKIP_DRAW; 15886 } 15887 15888 /* 15889 * When the background is set, we try to apply its padding to this 15890 * View. When the background is removed, we don't touch this View's 15891 * padding. This is noted in the Javadocs. Hence, we don't need to 15892 * requestLayout(), the invalidate() below is sufficient. 15893 */ 15894 15895 // The old background's minimum size could have affected this 15896 // View's layout, so let's requestLayout 15897 requestLayout = true; 15898 } 15899 15900 computeOpaqueFlags(); 15901 15902 if (requestLayout) { 15903 requestLayout(); 15904 } 15905 15906 mBackgroundSizeChanged = true; 15907 invalidate(true); 15908 } 15909 15910 /** 15911 * Gets the background drawable 15912 * 15913 * @return The drawable used as the background for this view, if any. 15914 * 15915 * @see #setBackground(Drawable) 15916 * 15917 * @attr ref android.R.styleable#View_background 15918 */ 15919 public Drawable getBackground() { 15920 return mBackground; 15921 } 15922 15923 /** 15924 * Sets the padding. The view may add on the space required to display 15925 * the scrollbars, depending on the style and visibility of the scrollbars. 15926 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 15927 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 15928 * from the values set in this call. 15929 * 15930 * @attr ref android.R.styleable#View_padding 15931 * @attr ref android.R.styleable#View_paddingBottom 15932 * @attr ref android.R.styleable#View_paddingLeft 15933 * @attr ref android.R.styleable#View_paddingRight 15934 * @attr ref android.R.styleable#View_paddingTop 15935 * @param left the left padding in pixels 15936 * @param top the top padding in pixels 15937 * @param right the right padding in pixels 15938 * @param bottom the bottom padding in pixels 15939 */ 15940 public void setPadding(int left, int top, int right, int bottom) { 15941 resetResolvedPadding(); 15942 15943 mUserPaddingStart = UNDEFINED_PADDING; 15944 mUserPaddingEnd = UNDEFINED_PADDING; 15945 15946 mUserPaddingLeftInitial = left; 15947 mUserPaddingRightInitial = right; 15948 15949 mLeftPaddingDefined = true; 15950 mRightPaddingDefined = true; 15951 15952 internalSetPadding(left, top, right, bottom); 15953 } 15954 15955 /** 15956 * @hide 15957 */ 15958 protected void internalSetPadding(int left, int top, int right, int bottom) { 15959 mUserPaddingLeft = left; 15960 mUserPaddingRight = right; 15961 mUserPaddingBottom = bottom; 15962 15963 final int viewFlags = mViewFlags; 15964 boolean changed = false; 15965 15966 // Common case is there are no scroll bars. 15967 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 15968 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 15969 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 15970 ? 0 : getVerticalScrollbarWidth(); 15971 switch (mVerticalScrollbarPosition) { 15972 case SCROLLBAR_POSITION_DEFAULT: 15973 if (isLayoutRtl()) { 15974 left += offset; 15975 } else { 15976 right += offset; 15977 } 15978 break; 15979 case SCROLLBAR_POSITION_RIGHT: 15980 right += offset; 15981 break; 15982 case SCROLLBAR_POSITION_LEFT: 15983 left += offset; 15984 break; 15985 } 15986 } 15987 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 15988 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 15989 ? 0 : getHorizontalScrollbarHeight(); 15990 } 15991 } 15992 15993 if (mPaddingLeft != left) { 15994 changed = true; 15995 mPaddingLeft = left; 15996 } 15997 if (mPaddingTop != top) { 15998 changed = true; 15999 mPaddingTop = top; 16000 } 16001 if (mPaddingRight != right) { 16002 changed = true; 16003 mPaddingRight = right; 16004 } 16005 if (mPaddingBottom != bottom) { 16006 changed = true; 16007 mPaddingBottom = bottom; 16008 } 16009 16010 if (changed) { 16011 requestLayout(); 16012 } 16013 } 16014 16015 /** 16016 * Sets the relative padding. The view may add on the space required to display 16017 * the scrollbars, depending on the style and visibility of the scrollbars. 16018 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 16019 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 16020 * from the values set in this call. 16021 * 16022 * @attr ref android.R.styleable#View_padding 16023 * @attr ref android.R.styleable#View_paddingBottom 16024 * @attr ref android.R.styleable#View_paddingStart 16025 * @attr ref android.R.styleable#View_paddingEnd 16026 * @attr ref android.R.styleable#View_paddingTop 16027 * @param start the start padding in pixels 16028 * @param top the top padding in pixels 16029 * @param end the end padding in pixels 16030 * @param bottom the bottom padding in pixels 16031 */ 16032 public void setPaddingRelative(int start, int top, int end, int bottom) { 16033 resetResolvedPadding(); 16034 16035 mUserPaddingStart = start; 16036 mUserPaddingEnd = end; 16037 mLeftPaddingDefined = true; 16038 mRightPaddingDefined = true; 16039 16040 switch(getLayoutDirection()) { 16041 case LAYOUT_DIRECTION_RTL: 16042 mUserPaddingLeftInitial = end; 16043 mUserPaddingRightInitial = start; 16044 internalSetPadding(end, top, start, bottom); 16045 break; 16046 case LAYOUT_DIRECTION_LTR: 16047 default: 16048 mUserPaddingLeftInitial = start; 16049 mUserPaddingRightInitial = end; 16050 internalSetPadding(start, top, end, bottom); 16051 } 16052 } 16053 16054 /** 16055 * Returns the top padding of this view. 16056 * 16057 * @return the top padding in pixels 16058 */ 16059 public int getPaddingTop() { 16060 return mPaddingTop; 16061 } 16062 16063 /** 16064 * Returns the bottom padding of this view. If there are inset and enabled 16065 * scrollbars, this value may include the space required to display the 16066 * scrollbars as well. 16067 * 16068 * @return the bottom padding in pixels 16069 */ 16070 public int getPaddingBottom() { 16071 return mPaddingBottom; 16072 } 16073 16074 /** 16075 * Returns the left padding of this view. If there are inset and enabled 16076 * scrollbars, this value may include the space required to display the 16077 * scrollbars as well. 16078 * 16079 * @return the left padding in pixels 16080 */ 16081 public int getPaddingLeft() { 16082 if (!isPaddingResolved()) { 16083 resolvePadding(); 16084 } 16085 return mPaddingLeft; 16086 } 16087 16088 /** 16089 * Returns the start padding of this view depending on its resolved layout direction. 16090 * If there are inset and enabled scrollbars, this value may include the space 16091 * required to display the scrollbars as well. 16092 * 16093 * @return the start padding in pixels 16094 */ 16095 public int getPaddingStart() { 16096 if (!isPaddingResolved()) { 16097 resolvePadding(); 16098 } 16099 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 16100 mPaddingRight : mPaddingLeft; 16101 } 16102 16103 /** 16104 * Returns the right padding of this view. If there are inset and enabled 16105 * scrollbars, this value may include the space required to display the 16106 * scrollbars as well. 16107 * 16108 * @return the right padding in pixels 16109 */ 16110 public int getPaddingRight() { 16111 if (!isPaddingResolved()) { 16112 resolvePadding(); 16113 } 16114 return mPaddingRight; 16115 } 16116 16117 /** 16118 * Returns the end padding of this view depending on its resolved layout direction. 16119 * If there are inset and enabled scrollbars, this value may include the space 16120 * required to display the scrollbars as well. 16121 * 16122 * @return the end padding in pixels 16123 */ 16124 public int getPaddingEnd() { 16125 if (!isPaddingResolved()) { 16126 resolvePadding(); 16127 } 16128 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 16129 mPaddingLeft : mPaddingRight; 16130 } 16131 16132 /** 16133 * Return if the padding as been set thru relative values 16134 * {@link #setPaddingRelative(int, int, int, int)} or thru 16135 * @attr ref android.R.styleable#View_paddingStart or 16136 * @attr ref android.R.styleable#View_paddingEnd 16137 * 16138 * @return true if the padding is relative or false if it is not. 16139 */ 16140 public boolean isPaddingRelative() { 16141 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 16142 } 16143 16144 Insets computeOpticalInsets() { 16145 return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets(); 16146 } 16147 16148 /** 16149 * @hide 16150 */ 16151 public void resetPaddingToInitialValues() { 16152 if (isRtlCompatibilityMode()) { 16153 mPaddingLeft = mUserPaddingLeftInitial; 16154 mPaddingRight = mUserPaddingRightInitial; 16155 return; 16156 } 16157 if (isLayoutRtl()) { 16158 mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial; 16159 mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial; 16160 } else { 16161 mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial; 16162 mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial; 16163 } 16164 } 16165 16166 /** 16167 * @hide 16168 */ 16169 public Insets getOpticalInsets() { 16170 if (mLayoutInsets == null) { 16171 mLayoutInsets = computeOpticalInsets(); 16172 } 16173 return mLayoutInsets; 16174 } 16175 16176 /** 16177 * Set this view's optical insets. 16178 * 16179 * <p>This method should be treated similarly to setMeasuredDimension and not as a general 16180 * property. Views that compute their own optical insets should call it as part of measurement. 16181 * This method does not request layout. If you are setting optical insets outside of 16182 * measure/layout itself you will want to call requestLayout() yourself. 16183 * </p> 16184 * @hide 16185 */ 16186 public void setOpticalInsets(Insets insets) { 16187 mLayoutInsets = insets; 16188 } 16189 16190 /** 16191 * Changes the selection state of this view. A view can be selected or not. 16192 * Note that selection is not the same as focus. Views are typically 16193 * selected in the context of an AdapterView like ListView or GridView; 16194 * the selected view is the view that is highlighted. 16195 * 16196 * @param selected true if the view must be selected, false otherwise 16197 */ 16198 public void setSelected(boolean selected) { 16199 //noinspection DoubleNegation 16200 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 16201 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 16202 if (!selected) resetPressedState(); 16203 invalidate(true); 16204 refreshDrawableState(); 16205 dispatchSetSelected(selected); 16206 notifyViewAccessibilityStateChangedIfNeeded( 16207 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 16208 } 16209 } 16210 16211 /** 16212 * Dispatch setSelected to all of this View's children. 16213 * 16214 * @see #setSelected(boolean) 16215 * 16216 * @param selected The new selected state 16217 */ 16218 protected void dispatchSetSelected(boolean selected) { 16219 } 16220 16221 /** 16222 * Indicates the selection state of this view. 16223 * 16224 * @return true if the view is selected, false otherwise 16225 */ 16226 @ViewDebug.ExportedProperty 16227 public boolean isSelected() { 16228 return (mPrivateFlags & PFLAG_SELECTED) != 0; 16229 } 16230 16231 /** 16232 * Changes the activated state of this view. A view can be activated or not. 16233 * Note that activation is not the same as selection. Selection is 16234 * a transient property, representing the view (hierarchy) the user is 16235 * currently interacting with. Activation is a longer-term state that the 16236 * user can move views in and out of. For example, in a list view with 16237 * single or multiple selection enabled, the views in the current selection 16238 * set are activated. (Um, yeah, we are deeply sorry about the terminology 16239 * here.) The activated state is propagated down to children of the view it 16240 * is set on. 16241 * 16242 * @param activated true if the view must be activated, false otherwise 16243 */ 16244 public void setActivated(boolean activated) { 16245 //noinspection DoubleNegation 16246 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 16247 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 16248 invalidate(true); 16249 refreshDrawableState(); 16250 dispatchSetActivated(activated); 16251 } 16252 } 16253 16254 /** 16255 * Dispatch setActivated to all of this View's children. 16256 * 16257 * @see #setActivated(boolean) 16258 * 16259 * @param activated The new activated state 16260 */ 16261 protected void dispatchSetActivated(boolean activated) { 16262 } 16263 16264 /** 16265 * Indicates the activation state of this view. 16266 * 16267 * @return true if the view is activated, false otherwise 16268 */ 16269 @ViewDebug.ExportedProperty 16270 public boolean isActivated() { 16271 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 16272 } 16273 16274 /** 16275 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 16276 * observer can be used to get notifications when global events, like 16277 * layout, happen. 16278 * 16279 * The returned ViewTreeObserver observer is not guaranteed to remain 16280 * valid for the lifetime of this View. If the caller of this method keeps 16281 * a long-lived reference to ViewTreeObserver, it should always check for 16282 * the return value of {@link ViewTreeObserver#isAlive()}. 16283 * 16284 * @return The ViewTreeObserver for this view's hierarchy. 16285 */ 16286 public ViewTreeObserver getViewTreeObserver() { 16287 if (mAttachInfo != null) { 16288 return mAttachInfo.mTreeObserver; 16289 } 16290 if (mFloatingTreeObserver == null) { 16291 mFloatingTreeObserver = new ViewTreeObserver(); 16292 } 16293 return mFloatingTreeObserver; 16294 } 16295 16296 /** 16297 * <p>Finds the topmost view in the current view hierarchy.</p> 16298 * 16299 * @return the topmost view containing this view 16300 */ 16301 public View getRootView() { 16302 if (mAttachInfo != null) { 16303 final View v = mAttachInfo.mRootView; 16304 if (v != null) { 16305 return v; 16306 } 16307 } 16308 16309 View parent = this; 16310 16311 while (parent.mParent != null && parent.mParent instanceof View) { 16312 parent = (View) parent.mParent; 16313 } 16314 16315 return parent; 16316 } 16317 16318 /** 16319 * Transforms a motion event from view-local coordinates to on-screen 16320 * coordinates. 16321 * 16322 * @param ev the view-local motion event 16323 * @return false if the transformation could not be applied 16324 * @hide 16325 */ 16326 public boolean toGlobalMotionEvent(MotionEvent ev) { 16327 final AttachInfo info = mAttachInfo; 16328 if (info == null) { 16329 return false; 16330 } 16331 16332 final Matrix m = info.mTmpMatrix; 16333 m.set(Matrix.IDENTITY_MATRIX); 16334 transformMatrixToGlobal(m); 16335 ev.transform(m); 16336 return true; 16337 } 16338 16339 /** 16340 * Transforms a motion event from on-screen coordinates to view-local 16341 * coordinates. 16342 * 16343 * @param ev the on-screen motion event 16344 * @return false if the transformation could not be applied 16345 * @hide 16346 */ 16347 public boolean toLocalMotionEvent(MotionEvent ev) { 16348 final AttachInfo info = mAttachInfo; 16349 if (info == null) { 16350 return false; 16351 } 16352 16353 final Matrix m = info.mTmpMatrix; 16354 m.set(Matrix.IDENTITY_MATRIX); 16355 transformMatrixToLocal(m); 16356 ev.transform(m); 16357 return true; 16358 } 16359 16360 /** 16361 * Modifies the input matrix such that it maps view-local coordinates to 16362 * on-screen coordinates. 16363 * 16364 * @param m input matrix to modify 16365 */ 16366 void transformMatrixToGlobal(Matrix m) { 16367 final ViewParent parent = mParent; 16368 if (parent instanceof View) { 16369 final View vp = (View) parent; 16370 vp.transformMatrixToGlobal(m); 16371 m.postTranslate(-vp.mScrollX, -vp.mScrollY); 16372 } else if (parent instanceof ViewRootImpl) { 16373 final ViewRootImpl vr = (ViewRootImpl) parent; 16374 vr.transformMatrixToGlobal(m); 16375 m.postTranslate(0, -vr.mCurScrollY); 16376 } 16377 16378 m.postTranslate(mLeft, mTop); 16379 16380 if (!hasIdentityMatrix()) { 16381 m.postConcat(getMatrix()); 16382 } 16383 } 16384 16385 /** 16386 * Modifies the input matrix such that it maps on-screen coordinates to 16387 * view-local coordinates. 16388 * 16389 * @param m input matrix to modify 16390 */ 16391 void transformMatrixToLocal(Matrix m) { 16392 final ViewParent parent = mParent; 16393 if (parent instanceof View) { 16394 final View vp = (View) parent; 16395 vp.transformMatrixToLocal(m); 16396 m.preTranslate(vp.mScrollX, vp.mScrollY); 16397 } else if (parent instanceof ViewRootImpl) { 16398 final ViewRootImpl vr = (ViewRootImpl) parent; 16399 vr.transformMatrixToLocal(m); 16400 m.preTranslate(0, vr.mCurScrollY); 16401 } 16402 16403 m.preTranslate(-mLeft, -mTop); 16404 16405 if (!hasIdentityMatrix()) { 16406 m.preConcat(getInverseMatrix()); 16407 } 16408 } 16409 16410 /** 16411 * <p>Computes the coordinates of this view on the screen. The argument 16412 * must be an array of two integers. After the method returns, the array 16413 * contains the x and y location in that order.</p> 16414 * 16415 * @param location an array of two integers in which to hold the coordinates 16416 */ 16417 public void getLocationOnScreen(int[] location) { 16418 getLocationInWindow(location); 16419 16420 final AttachInfo info = mAttachInfo; 16421 if (info != null) { 16422 location[0] += info.mWindowLeft; 16423 location[1] += info.mWindowTop; 16424 } 16425 } 16426 16427 /** 16428 * <p>Computes the coordinates of this view in its window. The argument 16429 * must be an array of two integers. After the method returns, the array 16430 * contains the x and y location in that order.</p> 16431 * 16432 * @param location an array of two integers in which to hold the coordinates 16433 */ 16434 public void getLocationInWindow(int[] location) { 16435 if (location == null || location.length < 2) { 16436 throw new IllegalArgumentException("location must be an array of two integers"); 16437 } 16438 16439 if (mAttachInfo == null) { 16440 // When the view is not attached to a window, this method does not make sense 16441 location[0] = location[1] = 0; 16442 return; 16443 } 16444 16445 float[] position = mAttachInfo.mTmpTransformLocation; 16446 position[0] = position[1] = 0.0f; 16447 16448 if (!hasIdentityMatrix()) { 16449 getMatrix().mapPoints(position); 16450 } 16451 16452 position[0] += mLeft; 16453 position[1] += mTop; 16454 16455 ViewParent viewParent = mParent; 16456 while (viewParent instanceof View) { 16457 final View view = (View) viewParent; 16458 16459 position[0] -= view.mScrollX; 16460 position[1] -= view.mScrollY; 16461 16462 if (!view.hasIdentityMatrix()) { 16463 view.getMatrix().mapPoints(position); 16464 } 16465 16466 position[0] += view.mLeft; 16467 position[1] += view.mTop; 16468 16469 viewParent = view.mParent; 16470 } 16471 16472 if (viewParent instanceof ViewRootImpl) { 16473 // *cough* 16474 final ViewRootImpl vr = (ViewRootImpl) viewParent; 16475 position[1] -= vr.mCurScrollY; 16476 } 16477 16478 location[0] = (int) (position[0] + 0.5f); 16479 location[1] = (int) (position[1] + 0.5f); 16480 } 16481 16482 /** 16483 * {@hide} 16484 * @param id the id of the view to be found 16485 * @return the view of the specified id, null if cannot be found 16486 */ 16487 protected View findViewTraversal(int id) { 16488 if (id == mID) { 16489 return this; 16490 } 16491 return null; 16492 } 16493 16494 /** 16495 * {@hide} 16496 * @param tag the tag of the view to be found 16497 * @return the view of specified tag, null if cannot be found 16498 */ 16499 protected View findViewWithTagTraversal(Object tag) { 16500 if (tag != null && tag.equals(mTag)) { 16501 return this; 16502 } 16503 return null; 16504 } 16505 16506 /** 16507 * {@hide} 16508 * @param predicate The predicate to evaluate. 16509 * @param childToSkip If not null, ignores this child during the recursive traversal. 16510 * @return The first view that matches the predicate or null. 16511 */ 16512 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 16513 if (predicate.apply(this)) { 16514 return this; 16515 } 16516 return null; 16517 } 16518 16519 /** 16520 * Look for a child view with the given id. If this view has the given 16521 * id, return this view. 16522 * 16523 * @param id The id to search for. 16524 * @return The view that has the given id in the hierarchy or null 16525 */ 16526 public final View findViewById(int id) { 16527 if (id < 0) { 16528 return null; 16529 } 16530 return findViewTraversal(id); 16531 } 16532 16533 /** 16534 * Finds a view by its unuque and stable accessibility id. 16535 * 16536 * @param accessibilityId The searched accessibility id. 16537 * @return The found view. 16538 */ 16539 final View findViewByAccessibilityId(int accessibilityId) { 16540 if (accessibilityId < 0) { 16541 return null; 16542 } 16543 return findViewByAccessibilityIdTraversal(accessibilityId); 16544 } 16545 16546 /** 16547 * Performs the traversal to find a view by its unuque and stable accessibility id. 16548 * 16549 * <strong>Note:</strong>This method does not stop at the root namespace 16550 * boundary since the user can touch the screen at an arbitrary location 16551 * potentially crossing the root namespace bounday which will send an 16552 * accessibility event to accessibility services and they should be able 16553 * to obtain the event source. Also accessibility ids are guaranteed to be 16554 * unique in the window. 16555 * 16556 * @param accessibilityId The accessibility id. 16557 * @return The found view. 16558 * 16559 * @hide 16560 */ 16561 public View findViewByAccessibilityIdTraversal(int accessibilityId) { 16562 if (getAccessibilityViewId() == accessibilityId) { 16563 return this; 16564 } 16565 return null; 16566 } 16567 16568 /** 16569 * Look for a child view with the given tag. If this view has the given 16570 * tag, return this view. 16571 * 16572 * @param tag The tag to search for, using "tag.equals(getTag())". 16573 * @return The View that has the given tag in the hierarchy or null 16574 */ 16575 public final View findViewWithTag(Object tag) { 16576 if (tag == null) { 16577 return null; 16578 } 16579 return findViewWithTagTraversal(tag); 16580 } 16581 16582 /** 16583 * {@hide} 16584 * Look for a child view that matches the specified predicate. 16585 * If this view matches the predicate, return this view. 16586 * 16587 * @param predicate The predicate to evaluate. 16588 * @return The first view that matches the predicate or null. 16589 */ 16590 public final View findViewByPredicate(Predicate<View> predicate) { 16591 return findViewByPredicateTraversal(predicate, null); 16592 } 16593 16594 /** 16595 * {@hide} 16596 * Look for a child view that matches the specified predicate, 16597 * starting with the specified view and its descendents and then 16598 * recusively searching the ancestors and siblings of that view 16599 * until this view is reached. 16600 * 16601 * This method is useful in cases where the predicate does not match 16602 * a single unique view (perhaps multiple views use the same id) 16603 * and we are trying to find the view that is "closest" in scope to the 16604 * starting view. 16605 * 16606 * @param start The view to start from. 16607 * @param predicate The predicate to evaluate. 16608 * @return The first view that matches the predicate or null. 16609 */ 16610 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 16611 View childToSkip = null; 16612 for (;;) { 16613 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 16614 if (view != null || start == this) { 16615 return view; 16616 } 16617 16618 ViewParent parent = start.getParent(); 16619 if (parent == null || !(parent instanceof View)) { 16620 return null; 16621 } 16622 16623 childToSkip = start; 16624 start = (View) parent; 16625 } 16626 } 16627 16628 /** 16629 * Sets the identifier for this view. The identifier does not have to be 16630 * unique in this view's hierarchy. The identifier should be a positive 16631 * number. 16632 * 16633 * @see #NO_ID 16634 * @see #getId() 16635 * @see #findViewById(int) 16636 * 16637 * @param id a number used to identify the view 16638 * 16639 * @attr ref android.R.styleable#View_id 16640 */ 16641 public void setId(int id) { 16642 mID = id; 16643 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 16644 mID = generateViewId(); 16645 } 16646 } 16647 16648 /** 16649 * {@hide} 16650 * 16651 * @param isRoot true if the view belongs to the root namespace, false 16652 * otherwise 16653 */ 16654 public void setIsRootNamespace(boolean isRoot) { 16655 if (isRoot) { 16656 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 16657 } else { 16658 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 16659 } 16660 } 16661 16662 /** 16663 * {@hide} 16664 * 16665 * @return true if the view belongs to the root namespace, false otherwise 16666 */ 16667 public boolean isRootNamespace() { 16668 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 16669 } 16670 16671 /** 16672 * Returns this view's identifier. 16673 * 16674 * @return a positive integer used to identify the view or {@link #NO_ID} 16675 * if the view has no ID 16676 * 16677 * @see #setId(int) 16678 * @see #findViewById(int) 16679 * @attr ref android.R.styleable#View_id 16680 */ 16681 @ViewDebug.CapturedViewProperty 16682 public int getId() { 16683 return mID; 16684 } 16685 16686 /** 16687 * Returns this view's tag. 16688 * 16689 * @return the Object stored in this view as a tag, or {@code null} if not 16690 * set 16691 * 16692 * @see #setTag(Object) 16693 * @see #getTag(int) 16694 */ 16695 @ViewDebug.ExportedProperty 16696 public Object getTag() { 16697 return mTag; 16698 } 16699 16700 /** 16701 * Sets the tag associated with this view. A tag can be used to mark 16702 * a view in its hierarchy and does not have to be unique within the 16703 * hierarchy. Tags can also be used to store data within a view without 16704 * resorting to another data structure. 16705 * 16706 * @param tag an Object to tag the view with 16707 * 16708 * @see #getTag() 16709 * @see #setTag(int, Object) 16710 */ 16711 public void setTag(final Object tag) { 16712 mTag = tag; 16713 } 16714 16715 /** 16716 * Returns the tag associated with this view and the specified key. 16717 * 16718 * @param key The key identifying the tag 16719 * 16720 * @return the Object stored in this view as a tag, or {@code null} if not 16721 * set 16722 * 16723 * @see #setTag(int, Object) 16724 * @see #getTag() 16725 */ 16726 public Object getTag(int key) { 16727 if (mKeyedTags != null) return mKeyedTags.get(key); 16728 return null; 16729 } 16730 16731 /** 16732 * Sets a tag associated with this view and a key. A tag can be used 16733 * to mark a view in its hierarchy and does not have to be unique within 16734 * the hierarchy. Tags can also be used to store data within a view 16735 * without resorting to another data structure. 16736 * 16737 * The specified key should be an id declared in the resources of the 16738 * application to ensure it is unique (see the <a 16739 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 16740 * Keys identified as belonging to 16741 * the Android framework or not associated with any package will cause 16742 * an {@link IllegalArgumentException} to be thrown. 16743 * 16744 * @param key The key identifying the tag 16745 * @param tag An Object to tag the view with 16746 * 16747 * @throws IllegalArgumentException If they specified key is not valid 16748 * 16749 * @see #setTag(Object) 16750 * @see #getTag(int) 16751 */ 16752 public void setTag(int key, final Object tag) { 16753 // If the package id is 0x00 or 0x01, it's either an undefined package 16754 // or a framework id 16755 if ((key >>> 24) < 2) { 16756 throw new IllegalArgumentException("The key must be an application-specific " 16757 + "resource id."); 16758 } 16759 16760 setKeyedTag(key, tag); 16761 } 16762 16763 /** 16764 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 16765 * framework id. 16766 * 16767 * @hide 16768 */ 16769 public void setTagInternal(int key, Object tag) { 16770 if ((key >>> 24) != 0x1) { 16771 throw new IllegalArgumentException("The key must be a framework-specific " 16772 + "resource id."); 16773 } 16774 16775 setKeyedTag(key, tag); 16776 } 16777 16778 private void setKeyedTag(int key, Object tag) { 16779 if (mKeyedTags == null) { 16780 mKeyedTags = new SparseArray<Object>(2); 16781 } 16782 16783 mKeyedTags.put(key, tag); 16784 } 16785 16786 /** 16787 * Prints information about this view in the log output, with the tag 16788 * {@link #VIEW_LOG_TAG}. 16789 * 16790 * @hide 16791 */ 16792 public void debug() { 16793 debug(0); 16794 } 16795 16796 /** 16797 * Prints information about this view in the log output, with the tag 16798 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 16799 * indentation defined by the <code>depth</code>. 16800 * 16801 * @param depth the indentation level 16802 * 16803 * @hide 16804 */ 16805 protected void debug(int depth) { 16806 String output = debugIndent(depth - 1); 16807 16808 output += "+ " + this; 16809 int id = getId(); 16810 if (id != -1) { 16811 output += " (id=" + id + ")"; 16812 } 16813 Object tag = getTag(); 16814 if (tag != null) { 16815 output += " (tag=" + tag + ")"; 16816 } 16817 Log.d(VIEW_LOG_TAG, output); 16818 16819 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 16820 output = debugIndent(depth) + " FOCUSED"; 16821 Log.d(VIEW_LOG_TAG, output); 16822 } 16823 16824 output = debugIndent(depth); 16825 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 16826 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 16827 + "} "; 16828 Log.d(VIEW_LOG_TAG, output); 16829 16830 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 16831 || mPaddingBottom != 0) { 16832 output = debugIndent(depth); 16833 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 16834 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 16835 Log.d(VIEW_LOG_TAG, output); 16836 } 16837 16838 output = debugIndent(depth); 16839 output += "mMeasureWidth=" + mMeasuredWidth + 16840 " mMeasureHeight=" + mMeasuredHeight; 16841 Log.d(VIEW_LOG_TAG, output); 16842 16843 output = debugIndent(depth); 16844 if (mLayoutParams == null) { 16845 output += "BAD! no layout params"; 16846 } else { 16847 output = mLayoutParams.debug(output); 16848 } 16849 Log.d(VIEW_LOG_TAG, output); 16850 16851 output = debugIndent(depth); 16852 output += "flags={"; 16853 output += View.printFlags(mViewFlags); 16854 output += "}"; 16855 Log.d(VIEW_LOG_TAG, output); 16856 16857 output = debugIndent(depth); 16858 output += "privateFlags={"; 16859 output += View.printPrivateFlags(mPrivateFlags); 16860 output += "}"; 16861 Log.d(VIEW_LOG_TAG, output); 16862 } 16863 16864 /** 16865 * Creates a string of whitespaces used for indentation. 16866 * 16867 * @param depth the indentation level 16868 * @return a String containing (depth * 2 + 3) * 2 white spaces 16869 * 16870 * @hide 16871 */ 16872 protected static String debugIndent(int depth) { 16873 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 16874 for (int i = 0; i < (depth * 2) + 3; i++) { 16875 spaces.append(' ').append(' '); 16876 } 16877 return spaces.toString(); 16878 } 16879 16880 /** 16881 * <p>Return the offset of the widget's text baseline from the widget's top 16882 * boundary. If this widget does not support baseline alignment, this 16883 * method returns -1. </p> 16884 * 16885 * @return the offset of the baseline within the widget's bounds or -1 16886 * if baseline alignment is not supported 16887 */ 16888 @ViewDebug.ExportedProperty(category = "layout") 16889 public int getBaseline() { 16890 return -1; 16891 } 16892 16893 /** 16894 * Returns whether the view hierarchy is currently undergoing a layout pass. This 16895 * information is useful to avoid situations such as calling {@link #requestLayout()} during 16896 * a layout pass. 16897 * 16898 * @return whether the view hierarchy is currently undergoing a layout pass 16899 */ 16900 public boolean isInLayout() { 16901 ViewRootImpl viewRoot = getViewRootImpl(); 16902 return (viewRoot != null && viewRoot.isInLayout()); 16903 } 16904 16905 /** 16906 * Call this when something has changed which has invalidated the 16907 * layout of this view. This will schedule a layout pass of the view 16908 * tree. This should not be called while the view hierarchy is currently in a layout 16909 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 16910 * end of the current layout pass (and then layout will run again) or after the current 16911 * frame is drawn and the next layout occurs. 16912 * 16913 * <p>Subclasses which override this method should call the superclass method to 16914 * handle possible request-during-layout errors correctly.</p> 16915 */ 16916 public void requestLayout() { 16917 if (mMeasureCache != null) mMeasureCache.clear(); 16918 16919 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) { 16920 // Only trigger request-during-layout logic if this is the view requesting it, 16921 // not the views in its parent hierarchy 16922 ViewRootImpl viewRoot = getViewRootImpl(); 16923 if (viewRoot != null && viewRoot.isInLayout()) { 16924 if (!viewRoot.requestLayoutDuringLayout(this)) { 16925 return; 16926 } 16927 } 16928 mAttachInfo.mViewRequestingLayout = this; 16929 } 16930 16931 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 16932 mPrivateFlags |= PFLAG_INVALIDATED; 16933 16934 if (mParent != null && !mParent.isLayoutRequested()) { 16935 mParent.requestLayout(); 16936 } 16937 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) { 16938 mAttachInfo.mViewRequestingLayout = null; 16939 } 16940 } 16941 16942 /** 16943 * Forces this view to be laid out during the next layout pass. 16944 * This method does not call requestLayout() or forceLayout() 16945 * on the parent. 16946 */ 16947 public void forceLayout() { 16948 if (mMeasureCache != null) mMeasureCache.clear(); 16949 16950 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 16951 mPrivateFlags |= PFLAG_INVALIDATED; 16952 } 16953 16954 /** 16955 * <p> 16956 * This is called to find out how big a view should be. The parent 16957 * supplies constraint information in the width and height parameters. 16958 * </p> 16959 * 16960 * <p> 16961 * The actual measurement work of a view is performed in 16962 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 16963 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 16964 * </p> 16965 * 16966 * 16967 * @param widthMeasureSpec Horizontal space requirements as imposed by the 16968 * parent 16969 * @param heightMeasureSpec Vertical space requirements as imposed by the 16970 * parent 16971 * 16972 * @see #onMeasure(int, int) 16973 */ 16974 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 16975 boolean optical = isLayoutModeOptical(this); 16976 if (optical != isLayoutModeOptical(mParent)) { 16977 Insets insets = getOpticalInsets(); 16978 int oWidth = insets.left + insets.right; 16979 int oHeight = insets.top + insets.bottom; 16980 widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth); 16981 heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight); 16982 } 16983 16984 // Suppress sign extension for the low bytes 16985 long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL; 16986 if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2); 16987 16988 if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT || 16989 widthMeasureSpec != mOldWidthMeasureSpec || 16990 heightMeasureSpec != mOldHeightMeasureSpec) { 16991 16992 // first clears the measured dimension flag 16993 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 16994 16995 resolveRtlPropertiesIfNeeded(); 16996 16997 int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 : 16998 mMeasureCache.indexOfKey(key); 16999 if (cacheIndex < 0 || sIgnoreMeasureCache) { 17000 // measure ourselves, this should set the measured dimension flag back 17001 onMeasure(widthMeasureSpec, heightMeasureSpec); 17002 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 17003 } else { 17004 long value = mMeasureCache.valueAt(cacheIndex); 17005 // Casting a long to int drops the high 32 bits, no mask needed 17006 setMeasuredDimensionRaw((int) (value >> 32), (int) value); 17007 mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 17008 } 17009 17010 // flag not set, setMeasuredDimension() was not invoked, we raise 17011 // an exception to warn the developer 17012 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 17013 throw new IllegalStateException("onMeasure() did not set the" 17014 + " measured dimension by calling" 17015 + " setMeasuredDimension()"); 17016 } 17017 17018 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 17019 } 17020 17021 mOldWidthMeasureSpec = widthMeasureSpec; 17022 mOldHeightMeasureSpec = heightMeasureSpec; 17023 17024 mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 | 17025 (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension 17026 } 17027 17028 /** 17029 * <p> 17030 * Measure the view and its content to determine the measured width and the 17031 * measured height. This method is invoked by {@link #measure(int, int)} and 17032 * should be overriden by subclasses to provide accurate and efficient 17033 * measurement of their contents. 17034 * </p> 17035 * 17036 * <p> 17037 * <strong>CONTRACT:</strong> When overriding this method, you 17038 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 17039 * measured width and height of this view. Failure to do so will trigger an 17040 * <code>IllegalStateException</code>, thrown by 17041 * {@link #measure(int, int)}. Calling the superclass' 17042 * {@link #onMeasure(int, int)} is a valid use. 17043 * </p> 17044 * 17045 * <p> 17046 * The base class implementation of measure defaults to the background size, 17047 * unless a larger size is allowed by the MeasureSpec. Subclasses should 17048 * override {@link #onMeasure(int, int)} to provide better measurements of 17049 * their content. 17050 * </p> 17051 * 17052 * <p> 17053 * If this method is overridden, it is the subclass's responsibility to make 17054 * sure the measured height and width are at least the view's minimum height 17055 * and width ({@link #getSuggestedMinimumHeight()} and 17056 * {@link #getSuggestedMinimumWidth()}). 17057 * </p> 17058 * 17059 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 17060 * The requirements are encoded with 17061 * {@link android.view.View.MeasureSpec}. 17062 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 17063 * The requirements are encoded with 17064 * {@link android.view.View.MeasureSpec}. 17065 * 17066 * @see #getMeasuredWidth() 17067 * @see #getMeasuredHeight() 17068 * @see #setMeasuredDimension(int, int) 17069 * @see #getSuggestedMinimumHeight() 17070 * @see #getSuggestedMinimumWidth() 17071 * @see android.view.View.MeasureSpec#getMode(int) 17072 * @see android.view.View.MeasureSpec#getSize(int) 17073 */ 17074 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 17075 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 17076 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 17077 } 17078 17079 /** 17080 * <p>This method must be called by {@link #onMeasure(int, int)} to store the 17081 * measured width and measured height. Failing to do so will trigger an 17082 * exception at measurement time.</p> 17083 * 17084 * @param measuredWidth The measured width of this view. May be a complex 17085 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17086 * {@link #MEASURED_STATE_TOO_SMALL}. 17087 * @param measuredHeight The measured height of this view. May be a complex 17088 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17089 * {@link #MEASURED_STATE_TOO_SMALL}. 17090 */ 17091 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 17092 boolean optical = isLayoutModeOptical(this); 17093 if (optical != isLayoutModeOptical(mParent)) { 17094 Insets insets = getOpticalInsets(); 17095 int opticalWidth = insets.left + insets.right; 17096 int opticalHeight = insets.top + insets.bottom; 17097 17098 measuredWidth += optical ? opticalWidth : -opticalWidth; 17099 measuredHeight += optical ? opticalHeight : -opticalHeight; 17100 } 17101 setMeasuredDimensionRaw(measuredWidth, measuredHeight); 17102 } 17103 17104 /** 17105 * Sets the measured dimension without extra processing for things like optical bounds. 17106 * Useful for reapplying consistent values that have already been cooked with adjustments 17107 * for optical bounds, etc. such as those from the measurement cache. 17108 * 17109 * @param measuredWidth The measured width of this view. May be a complex 17110 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17111 * {@link #MEASURED_STATE_TOO_SMALL}. 17112 * @param measuredHeight The measured height of this view. May be a complex 17113 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17114 * {@link #MEASURED_STATE_TOO_SMALL}. 17115 */ 17116 private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) { 17117 mMeasuredWidth = measuredWidth; 17118 mMeasuredHeight = measuredHeight; 17119 17120 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 17121 } 17122 17123 /** 17124 * Merge two states as returned by {@link #getMeasuredState()}. 17125 * @param curState The current state as returned from a view or the result 17126 * of combining multiple views. 17127 * @param newState The new view state to combine. 17128 * @return Returns a new integer reflecting the combination of the two 17129 * states. 17130 */ 17131 public static int combineMeasuredStates(int curState, int newState) { 17132 return curState | newState; 17133 } 17134 17135 /** 17136 * Version of {@link #resolveSizeAndState(int, int, int)} 17137 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 17138 */ 17139 public static int resolveSize(int size, int measureSpec) { 17140 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 17141 } 17142 17143 /** 17144 * Utility to reconcile a desired size and state, with constraints imposed 17145 * by a MeasureSpec. Will take the desired size, unless a different size 17146 * is imposed by the constraints. The returned value is a compound integer, 17147 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 17148 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 17149 * size is smaller than the size the view wants to be. 17150 * 17151 * @param size How big the view wants to be 17152 * @param measureSpec Constraints imposed by the parent 17153 * @return Size information bit mask as defined by 17154 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 17155 */ 17156 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 17157 int result = size; 17158 int specMode = MeasureSpec.getMode(measureSpec); 17159 int specSize = MeasureSpec.getSize(measureSpec); 17160 switch (specMode) { 17161 case MeasureSpec.UNSPECIFIED: 17162 result = size; 17163 break; 17164 case MeasureSpec.AT_MOST: 17165 if (specSize < size) { 17166 result = specSize | MEASURED_STATE_TOO_SMALL; 17167 } else { 17168 result = size; 17169 } 17170 break; 17171 case MeasureSpec.EXACTLY: 17172 result = specSize; 17173 break; 17174 } 17175 return result | (childMeasuredState&MEASURED_STATE_MASK); 17176 } 17177 17178 /** 17179 * Utility to return a default size. Uses the supplied size if the 17180 * MeasureSpec imposed no constraints. Will get larger if allowed 17181 * by the MeasureSpec. 17182 * 17183 * @param size Default size for this view 17184 * @param measureSpec Constraints imposed by the parent 17185 * @return The size this view should be. 17186 */ 17187 public static int getDefaultSize(int size, int measureSpec) { 17188 int result = size; 17189 int specMode = MeasureSpec.getMode(measureSpec); 17190 int specSize = MeasureSpec.getSize(measureSpec); 17191 17192 switch (specMode) { 17193 case MeasureSpec.UNSPECIFIED: 17194 result = size; 17195 break; 17196 case MeasureSpec.AT_MOST: 17197 case MeasureSpec.EXACTLY: 17198 result = specSize; 17199 break; 17200 } 17201 return result; 17202 } 17203 17204 /** 17205 * Returns the suggested minimum height that the view should use. This 17206 * returns the maximum of the view's minimum height 17207 * and the background's minimum height 17208 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 17209 * <p> 17210 * When being used in {@link #onMeasure(int, int)}, the caller should still 17211 * ensure the returned height is within the requirements of the parent. 17212 * 17213 * @return The suggested minimum height of the view. 17214 */ 17215 protected int getSuggestedMinimumHeight() { 17216 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 17217 17218 } 17219 17220 /** 17221 * Returns the suggested minimum width that the view should use. This 17222 * returns the maximum of the view's minimum width) 17223 * and the background's minimum width 17224 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 17225 * <p> 17226 * When being used in {@link #onMeasure(int, int)}, the caller should still 17227 * ensure the returned width is within the requirements of the parent. 17228 * 17229 * @return The suggested minimum width of the view. 17230 */ 17231 protected int getSuggestedMinimumWidth() { 17232 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 17233 } 17234 17235 /** 17236 * Returns the minimum height of the view. 17237 * 17238 * @return the minimum height the view will try to be. 17239 * 17240 * @see #setMinimumHeight(int) 17241 * 17242 * @attr ref android.R.styleable#View_minHeight 17243 */ 17244 public int getMinimumHeight() { 17245 return mMinHeight; 17246 } 17247 17248 /** 17249 * Sets the minimum height of the view. It is not guaranteed the view will 17250 * be able to achieve this minimum height (for example, if its parent layout 17251 * constrains it with less available height). 17252 * 17253 * @param minHeight The minimum height the view will try to be. 17254 * 17255 * @see #getMinimumHeight() 17256 * 17257 * @attr ref android.R.styleable#View_minHeight 17258 */ 17259 public void setMinimumHeight(int minHeight) { 17260 mMinHeight = minHeight; 17261 requestLayout(); 17262 } 17263 17264 /** 17265 * Returns the minimum width of the view. 17266 * 17267 * @return the minimum width the view will try to be. 17268 * 17269 * @see #setMinimumWidth(int) 17270 * 17271 * @attr ref android.R.styleable#View_minWidth 17272 */ 17273 public int getMinimumWidth() { 17274 return mMinWidth; 17275 } 17276 17277 /** 17278 * Sets the minimum width of the view. It is not guaranteed the view will 17279 * be able to achieve this minimum width (for example, if its parent layout 17280 * constrains it with less available width). 17281 * 17282 * @param minWidth The minimum width the view will try to be. 17283 * 17284 * @see #getMinimumWidth() 17285 * 17286 * @attr ref android.R.styleable#View_minWidth 17287 */ 17288 public void setMinimumWidth(int minWidth) { 17289 mMinWidth = minWidth; 17290 requestLayout(); 17291 17292 } 17293 17294 /** 17295 * Get the animation currently associated with this view. 17296 * 17297 * @return The animation that is currently playing or 17298 * scheduled to play for this view. 17299 */ 17300 public Animation getAnimation() { 17301 return mCurrentAnimation; 17302 } 17303 17304 /** 17305 * Start the specified animation now. 17306 * 17307 * @param animation the animation to start now 17308 */ 17309 public void startAnimation(Animation animation) { 17310 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 17311 setAnimation(animation); 17312 invalidateParentCaches(); 17313 invalidate(true); 17314 } 17315 17316 /** 17317 * Cancels any animations for this view. 17318 */ 17319 public void clearAnimation() { 17320 if (mCurrentAnimation != null) { 17321 mCurrentAnimation.detach(); 17322 } 17323 mCurrentAnimation = null; 17324 invalidateParentIfNeeded(); 17325 } 17326 17327 /** 17328 * Sets the next animation to play for this view. 17329 * If you want the animation to play immediately, use 17330 * {@link #startAnimation(android.view.animation.Animation)} instead. 17331 * This method provides allows fine-grained 17332 * control over the start time and invalidation, but you 17333 * must make sure that 1) the animation has a start time set, and 17334 * 2) the view's parent (which controls animations on its children) 17335 * will be invalidated when the animation is supposed to 17336 * start. 17337 * 17338 * @param animation The next animation, or null. 17339 */ 17340 public void setAnimation(Animation animation) { 17341 mCurrentAnimation = animation; 17342 17343 if (animation != null) { 17344 // If the screen is off assume the animation start time is now instead of 17345 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 17346 // would cause the animation to start when the screen turns back on 17347 if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF 17348 && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 17349 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 17350 } 17351 animation.reset(); 17352 } 17353 } 17354 17355 /** 17356 * Invoked by a parent ViewGroup to notify the start of the animation 17357 * currently associated with this view. If you override this method, 17358 * always call super.onAnimationStart(); 17359 * 17360 * @see #setAnimation(android.view.animation.Animation) 17361 * @see #getAnimation() 17362 */ 17363 protected void onAnimationStart() { 17364 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 17365 } 17366 17367 /** 17368 * Invoked by a parent ViewGroup to notify the end of the animation 17369 * currently associated with this view. If you override this method, 17370 * always call super.onAnimationEnd(); 17371 * 17372 * @see #setAnimation(android.view.animation.Animation) 17373 * @see #getAnimation() 17374 */ 17375 protected void onAnimationEnd() { 17376 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 17377 } 17378 17379 /** 17380 * Invoked if there is a Transform that involves alpha. Subclass that can 17381 * draw themselves with the specified alpha should return true, and then 17382 * respect that alpha when their onDraw() is called. If this returns false 17383 * then the view may be redirected to draw into an offscreen buffer to 17384 * fulfill the request, which will look fine, but may be slower than if the 17385 * subclass handles it internally. The default implementation returns false. 17386 * 17387 * @param alpha The alpha (0..255) to apply to the view's drawing 17388 * @return true if the view can draw with the specified alpha. 17389 */ 17390 protected boolean onSetAlpha(int alpha) { 17391 return false; 17392 } 17393 17394 /** 17395 * This is used by the RootView to perform an optimization when 17396 * the view hierarchy contains one or several SurfaceView. 17397 * SurfaceView is always considered transparent, but its children are not, 17398 * therefore all View objects remove themselves from the global transparent 17399 * region (passed as a parameter to this function). 17400 * 17401 * @param region The transparent region for this ViewAncestor (window). 17402 * 17403 * @return Returns true if the effective visibility of the view at this 17404 * point is opaque, regardless of the transparent region; returns false 17405 * if it is possible for underlying windows to be seen behind the view. 17406 * 17407 * {@hide} 17408 */ 17409 public boolean gatherTransparentRegion(Region region) { 17410 final AttachInfo attachInfo = mAttachInfo; 17411 if (region != null && attachInfo != null) { 17412 final int pflags = mPrivateFlags; 17413 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 17414 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 17415 // remove it from the transparent region. 17416 final int[] location = attachInfo.mTransparentLocation; 17417 getLocationInWindow(location); 17418 region.op(location[0], location[1], location[0] + mRight - mLeft, 17419 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 17420 } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) { 17421 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 17422 // exists, so we remove the background drawable's non-transparent 17423 // parts from this transparent region. 17424 applyDrawableToTransparentRegion(mBackground, region); 17425 } 17426 } 17427 return true; 17428 } 17429 17430 /** 17431 * Play a sound effect for this view. 17432 * 17433 * <p>The framework will play sound effects for some built in actions, such as 17434 * clicking, but you may wish to play these effects in your widget, 17435 * for instance, for internal navigation. 17436 * 17437 * <p>The sound effect will only be played if sound effects are enabled by the user, and 17438 * {@link #isSoundEffectsEnabled()} is true. 17439 * 17440 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 17441 */ 17442 public void playSoundEffect(int soundConstant) { 17443 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 17444 return; 17445 } 17446 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 17447 } 17448 17449 /** 17450 * BZZZTT!!1! 17451 * 17452 * <p>Provide haptic feedback to the user for this view. 17453 * 17454 * <p>The framework will provide haptic feedback for some built in actions, 17455 * such as long presses, but you may wish to provide feedback for your 17456 * own widget. 17457 * 17458 * <p>The feedback will only be performed if 17459 * {@link #isHapticFeedbackEnabled()} is true. 17460 * 17461 * @param feedbackConstant One of the constants defined in 17462 * {@link HapticFeedbackConstants} 17463 */ 17464 public boolean performHapticFeedback(int feedbackConstant) { 17465 return performHapticFeedback(feedbackConstant, 0); 17466 } 17467 17468 /** 17469 * BZZZTT!!1! 17470 * 17471 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 17472 * 17473 * @param feedbackConstant One of the constants defined in 17474 * {@link HapticFeedbackConstants} 17475 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 17476 */ 17477 public boolean performHapticFeedback(int feedbackConstant, int flags) { 17478 if (mAttachInfo == null) { 17479 return false; 17480 } 17481 //noinspection SimplifiableIfStatement 17482 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 17483 && !isHapticFeedbackEnabled()) { 17484 return false; 17485 } 17486 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 17487 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 17488 } 17489 17490 /** 17491 * Request that the visibility of the status bar or other screen/window 17492 * decorations be changed. 17493 * 17494 * <p>This method is used to put the over device UI into temporary modes 17495 * where the user's attention is focused more on the application content, 17496 * by dimming or hiding surrounding system affordances. This is typically 17497 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 17498 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 17499 * to be placed behind the action bar (and with these flags other system 17500 * affordances) so that smooth transitions between hiding and showing them 17501 * can be done. 17502 * 17503 * <p>Two representative examples of the use of system UI visibility is 17504 * implementing a content browsing application (like a magazine reader) 17505 * and a video playing application. 17506 * 17507 * <p>The first code shows a typical implementation of a View in a content 17508 * browsing application. In this implementation, the application goes 17509 * into a content-oriented mode by hiding the status bar and action bar, 17510 * and putting the navigation elements into lights out mode. The user can 17511 * then interact with content while in this mode. Such an application should 17512 * provide an easy way for the user to toggle out of the mode (such as to 17513 * check information in the status bar or access notifications). In the 17514 * implementation here, this is done simply by tapping on the content. 17515 * 17516 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 17517 * content} 17518 * 17519 * <p>This second code sample shows a typical implementation of a View 17520 * in a video playing application. In this situation, while the video is 17521 * playing the application would like to go into a complete full-screen mode, 17522 * to use as much of the display as possible for the video. When in this state 17523 * the user can not interact with the application; the system intercepts 17524 * touching on the screen to pop the UI out of full screen mode. See 17525 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 17526 * 17527 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 17528 * content} 17529 * 17530 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 17531 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 17532 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 17533 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 17534 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 17535 */ 17536 public void setSystemUiVisibility(int visibility) { 17537 if (visibility != mSystemUiVisibility) { 17538 mSystemUiVisibility = visibility; 17539 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 17540 mParent.recomputeViewAttributes(this); 17541 } 17542 } 17543 } 17544 17545 /** 17546 * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested. 17547 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 17548 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 17549 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 17550 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 17551 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 17552 */ 17553 public int getSystemUiVisibility() { 17554 return mSystemUiVisibility; 17555 } 17556 17557 /** 17558 * Returns the current system UI visibility that is currently set for 17559 * the entire window. This is the combination of the 17560 * {@link #setSystemUiVisibility(int)} values supplied by all of the 17561 * views in the window. 17562 */ 17563 public int getWindowSystemUiVisibility() { 17564 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 17565 } 17566 17567 /** 17568 * Override to find out when the window's requested system UI visibility 17569 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 17570 * This is different from the callbacks received through 17571 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 17572 * in that this is only telling you about the local request of the window, 17573 * not the actual values applied by the system. 17574 */ 17575 public void onWindowSystemUiVisibilityChanged(int visible) { 17576 } 17577 17578 /** 17579 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 17580 * the view hierarchy. 17581 */ 17582 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 17583 onWindowSystemUiVisibilityChanged(visible); 17584 } 17585 17586 /** 17587 * Set a listener to receive callbacks when the visibility of the system bar changes. 17588 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 17589 */ 17590 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 17591 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 17592 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 17593 mParent.recomputeViewAttributes(this); 17594 } 17595 } 17596 17597 /** 17598 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 17599 * the view hierarchy. 17600 */ 17601 public void dispatchSystemUiVisibilityChanged(int visibility) { 17602 ListenerInfo li = mListenerInfo; 17603 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 17604 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 17605 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 17606 } 17607 } 17608 17609 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 17610 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 17611 if (val != mSystemUiVisibility) { 17612 setSystemUiVisibility(val); 17613 return true; 17614 } 17615 return false; 17616 } 17617 17618 /** @hide */ 17619 public void setDisabledSystemUiVisibility(int flags) { 17620 if (mAttachInfo != null) { 17621 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 17622 mAttachInfo.mDisabledSystemUiVisibility = flags; 17623 if (mParent != null) { 17624 mParent.recomputeViewAttributes(this); 17625 } 17626 } 17627 } 17628 } 17629 17630 /** 17631 * Creates an image that the system displays during the drag and drop 17632 * operation. This is called a "drag shadow". The default implementation 17633 * for a DragShadowBuilder based on a View returns an image that has exactly the same 17634 * appearance as the given View. The default also positions the center of the drag shadow 17635 * directly under the touch point. If no View is provided (the constructor with no parameters 17636 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 17637 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 17638 * default is an invisible drag shadow. 17639 * <p> 17640 * You are not required to use the View you provide to the constructor as the basis of the 17641 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 17642 * anything you want as the drag shadow. 17643 * </p> 17644 * <p> 17645 * You pass a DragShadowBuilder object to the system when you start the drag. The system 17646 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 17647 * size and position of the drag shadow. It uses this data to construct a 17648 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 17649 * so that your application can draw the shadow image in the Canvas. 17650 * </p> 17651 * 17652 * <div class="special reference"> 17653 * <h3>Developer Guides</h3> 17654 * <p>For a guide to implementing drag and drop features, read the 17655 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 17656 * </div> 17657 */ 17658 public static class DragShadowBuilder { 17659 private final WeakReference<View> mView; 17660 17661 /** 17662 * Constructs a shadow image builder based on a View. By default, the resulting drag 17663 * shadow will have the same appearance and dimensions as the View, with the touch point 17664 * over the center of the View. 17665 * @param view A View. Any View in scope can be used. 17666 */ 17667 public DragShadowBuilder(View view) { 17668 mView = new WeakReference<View>(view); 17669 } 17670 17671 /** 17672 * Construct a shadow builder object with no associated View. This 17673 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 17674 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 17675 * to supply the drag shadow's dimensions and appearance without 17676 * reference to any View object. If they are not overridden, then the result is an 17677 * invisible drag shadow. 17678 */ 17679 public DragShadowBuilder() { 17680 mView = new WeakReference<View>(null); 17681 } 17682 17683 /** 17684 * Returns the View object that had been passed to the 17685 * {@link #View.DragShadowBuilder(View)} 17686 * constructor. If that View parameter was {@code null} or if the 17687 * {@link #View.DragShadowBuilder()} 17688 * constructor was used to instantiate the builder object, this method will return 17689 * null. 17690 * 17691 * @return The View object associate with this builder object. 17692 */ 17693 @SuppressWarnings({"JavadocReference"}) 17694 final public View getView() { 17695 return mView.get(); 17696 } 17697 17698 /** 17699 * Provides the metrics for the shadow image. These include the dimensions of 17700 * the shadow image, and the point within that shadow that should 17701 * be centered under the touch location while dragging. 17702 * <p> 17703 * The default implementation sets the dimensions of the shadow to be the 17704 * same as the dimensions of the View itself and centers the shadow under 17705 * the touch point. 17706 * </p> 17707 * 17708 * @param shadowSize A {@link android.graphics.Point} containing the width and height 17709 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 17710 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 17711 * image. 17712 * 17713 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 17714 * shadow image that should be underneath the touch point during the drag and drop 17715 * operation. Your application must set {@link android.graphics.Point#x} to the 17716 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 17717 */ 17718 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 17719 final View view = mView.get(); 17720 if (view != null) { 17721 shadowSize.set(view.getWidth(), view.getHeight()); 17722 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 17723 } else { 17724 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 17725 } 17726 } 17727 17728 /** 17729 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 17730 * based on the dimensions it received from the 17731 * {@link #onProvideShadowMetrics(Point, Point)} callback. 17732 * 17733 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 17734 */ 17735 public void onDrawShadow(Canvas canvas) { 17736 final View view = mView.get(); 17737 if (view != null) { 17738 view.draw(canvas); 17739 } else { 17740 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 17741 } 17742 } 17743 } 17744 17745 /** 17746 * Starts a drag and drop operation. When your application calls this method, it passes a 17747 * {@link android.view.View.DragShadowBuilder} object to the system. The 17748 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 17749 * to get metrics for the drag shadow, and then calls the object's 17750 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 17751 * <p> 17752 * Once the system has the drag shadow, it begins the drag and drop operation by sending 17753 * drag events to all the View objects in your application that are currently visible. It does 17754 * this either by calling the View object's drag listener (an implementation of 17755 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 17756 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 17757 * Both are passed a {@link android.view.DragEvent} object that has a 17758 * {@link android.view.DragEvent#getAction()} value of 17759 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 17760 * </p> 17761 * <p> 17762 * Your application can invoke startDrag() on any attached View object. The View object does not 17763 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 17764 * be related to the View the user selected for dragging. 17765 * </p> 17766 * @param data A {@link android.content.ClipData} object pointing to the data to be 17767 * transferred by the drag and drop operation. 17768 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 17769 * drag shadow. 17770 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 17771 * drop operation. This Object is put into every DragEvent object sent by the system during the 17772 * current drag. 17773 * <p> 17774 * myLocalState is a lightweight mechanism for the sending information from the dragged View 17775 * to the target Views. For example, it can contain flags that differentiate between a 17776 * a copy operation and a move operation. 17777 * </p> 17778 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 17779 * so the parameter should be set to 0. 17780 * @return {@code true} if the method completes successfully, or 17781 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 17782 * do a drag, and so no drag operation is in progress. 17783 */ 17784 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 17785 Object myLocalState, int flags) { 17786 if (ViewDebug.DEBUG_DRAG) { 17787 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 17788 } 17789 boolean okay = false; 17790 17791 Point shadowSize = new Point(); 17792 Point shadowTouchPoint = new Point(); 17793 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 17794 17795 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 17796 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 17797 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 17798 } 17799 17800 if (ViewDebug.DEBUG_DRAG) { 17801 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 17802 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 17803 } 17804 Surface surface = new Surface(); 17805 try { 17806 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 17807 flags, shadowSize.x, shadowSize.y, surface); 17808 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 17809 + " surface=" + surface); 17810 if (token != null) { 17811 Canvas canvas = surface.lockCanvas(null); 17812 try { 17813 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 17814 shadowBuilder.onDrawShadow(canvas); 17815 } finally { 17816 surface.unlockCanvasAndPost(canvas); 17817 } 17818 17819 final ViewRootImpl root = getViewRootImpl(); 17820 17821 // Cache the local state object for delivery with DragEvents 17822 root.setLocalDragState(myLocalState); 17823 17824 // repurpose 'shadowSize' for the last touch point 17825 root.getLastTouchPoint(shadowSize); 17826 17827 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 17828 shadowSize.x, shadowSize.y, 17829 shadowTouchPoint.x, shadowTouchPoint.y, data); 17830 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 17831 17832 // Off and running! Release our local surface instance; the drag 17833 // shadow surface is now managed by the system process. 17834 surface.release(); 17835 } 17836 } catch (Exception e) { 17837 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 17838 surface.destroy(); 17839 } 17840 17841 return okay; 17842 } 17843 17844 /** 17845 * Handles drag events sent by the system following a call to 17846 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 17847 *<p> 17848 * When the system calls this method, it passes a 17849 * {@link android.view.DragEvent} object. A call to 17850 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 17851 * in DragEvent. The method uses these to determine what is happening in the drag and drop 17852 * operation. 17853 * @param event The {@link android.view.DragEvent} sent by the system. 17854 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 17855 * in DragEvent, indicating the type of drag event represented by this object. 17856 * @return {@code true} if the method was successful, otherwise {@code false}. 17857 * <p> 17858 * The method should return {@code true} in response to an action type of 17859 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 17860 * operation. 17861 * </p> 17862 * <p> 17863 * The method should also return {@code true} in response to an action type of 17864 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 17865 * {@code false} if it didn't. 17866 * </p> 17867 */ 17868 public boolean onDragEvent(DragEvent event) { 17869 return false; 17870 } 17871 17872 /** 17873 * Detects if this View is enabled and has a drag event listener. 17874 * If both are true, then it calls the drag event listener with the 17875 * {@link android.view.DragEvent} it received. If the drag event listener returns 17876 * {@code true}, then dispatchDragEvent() returns {@code true}. 17877 * <p> 17878 * For all other cases, the method calls the 17879 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 17880 * method and returns its result. 17881 * </p> 17882 * <p> 17883 * This ensures that a drag event is always consumed, even if the View does not have a drag 17884 * event listener. However, if the View has a listener and the listener returns true, then 17885 * onDragEvent() is not called. 17886 * </p> 17887 */ 17888 public boolean dispatchDragEvent(DragEvent event) { 17889 ListenerInfo li = mListenerInfo; 17890 //noinspection SimplifiableIfStatement 17891 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 17892 && li.mOnDragListener.onDrag(this, event)) { 17893 return true; 17894 } 17895 return onDragEvent(event); 17896 } 17897 17898 boolean canAcceptDrag() { 17899 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 17900 } 17901 17902 /** 17903 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 17904 * it is ever exposed at all. 17905 * @hide 17906 */ 17907 public void onCloseSystemDialogs(String reason) { 17908 } 17909 17910 /** 17911 * Given a Drawable whose bounds have been set to draw into this view, 17912 * update a Region being computed for 17913 * {@link #gatherTransparentRegion(android.graphics.Region)} so 17914 * that any non-transparent parts of the Drawable are removed from the 17915 * given transparent region. 17916 * 17917 * @param dr The Drawable whose transparency is to be applied to the region. 17918 * @param region A Region holding the current transparency information, 17919 * where any parts of the region that are set are considered to be 17920 * transparent. On return, this region will be modified to have the 17921 * transparency information reduced by the corresponding parts of the 17922 * Drawable that are not transparent. 17923 * {@hide} 17924 */ 17925 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 17926 if (DBG) { 17927 Log.i("View", "Getting transparent region for: " + this); 17928 } 17929 final Region r = dr.getTransparentRegion(); 17930 final Rect db = dr.getBounds(); 17931 final AttachInfo attachInfo = mAttachInfo; 17932 if (r != null && attachInfo != null) { 17933 final int w = getRight()-getLeft(); 17934 final int h = getBottom()-getTop(); 17935 if (db.left > 0) { 17936 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 17937 r.op(0, 0, db.left, h, Region.Op.UNION); 17938 } 17939 if (db.right < w) { 17940 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 17941 r.op(db.right, 0, w, h, Region.Op.UNION); 17942 } 17943 if (db.top > 0) { 17944 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 17945 r.op(0, 0, w, db.top, Region.Op.UNION); 17946 } 17947 if (db.bottom < h) { 17948 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 17949 r.op(0, db.bottom, w, h, Region.Op.UNION); 17950 } 17951 final int[] location = attachInfo.mTransparentLocation; 17952 getLocationInWindow(location); 17953 r.translate(location[0], location[1]); 17954 region.op(r, Region.Op.INTERSECT); 17955 } else { 17956 region.op(db, Region.Op.DIFFERENCE); 17957 } 17958 } 17959 17960 private void checkForLongClick(int delayOffset) { 17961 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 17962 mHasPerformedLongPress = false; 17963 17964 if (mPendingCheckForLongPress == null) { 17965 mPendingCheckForLongPress = new CheckForLongPress(); 17966 } 17967 mPendingCheckForLongPress.rememberWindowAttachCount(); 17968 postDelayed(mPendingCheckForLongPress, 17969 ViewConfiguration.getLongPressTimeout() - delayOffset); 17970 } 17971 } 17972 17973 /** 17974 * Inflate a view from an XML resource. This convenience method wraps the {@link 17975 * LayoutInflater} class, which provides a full range of options for view inflation. 17976 * 17977 * @param context The Context object for your activity or application. 17978 * @param resource The resource ID to inflate 17979 * @param root A view group that will be the parent. Used to properly inflate the 17980 * layout_* parameters. 17981 * @see LayoutInflater 17982 */ 17983 public static View inflate(Context context, int resource, ViewGroup root) { 17984 LayoutInflater factory = LayoutInflater.from(context); 17985 return factory.inflate(resource, root); 17986 } 17987 17988 /** 17989 * Scroll the view with standard behavior for scrolling beyond the normal 17990 * content boundaries. Views that call this method should override 17991 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 17992 * results of an over-scroll operation. 17993 * 17994 * Views can use this method to handle any touch or fling-based scrolling. 17995 * 17996 * @param deltaX Change in X in pixels 17997 * @param deltaY Change in Y in pixels 17998 * @param scrollX Current X scroll value in pixels before applying deltaX 17999 * @param scrollY Current Y scroll value in pixels before applying deltaY 18000 * @param scrollRangeX Maximum content scroll range along the X axis 18001 * @param scrollRangeY Maximum content scroll range along the Y axis 18002 * @param maxOverScrollX Number of pixels to overscroll by in either direction 18003 * along the X axis. 18004 * @param maxOverScrollY Number of pixels to overscroll by in either direction 18005 * along the Y axis. 18006 * @param isTouchEvent true if this scroll operation is the result of a touch event. 18007 * @return true if scrolling was clamped to an over-scroll boundary along either 18008 * axis, false otherwise. 18009 */ 18010 @SuppressWarnings({"UnusedParameters"}) 18011 protected boolean overScrollBy(int deltaX, int deltaY, 18012 int scrollX, int scrollY, 18013 int scrollRangeX, int scrollRangeY, 18014 int maxOverScrollX, int maxOverScrollY, 18015 boolean isTouchEvent) { 18016 final int overScrollMode = mOverScrollMode; 18017 final boolean canScrollHorizontal = 18018 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 18019 final boolean canScrollVertical = 18020 computeVerticalScrollRange() > computeVerticalScrollExtent(); 18021 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 18022 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 18023 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 18024 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 18025 18026 int newScrollX = scrollX + deltaX; 18027 if (!overScrollHorizontal) { 18028 maxOverScrollX = 0; 18029 } 18030 18031 int newScrollY = scrollY + deltaY; 18032 if (!overScrollVertical) { 18033 maxOverScrollY = 0; 18034 } 18035 18036 // Clamp values if at the limits and record 18037 final int left = -maxOverScrollX; 18038 final int right = maxOverScrollX + scrollRangeX; 18039 final int top = -maxOverScrollY; 18040 final int bottom = maxOverScrollY + scrollRangeY; 18041 18042 boolean clampedX = false; 18043 if (newScrollX > right) { 18044 newScrollX = right; 18045 clampedX = true; 18046 } else if (newScrollX < left) { 18047 newScrollX = left; 18048 clampedX = true; 18049 } 18050 18051 boolean clampedY = false; 18052 if (newScrollY > bottom) { 18053 newScrollY = bottom; 18054 clampedY = true; 18055 } else if (newScrollY < top) { 18056 newScrollY = top; 18057 clampedY = true; 18058 } 18059 18060 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 18061 18062 return clampedX || clampedY; 18063 } 18064 18065 /** 18066 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 18067 * respond to the results of an over-scroll operation. 18068 * 18069 * @param scrollX New X scroll value in pixels 18070 * @param scrollY New Y scroll value in pixels 18071 * @param clampedX True if scrollX was clamped to an over-scroll boundary 18072 * @param clampedY True if scrollY was clamped to an over-scroll boundary 18073 */ 18074 protected void onOverScrolled(int scrollX, int scrollY, 18075 boolean clampedX, boolean clampedY) { 18076 // Intentionally empty. 18077 } 18078 18079 /** 18080 * Returns the over-scroll mode for this view. The result will be 18081 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 18082 * (allow over-scrolling only if the view content is larger than the container), 18083 * or {@link #OVER_SCROLL_NEVER}. 18084 * 18085 * @return This view's over-scroll mode. 18086 */ 18087 public int getOverScrollMode() { 18088 return mOverScrollMode; 18089 } 18090 18091 /** 18092 * Set the over-scroll mode for this view. Valid over-scroll modes are 18093 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 18094 * (allow over-scrolling only if the view content is larger than the container), 18095 * or {@link #OVER_SCROLL_NEVER}. 18096 * 18097 * Setting the over-scroll mode of a view will have an effect only if the 18098 * view is capable of scrolling. 18099 * 18100 * @param overScrollMode The new over-scroll mode for this view. 18101 */ 18102 public void setOverScrollMode(int overScrollMode) { 18103 if (overScrollMode != OVER_SCROLL_ALWAYS && 18104 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 18105 overScrollMode != OVER_SCROLL_NEVER) { 18106 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 18107 } 18108 mOverScrollMode = overScrollMode; 18109 } 18110 18111 /** 18112 * Enable or disable nested scrolling for this view. 18113 * 18114 * <p>If this property is set to true the view will be permitted to initiate nested 18115 * scrolling operations with a compatible parent view in the current hierarchy. If this 18116 * view does not implement nested scrolling this will have no effect. Disabling nested scrolling 18117 * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping} 18118 * the nested scroll.</p> 18119 * 18120 * @param enabled true to enable nested scrolling, false to disable 18121 * 18122 * @see #isNestedScrollingEnabled() 18123 */ 18124 public void setNestedScrollingEnabled(boolean enabled) { 18125 if (enabled) { 18126 mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED; 18127 } else { 18128 stopNestedScroll(); 18129 mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED; 18130 } 18131 } 18132 18133 /** 18134 * Returns true if nested scrolling is enabled for this view. 18135 * 18136 * <p>If nested scrolling is enabled and this View class implementation supports it, 18137 * this view will act as a nested scrolling child view when applicable, forwarding data 18138 * about the scroll operation in progress to a compatible and cooperating nested scrolling 18139 * parent.</p> 18140 * 18141 * @return true if nested scrolling is enabled 18142 * 18143 * @see #setNestedScrollingEnabled(boolean) 18144 */ 18145 public boolean isNestedScrollingEnabled() { 18146 return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) == 18147 PFLAG3_NESTED_SCROLLING_ENABLED; 18148 } 18149 18150 /** 18151 * Begin a nestable scroll operation along the given axes. 18152 * 18153 * <p>A view starting a nested scroll promises to abide by the following contract:</p> 18154 * 18155 * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case 18156 * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}. 18157 * In the case of touch scrolling the nested scroll will be terminated automatically in 18158 * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}. 18159 * In the event of programmatic scrolling the caller must explicitly call 18160 * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p> 18161 * 18162 * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found. 18163 * If it returns false the caller may ignore the rest of this contract until the next scroll. 18164 * Calling startNestedScroll while a nested scroll is already in progress will return true.</p> 18165 * 18166 * <p>At each incremental step of the scroll the caller should invoke 18167 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} 18168 * once it has calculated the requested scrolling delta. If it returns true the nested scrolling 18169 * parent at least partially consumed the scroll and the caller should adjust the amount it 18170 * scrolls by.</p> 18171 * 18172 * <p>After applying the remainder of the scroll delta the caller should invoke 18173 * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing 18174 * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat 18175 * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}. 18176 * </p> 18177 * 18178 * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or 18179 * {@link #SCROLL_AXIS_VERTICAL}. 18180 * @return true if a cooperative parent was found and nested scrolling has been enabled for 18181 * the current gesture. 18182 * 18183 * @see #stopNestedScroll() 18184 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 18185 * @see #dispatchNestedScroll(int, int, int, int, int[]) 18186 */ 18187 public boolean startNestedScroll(int axes) { 18188 if (hasNestedScrollingParent()) { 18189 // Already in progress 18190 return true; 18191 } 18192 if (isNestedScrollingEnabled()) { 18193 ViewParent p = getParent(); 18194 View child = this; 18195 while (p != null) { 18196 try { 18197 if (p.onStartNestedScroll(child, this, axes)) { 18198 mNestedScrollingParent = p; 18199 p.onNestedScrollAccepted(child, this, axes); 18200 return true; 18201 } 18202 } catch (AbstractMethodError e) { 18203 Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " + 18204 "method onStartNestedScroll", e); 18205 // Allow the search upward to continue 18206 } 18207 if (p instanceof View) { 18208 child = (View) p; 18209 } 18210 p = p.getParent(); 18211 } 18212 } 18213 return false; 18214 } 18215 18216 /** 18217 * Stop a nested scroll in progress. 18218 * 18219 * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p> 18220 * 18221 * @see #startNestedScroll(int) 18222 */ 18223 public void stopNestedScroll() { 18224 if (mNestedScrollingParent != null) { 18225 mNestedScrollingParent.onStopNestedScroll(this); 18226 mNestedScrollingParent = null; 18227 } 18228 } 18229 18230 /** 18231 * Returns true if this view has a nested scrolling parent. 18232 * 18233 * <p>The presence of a nested scrolling parent indicates that this view has initiated 18234 * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p> 18235 * 18236 * @return whether this view has a nested scrolling parent 18237 */ 18238 public boolean hasNestedScrollingParent() { 18239 return mNestedScrollingParent != null; 18240 } 18241 18242 /** 18243 * Dispatch one step of a nested scroll in progress. 18244 * 18245 * <p>Implementations of views that support nested scrolling should call this to report 18246 * info about a scroll in progress to the current nested scrolling parent. If a nested scroll 18247 * is not currently in progress or nested scrolling is not 18248 * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p> 18249 * 18250 * <p>Compatible View implementations should also call 18251 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before 18252 * consuming a component of the scroll event themselves.</p> 18253 * 18254 * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step 18255 * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step 18256 * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view 18257 * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view 18258 * @param offsetInWindow Optional. If not null, on return this will contain the offset 18259 * in local view coordinates of this view from before this operation 18260 * to after it completes. View implementations may use this to adjust 18261 * expected input coordinate tracking. 18262 * @return true if the event was dispatched, false if it could not be dispatched. 18263 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 18264 */ 18265 public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, 18266 int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) { 18267 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18268 if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) { 18269 int startX = 0; 18270 int startY = 0; 18271 if (offsetInWindow != null) { 18272 getLocationInWindow(offsetInWindow); 18273 startX = offsetInWindow[0]; 18274 startY = offsetInWindow[1]; 18275 } 18276 18277 mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed, 18278 dxUnconsumed, dyUnconsumed); 18279 18280 if (offsetInWindow != null) { 18281 getLocationInWindow(offsetInWindow); 18282 offsetInWindow[0] -= startX; 18283 offsetInWindow[1] -= startY; 18284 } 18285 return true; 18286 } else if (offsetInWindow != null) { 18287 // No motion, no dispatch. Keep offsetInWindow up to date. 18288 offsetInWindow[0] = 0; 18289 offsetInWindow[1] = 0; 18290 } 18291 } 18292 return false; 18293 } 18294 18295 /** 18296 * Dispatch one step of a nested scroll in progress before this view consumes any portion of it. 18297 * 18298 * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch. 18299 * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested 18300 * scrolling operation to consume some or all of the scroll operation before the child view 18301 * consumes it.</p> 18302 * 18303 * @param dx Horizontal scroll distance in pixels 18304 * @param dy Vertical scroll distance in pixels 18305 * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx 18306 * and consumed[1] the consumed dy. 18307 * @param offsetInWindow Optional. If not null, on return this will contain the offset 18308 * in local view coordinates of this view from before this operation 18309 * to after it completes. View implementations may use this to adjust 18310 * expected input coordinate tracking. 18311 * @return true if the parent consumed some or all of the scroll delta 18312 * @see #dispatchNestedScroll(int, int, int, int, int[]) 18313 */ 18314 public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) { 18315 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18316 if (dx != 0 || dy != 0) { 18317 int startX = 0; 18318 int startY = 0; 18319 if (offsetInWindow != null) { 18320 getLocationInWindow(offsetInWindow); 18321 startX = offsetInWindow[0]; 18322 startY = offsetInWindow[1]; 18323 } 18324 18325 if (consumed == null) { 18326 if (mTempNestedScrollConsumed == null) { 18327 mTempNestedScrollConsumed = new int[2]; 18328 } 18329 consumed = mTempNestedScrollConsumed; 18330 } 18331 consumed[0] = 0; 18332 consumed[1] = 0; 18333 mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed); 18334 18335 if (offsetInWindow != null) { 18336 getLocationInWindow(offsetInWindow); 18337 offsetInWindow[0] -= startX; 18338 offsetInWindow[1] -= startY; 18339 } 18340 return consumed[0] != 0 || consumed[1] != 0; 18341 } else if (offsetInWindow != null) { 18342 offsetInWindow[0] = 0; 18343 offsetInWindow[1] = 0; 18344 } 18345 } 18346 return false; 18347 } 18348 18349 /** 18350 * Dispatch a fling to a nested scrolling parent. 18351 * 18352 * <p>This method should be used to indicate that a nested scrolling child has detected 18353 * suitable conditions for a fling. Generally this means that a touch scroll has ended with a 18354 * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds 18355 * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity} 18356 * along a scrollable axis.</p> 18357 * 18358 * <p>If a nested scrolling child view would normally fling but it is at the edge of 18359 * its own content, it can use this method to delegate the fling to its nested scrolling 18360 * parent instead. The parent may optionally consume the fling or observe a child fling.</p> 18361 * 18362 * @param velocityX Horizontal fling velocity in pixels per second 18363 * @param velocityY Vertical fling velocity in pixels per second 18364 * @param consumed true if the child consumed the fling, false otherwise 18365 * @return true if the nested scrolling parent consumed or otherwise reacted to the fling 18366 */ 18367 public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) { 18368 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18369 return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed); 18370 } 18371 return false; 18372 } 18373 18374 /** 18375 * Gets a scale factor that determines the distance the view should scroll 18376 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 18377 * @return The vertical scroll scale factor. 18378 * @hide 18379 */ 18380 protected float getVerticalScrollFactor() { 18381 if (mVerticalScrollFactor == 0) { 18382 TypedValue outValue = new TypedValue(); 18383 if (!mContext.getTheme().resolveAttribute( 18384 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 18385 throw new IllegalStateException( 18386 "Expected theme to define listPreferredItemHeight."); 18387 } 18388 mVerticalScrollFactor = outValue.getDimension( 18389 mContext.getResources().getDisplayMetrics()); 18390 } 18391 return mVerticalScrollFactor; 18392 } 18393 18394 /** 18395 * Gets a scale factor that determines the distance the view should scroll 18396 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 18397 * @return The horizontal scroll scale factor. 18398 * @hide 18399 */ 18400 protected float getHorizontalScrollFactor() { 18401 // TODO: Should use something else. 18402 return getVerticalScrollFactor(); 18403 } 18404 18405 /** 18406 * Return the value specifying the text direction or policy that was set with 18407 * {@link #setTextDirection(int)}. 18408 * 18409 * @return the defined text direction. It can be one of: 18410 * 18411 * {@link #TEXT_DIRECTION_INHERIT}, 18412 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18413 * {@link #TEXT_DIRECTION_ANY_RTL}, 18414 * {@link #TEXT_DIRECTION_LTR}, 18415 * {@link #TEXT_DIRECTION_RTL}, 18416 * {@link #TEXT_DIRECTION_LOCALE} 18417 * 18418 * @attr ref android.R.styleable#View_textDirection 18419 * 18420 * @hide 18421 */ 18422 @ViewDebug.ExportedProperty(category = "text", mapping = { 18423 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 18424 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 18425 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 18426 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 18427 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 18428 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 18429 }) 18430 public int getRawTextDirection() { 18431 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 18432 } 18433 18434 /** 18435 * Set the text direction. 18436 * 18437 * @param textDirection the direction to set. Should be one of: 18438 * 18439 * {@link #TEXT_DIRECTION_INHERIT}, 18440 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18441 * {@link #TEXT_DIRECTION_ANY_RTL}, 18442 * {@link #TEXT_DIRECTION_LTR}, 18443 * {@link #TEXT_DIRECTION_RTL}, 18444 * {@link #TEXT_DIRECTION_LOCALE} 18445 * 18446 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution 18447 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will 18448 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 18449 * 18450 * @attr ref android.R.styleable#View_textDirection 18451 */ 18452 public void setTextDirection(int textDirection) { 18453 if (getRawTextDirection() != textDirection) { 18454 // Reset the current text direction and the resolved one 18455 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 18456 resetResolvedTextDirection(); 18457 // Set the new text direction 18458 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 18459 // Do resolution 18460 resolveTextDirection(); 18461 // Notify change 18462 onRtlPropertiesChanged(getLayoutDirection()); 18463 // Refresh 18464 requestLayout(); 18465 invalidate(true); 18466 } 18467 } 18468 18469 /** 18470 * Return the resolved text direction. 18471 * 18472 * @return the resolved text direction. Returns one of: 18473 * 18474 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18475 * {@link #TEXT_DIRECTION_ANY_RTL}, 18476 * {@link #TEXT_DIRECTION_LTR}, 18477 * {@link #TEXT_DIRECTION_RTL}, 18478 * {@link #TEXT_DIRECTION_LOCALE} 18479 * 18480 * @attr ref android.R.styleable#View_textDirection 18481 */ 18482 @ViewDebug.ExportedProperty(category = "text", mapping = { 18483 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 18484 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 18485 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 18486 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 18487 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 18488 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 18489 }) 18490 public int getTextDirection() { 18491 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 18492 } 18493 18494 /** 18495 * Resolve the text direction. 18496 * 18497 * @return true if resolution has been done, false otherwise. 18498 * 18499 * @hide 18500 */ 18501 public boolean resolveTextDirection() { 18502 // Reset any previous text direction resolution 18503 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 18504 18505 if (hasRtlSupport()) { 18506 // Set resolved text direction flag depending on text direction flag 18507 final int textDirection = getRawTextDirection(); 18508 switch(textDirection) { 18509 case TEXT_DIRECTION_INHERIT: 18510 if (!canResolveTextDirection()) { 18511 // We cannot do the resolution if there is no parent, so use the default one 18512 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18513 // Resolution will need to happen again later 18514 return false; 18515 } 18516 18517 // Parent has not yet resolved, so we still return the default 18518 try { 18519 if (!mParent.isTextDirectionResolved()) { 18520 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18521 // Resolution will need to happen again later 18522 return false; 18523 } 18524 } catch (AbstractMethodError e) { 18525 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18526 " does not fully implement ViewParent", e); 18527 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED | 18528 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18529 return true; 18530 } 18531 18532 // Set current resolved direction to the same value as the parent's one 18533 int parentResolvedDirection; 18534 try { 18535 parentResolvedDirection = mParent.getTextDirection(); 18536 } catch (AbstractMethodError e) { 18537 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18538 " does not fully implement ViewParent", e); 18539 parentResolvedDirection = TEXT_DIRECTION_LTR; 18540 } 18541 switch (parentResolvedDirection) { 18542 case TEXT_DIRECTION_FIRST_STRONG: 18543 case TEXT_DIRECTION_ANY_RTL: 18544 case TEXT_DIRECTION_LTR: 18545 case TEXT_DIRECTION_RTL: 18546 case TEXT_DIRECTION_LOCALE: 18547 mPrivateFlags2 |= 18548 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 18549 break; 18550 default: 18551 // Default resolved direction is "first strong" heuristic 18552 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18553 } 18554 break; 18555 case TEXT_DIRECTION_FIRST_STRONG: 18556 case TEXT_DIRECTION_ANY_RTL: 18557 case TEXT_DIRECTION_LTR: 18558 case TEXT_DIRECTION_RTL: 18559 case TEXT_DIRECTION_LOCALE: 18560 // Resolved direction is the same as text direction 18561 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 18562 break; 18563 default: 18564 // Default resolved direction is "first strong" heuristic 18565 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18566 } 18567 } else { 18568 // Default resolved direction is "first strong" heuristic 18569 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18570 } 18571 18572 // Set to resolved 18573 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 18574 return true; 18575 } 18576 18577 /** 18578 * Check if text direction resolution can be done. 18579 * 18580 * @return true if text direction resolution can be done otherwise return false. 18581 */ 18582 public boolean canResolveTextDirection() { 18583 switch (getRawTextDirection()) { 18584 case TEXT_DIRECTION_INHERIT: 18585 if (mParent != null) { 18586 try { 18587 return mParent.canResolveTextDirection(); 18588 } catch (AbstractMethodError e) { 18589 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18590 " does not fully implement ViewParent", e); 18591 } 18592 } 18593 return false; 18594 18595 default: 18596 return true; 18597 } 18598 } 18599 18600 /** 18601 * Reset resolved text direction. Text direction will be resolved during a call to 18602 * {@link #onMeasure(int, int)}. 18603 * 18604 * @hide 18605 */ 18606 public void resetResolvedTextDirection() { 18607 // Reset any previous text direction resolution 18608 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 18609 // Set to default value 18610 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18611 } 18612 18613 /** 18614 * @return true if text direction is inherited. 18615 * 18616 * @hide 18617 */ 18618 public boolean isTextDirectionInherited() { 18619 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 18620 } 18621 18622 /** 18623 * @return true if text direction is resolved. 18624 */ 18625 public boolean isTextDirectionResolved() { 18626 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED; 18627 } 18628 18629 /** 18630 * Return the value specifying the text alignment or policy that was set with 18631 * {@link #setTextAlignment(int)}. 18632 * 18633 * @return the defined text alignment. It can be one of: 18634 * 18635 * {@link #TEXT_ALIGNMENT_INHERIT}, 18636 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18637 * {@link #TEXT_ALIGNMENT_CENTER}, 18638 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18639 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18640 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18641 * {@link #TEXT_ALIGNMENT_VIEW_END} 18642 * 18643 * @attr ref android.R.styleable#View_textAlignment 18644 * 18645 * @hide 18646 */ 18647 @ViewDebug.ExportedProperty(category = "text", mapping = { 18648 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 18649 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 18650 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 18651 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 18652 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 18653 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 18654 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 18655 }) 18656 @TextAlignment 18657 public int getRawTextAlignment() { 18658 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 18659 } 18660 18661 /** 18662 * Set the text alignment. 18663 * 18664 * @param textAlignment The text alignment to set. Should be one of 18665 * 18666 * {@link #TEXT_ALIGNMENT_INHERIT}, 18667 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18668 * {@link #TEXT_ALIGNMENT_CENTER}, 18669 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18670 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18671 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18672 * {@link #TEXT_ALIGNMENT_VIEW_END} 18673 * 18674 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution 18675 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 18676 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}. 18677 * 18678 * @attr ref android.R.styleable#View_textAlignment 18679 */ 18680 public void setTextAlignment(@TextAlignment int textAlignment) { 18681 if (textAlignment != getRawTextAlignment()) { 18682 // Reset the current and resolved text alignment 18683 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 18684 resetResolvedTextAlignment(); 18685 // Set the new text alignment 18686 mPrivateFlags2 |= 18687 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 18688 // Do resolution 18689 resolveTextAlignment(); 18690 // Notify change 18691 onRtlPropertiesChanged(getLayoutDirection()); 18692 // Refresh 18693 requestLayout(); 18694 invalidate(true); 18695 } 18696 } 18697 18698 /** 18699 * Return the resolved text alignment. 18700 * 18701 * @return the resolved text alignment. Returns one of: 18702 * 18703 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18704 * {@link #TEXT_ALIGNMENT_CENTER}, 18705 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18706 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18707 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18708 * {@link #TEXT_ALIGNMENT_VIEW_END} 18709 * 18710 * @attr ref android.R.styleable#View_textAlignment 18711 */ 18712 @ViewDebug.ExportedProperty(category = "text", mapping = { 18713 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 18714 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 18715 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 18716 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 18717 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 18718 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 18719 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 18720 }) 18721 @TextAlignment 18722 public int getTextAlignment() { 18723 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> 18724 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 18725 } 18726 18727 /** 18728 * Resolve the text alignment. 18729 * 18730 * @return true if resolution has been done, false otherwise. 18731 * 18732 * @hide 18733 */ 18734 public boolean resolveTextAlignment() { 18735 // Reset any previous text alignment resolution 18736 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 18737 18738 if (hasRtlSupport()) { 18739 // Set resolved text alignment flag depending on text alignment flag 18740 final int textAlignment = getRawTextAlignment(); 18741 switch (textAlignment) { 18742 case TEXT_ALIGNMENT_INHERIT: 18743 // Check if we can resolve the text alignment 18744 if (!canResolveTextAlignment()) { 18745 // We cannot do the resolution if there is no parent so use the default 18746 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18747 // Resolution will need to happen again later 18748 return false; 18749 } 18750 18751 // Parent has not yet resolved, so we still return the default 18752 try { 18753 if (!mParent.isTextAlignmentResolved()) { 18754 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18755 // Resolution will need to happen again later 18756 return false; 18757 } 18758 } catch (AbstractMethodError e) { 18759 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18760 " does not fully implement ViewParent", e); 18761 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED | 18762 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18763 return true; 18764 } 18765 18766 int parentResolvedTextAlignment; 18767 try { 18768 parentResolvedTextAlignment = mParent.getTextAlignment(); 18769 } catch (AbstractMethodError e) { 18770 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18771 " does not fully implement ViewParent", e); 18772 parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY; 18773 } 18774 switch (parentResolvedTextAlignment) { 18775 case TEXT_ALIGNMENT_GRAVITY: 18776 case TEXT_ALIGNMENT_TEXT_START: 18777 case TEXT_ALIGNMENT_TEXT_END: 18778 case TEXT_ALIGNMENT_CENTER: 18779 case TEXT_ALIGNMENT_VIEW_START: 18780 case TEXT_ALIGNMENT_VIEW_END: 18781 // Resolved text alignment is the same as the parent resolved 18782 // text alignment 18783 mPrivateFlags2 |= 18784 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 18785 break; 18786 default: 18787 // Use default resolved text alignment 18788 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18789 } 18790 break; 18791 case TEXT_ALIGNMENT_GRAVITY: 18792 case TEXT_ALIGNMENT_TEXT_START: 18793 case TEXT_ALIGNMENT_TEXT_END: 18794 case TEXT_ALIGNMENT_CENTER: 18795 case TEXT_ALIGNMENT_VIEW_START: 18796 case TEXT_ALIGNMENT_VIEW_END: 18797 // Resolved text alignment is the same as text alignment 18798 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 18799 break; 18800 default: 18801 // Use default resolved text alignment 18802 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18803 } 18804 } else { 18805 // Use default resolved text alignment 18806 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18807 } 18808 18809 // Set the resolved 18810 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 18811 return true; 18812 } 18813 18814 /** 18815 * Check if text alignment resolution can be done. 18816 * 18817 * @return true if text alignment resolution can be done otherwise return false. 18818 */ 18819 public boolean canResolveTextAlignment() { 18820 switch (getRawTextAlignment()) { 18821 case TEXT_DIRECTION_INHERIT: 18822 if (mParent != null) { 18823 try { 18824 return mParent.canResolveTextAlignment(); 18825 } catch (AbstractMethodError e) { 18826 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18827 " does not fully implement ViewParent", e); 18828 } 18829 } 18830 return false; 18831 18832 default: 18833 return true; 18834 } 18835 } 18836 18837 /** 18838 * Reset resolved text alignment. Text alignment will be resolved during a call to 18839 * {@link #onMeasure(int, int)}. 18840 * 18841 * @hide 18842 */ 18843 public void resetResolvedTextAlignment() { 18844 // Reset any previous text alignment resolution 18845 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 18846 // Set to default 18847 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18848 } 18849 18850 /** 18851 * @return true if text alignment is inherited. 18852 * 18853 * @hide 18854 */ 18855 public boolean isTextAlignmentInherited() { 18856 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 18857 } 18858 18859 /** 18860 * @return true if text alignment is resolved. 18861 */ 18862 public boolean isTextAlignmentResolved() { 18863 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED; 18864 } 18865 18866 /** 18867 * Generate a value suitable for use in {@link #setId(int)}. 18868 * This value will not collide with ID values generated at build time by aapt for R.id. 18869 * 18870 * @return a generated ID value 18871 */ 18872 public static int generateViewId() { 18873 for (;;) { 18874 final int result = sNextGeneratedId.get(); 18875 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 18876 int newValue = result + 1; 18877 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 18878 if (sNextGeneratedId.compareAndSet(result, newValue)) { 18879 return result; 18880 } 18881 } 18882 } 18883 18884 /** 18885 * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions. 18886 * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and 18887 * a normal View or a ViewGroup with 18888 * {@link android.view.ViewGroup#isTransitionGroup()} true. 18889 * @hide 18890 */ 18891 public void captureTransitioningViews(List<View> transitioningViews) { 18892 if (getVisibility() == View.VISIBLE) { 18893 transitioningViews.add(this); 18894 } 18895 } 18896 18897 /** 18898 * Adds all Views that have {@link #getViewName()} non-null to namedElements. 18899 * @param namedElements Will contain all Views in the hierarchy having a view name. 18900 * @hide 18901 */ 18902 public void findNamedViews(Map<String, View> namedElements) { 18903 if (getVisibility() == VISIBLE) { 18904 String viewName = getViewName(); 18905 if (viewName != null) { 18906 namedElements.put(viewName, this); 18907 } 18908 } 18909 } 18910 18911 // 18912 // Properties 18913 // 18914 /** 18915 * A Property wrapper around the <code>alpha</code> functionality handled by the 18916 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 18917 */ 18918 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 18919 @Override 18920 public void setValue(View object, float value) { 18921 object.setAlpha(value); 18922 } 18923 18924 @Override 18925 public Float get(View object) { 18926 return object.getAlpha(); 18927 } 18928 }; 18929 18930 /** 18931 * A Property wrapper around the <code>translationX</code> functionality handled by the 18932 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 18933 */ 18934 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 18935 @Override 18936 public void setValue(View object, float value) { 18937 object.setTranslationX(value); 18938 } 18939 18940 @Override 18941 public Float get(View object) { 18942 return object.getTranslationX(); 18943 } 18944 }; 18945 18946 /** 18947 * A Property wrapper around the <code>translationY</code> functionality handled by the 18948 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 18949 */ 18950 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 18951 @Override 18952 public void setValue(View object, float value) { 18953 object.setTranslationY(value); 18954 } 18955 18956 @Override 18957 public Float get(View object) { 18958 return object.getTranslationY(); 18959 } 18960 }; 18961 18962 /** 18963 * A Property wrapper around the <code>translationZ</code> functionality handled by the 18964 * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods. 18965 */ 18966 public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") { 18967 @Override 18968 public void setValue(View object, float value) { 18969 object.setTranslationZ(value); 18970 } 18971 18972 @Override 18973 public Float get(View object) { 18974 return object.getTranslationZ(); 18975 } 18976 }; 18977 18978 /** 18979 * A Property wrapper around the <code>x</code> functionality handled by the 18980 * {@link View#setX(float)} and {@link View#getX()} methods. 18981 */ 18982 public static final Property<View, Float> X = new FloatProperty<View>("x") { 18983 @Override 18984 public void setValue(View object, float value) { 18985 object.setX(value); 18986 } 18987 18988 @Override 18989 public Float get(View object) { 18990 return object.getX(); 18991 } 18992 }; 18993 18994 /** 18995 * A Property wrapper around the <code>y</code> functionality handled by the 18996 * {@link View#setY(float)} and {@link View#getY()} methods. 18997 */ 18998 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 18999 @Override 19000 public void setValue(View object, float value) { 19001 object.setY(value); 19002 } 19003 19004 @Override 19005 public Float get(View object) { 19006 return object.getY(); 19007 } 19008 }; 19009 19010 /** 19011 * A Property wrapper around the <code>z</code> functionality handled by the 19012 * {@link View#setZ(float)} and {@link View#getZ()} methods. 19013 */ 19014 public static final Property<View, Float> Z = new FloatProperty<View>("z") { 19015 @Override 19016 public void setValue(View object, float value) { 19017 object.setZ(value); 19018 } 19019 19020 @Override 19021 public Float get(View object) { 19022 return object.getZ(); 19023 } 19024 }; 19025 19026 /** 19027 * A Property wrapper around the <code>rotation</code> functionality handled by the 19028 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 19029 */ 19030 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 19031 @Override 19032 public void setValue(View object, float value) { 19033 object.setRotation(value); 19034 } 19035 19036 @Override 19037 public Float get(View object) { 19038 return object.getRotation(); 19039 } 19040 }; 19041 19042 /** 19043 * A Property wrapper around the <code>rotationX</code> functionality handled by the 19044 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 19045 */ 19046 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 19047 @Override 19048 public void setValue(View object, float value) { 19049 object.setRotationX(value); 19050 } 19051 19052 @Override 19053 public Float get(View object) { 19054 return object.getRotationX(); 19055 } 19056 }; 19057 19058 /** 19059 * A Property wrapper around the <code>rotationY</code> functionality handled by the 19060 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 19061 */ 19062 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 19063 @Override 19064 public void setValue(View object, float value) { 19065 object.setRotationY(value); 19066 } 19067 19068 @Override 19069 public Float get(View object) { 19070 return object.getRotationY(); 19071 } 19072 }; 19073 19074 /** 19075 * A Property wrapper around the <code>scaleX</code> functionality handled by the 19076 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 19077 */ 19078 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 19079 @Override 19080 public void setValue(View object, float value) { 19081 object.setScaleX(value); 19082 } 19083 19084 @Override 19085 public Float get(View object) { 19086 return object.getScaleX(); 19087 } 19088 }; 19089 19090 /** 19091 * A Property wrapper around the <code>scaleY</code> functionality handled by the 19092 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 19093 */ 19094 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 19095 @Override 19096 public void setValue(View object, float value) { 19097 object.setScaleY(value); 19098 } 19099 19100 @Override 19101 public Float get(View object) { 19102 return object.getScaleY(); 19103 } 19104 }; 19105 19106 /** 19107 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 19108 * Each MeasureSpec represents a requirement for either the width or the height. 19109 * A MeasureSpec is comprised of a size and a mode. There are three possible 19110 * modes: 19111 * <dl> 19112 * <dt>UNSPECIFIED</dt> 19113 * <dd> 19114 * The parent has not imposed any constraint on the child. It can be whatever size 19115 * it wants. 19116 * </dd> 19117 * 19118 * <dt>EXACTLY</dt> 19119 * <dd> 19120 * The parent has determined an exact size for the child. The child is going to be 19121 * given those bounds regardless of how big it wants to be. 19122 * </dd> 19123 * 19124 * <dt>AT_MOST</dt> 19125 * <dd> 19126 * The child can be as large as it wants up to the specified size. 19127 * </dd> 19128 * </dl> 19129 * 19130 * MeasureSpecs are implemented as ints to reduce object allocation. This class 19131 * is provided to pack and unpack the <size, mode> tuple into the int. 19132 */ 19133 public static class MeasureSpec { 19134 private static final int MODE_SHIFT = 30; 19135 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 19136 19137 /** 19138 * Measure specification mode: The parent has not imposed any constraint 19139 * on the child. It can be whatever size it wants. 19140 */ 19141 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 19142 19143 /** 19144 * Measure specification mode: The parent has determined an exact size 19145 * for the child. The child is going to be given those bounds regardless 19146 * of how big it wants to be. 19147 */ 19148 public static final int EXACTLY = 1 << MODE_SHIFT; 19149 19150 /** 19151 * Measure specification mode: The child can be as large as it wants up 19152 * to the specified size. 19153 */ 19154 public static final int AT_MOST = 2 << MODE_SHIFT; 19155 19156 /** 19157 * Creates a measure specification based on the supplied size and mode. 19158 * 19159 * The mode must always be one of the following: 19160 * <ul> 19161 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 19162 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 19163 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 19164 * </ul> 19165 * 19166 * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's 19167 * implementation was such that the order of arguments did not matter 19168 * and overflow in either value could impact the resulting MeasureSpec. 19169 * {@link android.widget.RelativeLayout} was affected by this bug. 19170 * Apps targeting API levels greater than 17 will get the fixed, more strict 19171 * behavior.</p> 19172 * 19173 * @param size the size of the measure specification 19174 * @param mode the mode of the measure specification 19175 * @return the measure specification based on size and mode 19176 */ 19177 public static int makeMeasureSpec(int size, int mode) { 19178 if (sUseBrokenMakeMeasureSpec) { 19179 return size + mode; 19180 } else { 19181 return (size & ~MODE_MASK) | (mode & MODE_MASK); 19182 } 19183 } 19184 19185 /** 19186 * Extracts the mode from the supplied measure specification. 19187 * 19188 * @param measureSpec the measure specification to extract the mode from 19189 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 19190 * {@link android.view.View.MeasureSpec#AT_MOST} or 19191 * {@link android.view.View.MeasureSpec#EXACTLY} 19192 */ 19193 public static int getMode(int measureSpec) { 19194 return (measureSpec & MODE_MASK); 19195 } 19196 19197 /** 19198 * Extracts the size from the supplied measure specification. 19199 * 19200 * @param measureSpec the measure specification to extract the size from 19201 * @return the size in pixels defined in the supplied measure specification 19202 */ 19203 public static int getSize(int measureSpec) { 19204 return (measureSpec & ~MODE_MASK); 19205 } 19206 19207 static int adjust(int measureSpec, int delta) { 19208 final int mode = getMode(measureSpec); 19209 if (mode == UNSPECIFIED) { 19210 // No need to adjust size for UNSPECIFIED mode. 19211 return makeMeasureSpec(0, UNSPECIFIED); 19212 } 19213 int size = getSize(measureSpec) + delta; 19214 if (size < 0) { 19215 Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size + 19216 ") spec: " + toString(measureSpec) + " delta: " + delta); 19217 size = 0; 19218 } 19219 return makeMeasureSpec(size, mode); 19220 } 19221 19222 /** 19223 * Returns a String representation of the specified measure 19224 * specification. 19225 * 19226 * @param measureSpec the measure specification to convert to a String 19227 * @return a String with the following format: "MeasureSpec: MODE SIZE" 19228 */ 19229 public static String toString(int measureSpec) { 19230 int mode = getMode(measureSpec); 19231 int size = getSize(measureSpec); 19232 19233 StringBuilder sb = new StringBuilder("MeasureSpec: "); 19234 19235 if (mode == UNSPECIFIED) 19236 sb.append("UNSPECIFIED "); 19237 else if (mode == EXACTLY) 19238 sb.append("EXACTLY "); 19239 else if (mode == AT_MOST) 19240 sb.append("AT_MOST "); 19241 else 19242 sb.append(mode).append(" "); 19243 19244 sb.append(size); 19245 return sb.toString(); 19246 } 19247 } 19248 19249 private final class CheckForLongPress implements Runnable { 19250 private int mOriginalWindowAttachCount; 19251 19252 @Override 19253 public void run() { 19254 if (isPressed() && (mParent != null) 19255 && mOriginalWindowAttachCount == mWindowAttachCount) { 19256 if (performLongClick()) { 19257 mHasPerformedLongPress = true; 19258 } 19259 } 19260 } 19261 19262 public void rememberWindowAttachCount() { 19263 mOriginalWindowAttachCount = mWindowAttachCount; 19264 } 19265 } 19266 19267 private final class CheckForTap implements Runnable { 19268 public float x; 19269 public float y; 19270 19271 @Override 19272 public void run() { 19273 mPrivateFlags &= ~PFLAG_PREPRESSED; 19274 setPressed(true, x, y); 19275 checkForLongClick(ViewConfiguration.getTapTimeout()); 19276 } 19277 } 19278 19279 private final class PerformClick implements Runnable { 19280 @Override 19281 public void run() { 19282 performClick(); 19283 } 19284 } 19285 19286 /** @hide */ 19287 public void hackTurnOffWindowResizeAnim(boolean off) { 19288 mAttachInfo.mTurnOffWindowResizeAnim = off; 19289 } 19290 19291 /** 19292 * This method returns a ViewPropertyAnimator object, which can be used to animate 19293 * specific properties on this View. 19294 * 19295 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 19296 */ 19297 public ViewPropertyAnimator animate() { 19298 if (mAnimator == null) { 19299 mAnimator = new ViewPropertyAnimator(this); 19300 } 19301 return mAnimator; 19302 } 19303 19304 /** 19305 * Sets the name of the View to be used to identify Views in Transitions. 19306 * Names should be unique in the View hierarchy. 19307 * 19308 * @param viewName The name of the View to uniquely identify it for Transitions. 19309 */ 19310 public final void setViewName(String viewName) { 19311 mViewName = viewName; 19312 } 19313 19314 /** 19315 * Returns the name of the View to be used to identify Views in Transitions. 19316 * Names should be unique in the View hierarchy. 19317 * 19318 * <p>This returns null if the View has not been given a name.</p> 19319 * 19320 * @return The name used of the View to be used to identify Views in Transitions or null 19321 * if no name has been given. 19322 */ 19323 public String getViewName() { 19324 return mViewName; 19325 } 19326 19327 /** 19328 * Interface definition for a callback to be invoked when a hardware key event is 19329 * dispatched to this view. The callback will be invoked before the key event is 19330 * given to the view. This is only useful for hardware keyboards; a software input 19331 * method has no obligation to trigger this listener. 19332 */ 19333 public interface OnKeyListener { 19334 /** 19335 * Called when a hardware key is dispatched to a view. This allows listeners to 19336 * get a chance to respond before the target view. 19337 * <p>Key presses in software keyboards will generally NOT trigger this method, 19338 * although some may elect to do so in some situations. Do not assume a 19339 * software input method has to be key-based; even if it is, it may use key presses 19340 * in a different way than you expect, so there is no way to reliably catch soft 19341 * input key presses. 19342 * 19343 * @param v The view the key has been dispatched to. 19344 * @param keyCode The code for the physical key that was pressed 19345 * @param event The KeyEvent object containing full information about 19346 * the event. 19347 * @return True if the listener has consumed the event, false otherwise. 19348 */ 19349 boolean onKey(View v, int keyCode, KeyEvent event); 19350 } 19351 19352 /** 19353 * Interface definition for a callback to be invoked when a touch event is 19354 * dispatched to this view. The callback will be invoked before the touch 19355 * event is given to the view. 19356 */ 19357 public interface OnTouchListener { 19358 /** 19359 * Called when a touch event is dispatched to a view. This allows listeners to 19360 * get a chance to respond before the target view. 19361 * 19362 * @param v The view the touch event has been dispatched to. 19363 * @param event The MotionEvent object containing full information about 19364 * the event. 19365 * @return True if the listener has consumed the event, false otherwise. 19366 */ 19367 boolean onTouch(View v, MotionEvent event); 19368 } 19369 19370 /** 19371 * Interface definition for a callback to be invoked when a hover event is 19372 * dispatched to this view. The callback will be invoked before the hover 19373 * event is given to the view. 19374 */ 19375 public interface OnHoverListener { 19376 /** 19377 * Called when a hover event is dispatched to a view. This allows listeners to 19378 * get a chance to respond before the target view. 19379 * 19380 * @param v The view the hover event has been dispatched to. 19381 * @param event The MotionEvent object containing full information about 19382 * the event. 19383 * @return True if the listener has consumed the event, false otherwise. 19384 */ 19385 boolean onHover(View v, MotionEvent event); 19386 } 19387 19388 /** 19389 * Interface definition for a callback to be invoked when a generic motion event is 19390 * dispatched to this view. The callback will be invoked before the generic motion 19391 * event is given to the view. 19392 */ 19393 public interface OnGenericMotionListener { 19394 /** 19395 * Called when a generic motion event is dispatched to a view. This allows listeners to 19396 * get a chance to respond before the target view. 19397 * 19398 * @param v The view the generic motion event has been dispatched to. 19399 * @param event The MotionEvent object containing full information about 19400 * the event. 19401 * @return True if the listener has consumed the event, false otherwise. 19402 */ 19403 boolean onGenericMotion(View v, MotionEvent event); 19404 } 19405 19406 /** 19407 * Interface definition for a callback to be invoked when a view has been clicked and held. 19408 */ 19409 public interface OnLongClickListener { 19410 /** 19411 * Called when a view has been clicked and held. 19412 * 19413 * @param v The view that was clicked and held. 19414 * 19415 * @return true if the callback consumed the long click, false otherwise. 19416 */ 19417 boolean onLongClick(View v); 19418 } 19419 19420 /** 19421 * Interface definition for a callback to be invoked when a drag is being dispatched 19422 * to this view. The callback will be invoked before the hosting view's own 19423 * onDrag(event) method. If the listener wants to fall back to the hosting view's 19424 * onDrag(event) behavior, it should return 'false' from this callback. 19425 * 19426 * <div class="special reference"> 19427 * <h3>Developer Guides</h3> 19428 * <p>For a guide to implementing drag and drop features, read the 19429 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 19430 * </div> 19431 */ 19432 public interface OnDragListener { 19433 /** 19434 * Called when a drag event is dispatched to a view. This allows listeners 19435 * to get a chance to override base View behavior. 19436 * 19437 * @param v The View that received the drag event. 19438 * @param event The {@link android.view.DragEvent} object for the drag event. 19439 * @return {@code true} if the drag event was handled successfully, or {@code false} 19440 * if the drag event was not handled. Note that {@code false} will trigger the View 19441 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 19442 */ 19443 boolean onDrag(View v, DragEvent event); 19444 } 19445 19446 /** 19447 * Interface definition for a callback to be invoked when the focus state of 19448 * a view changed. 19449 */ 19450 public interface OnFocusChangeListener { 19451 /** 19452 * Called when the focus state of a view has changed. 19453 * 19454 * @param v The view whose state has changed. 19455 * @param hasFocus The new focus state of v. 19456 */ 19457 void onFocusChange(View v, boolean hasFocus); 19458 } 19459 19460 /** 19461 * Interface definition for a callback to be invoked when a view is clicked. 19462 */ 19463 public interface OnClickListener { 19464 /** 19465 * Called when a view has been clicked. 19466 * 19467 * @param v The view that was clicked. 19468 */ 19469 void onClick(View v); 19470 } 19471 19472 /** 19473 * Interface definition for a callback to be invoked when the context menu 19474 * for this view is being built. 19475 */ 19476 public interface OnCreateContextMenuListener { 19477 /** 19478 * Called when the context menu for this view is being built. It is not 19479 * safe to hold onto the menu after this method returns. 19480 * 19481 * @param menu The context menu that is being built 19482 * @param v The view for which the context menu is being built 19483 * @param menuInfo Extra information about the item for which the 19484 * context menu should be shown. This information will vary 19485 * depending on the class of v. 19486 */ 19487 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 19488 } 19489 19490 /** 19491 * Interface definition for a callback to be invoked when the status bar changes 19492 * visibility. This reports <strong>global</strong> changes to the system UI 19493 * state, not what the application is requesting. 19494 * 19495 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 19496 */ 19497 public interface OnSystemUiVisibilityChangeListener { 19498 /** 19499 * Called when the status bar changes visibility because of a call to 19500 * {@link View#setSystemUiVisibility(int)}. 19501 * 19502 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 19503 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 19504 * This tells you the <strong>global</strong> state of these UI visibility 19505 * flags, not what your app is currently applying. 19506 */ 19507 public void onSystemUiVisibilityChange(int visibility); 19508 } 19509 19510 /** 19511 * Interface definition for a callback to be invoked when this view is attached 19512 * or detached from its window. 19513 */ 19514 public interface OnAttachStateChangeListener { 19515 /** 19516 * Called when the view is attached to a window. 19517 * @param v The view that was attached 19518 */ 19519 public void onViewAttachedToWindow(View v); 19520 /** 19521 * Called when the view is detached from a window. 19522 * @param v The view that was detached 19523 */ 19524 public void onViewDetachedFromWindow(View v); 19525 } 19526 19527 /** 19528 * Listener for applying window insets on a view in a custom way. 19529 * 19530 * <p>Apps may choose to implement this interface if they want to apply custom policy 19531 * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener 19532 * is set, its 19533 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 19534 * method will be called instead of the View's own 19535 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener 19536 * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply 19537 * the View's normal behavior as part of its own.</p> 19538 */ 19539 public interface OnApplyWindowInsetsListener { 19540 /** 19541 * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set} 19542 * on a View, this listener method will be called instead of the view's own 19543 * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 19544 * 19545 * @param v The view applying window insets 19546 * @param insets The insets to apply 19547 * @return The insets supplied, minus any insets that were consumed 19548 */ 19549 public WindowInsets onApplyWindowInsets(View v, WindowInsets insets); 19550 } 19551 19552 private final class UnsetPressedState implements Runnable { 19553 @Override 19554 public void run() { 19555 setPressed(false); 19556 } 19557 } 19558 19559 /** 19560 * Base class for derived classes that want to save and restore their own 19561 * state in {@link android.view.View#onSaveInstanceState()}. 19562 */ 19563 public static class BaseSavedState extends AbsSavedState { 19564 /** 19565 * Constructor used when reading from a parcel. Reads the state of the superclass. 19566 * 19567 * @param source 19568 */ 19569 public BaseSavedState(Parcel source) { 19570 super(source); 19571 } 19572 19573 /** 19574 * Constructor called by derived classes when creating their SavedState objects 19575 * 19576 * @param superState The state of the superclass of this view 19577 */ 19578 public BaseSavedState(Parcelable superState) { 19579 super(superState); 19580 } 19581 19582 public static final Parcelable.Creator<BaseSavedState> CREATOR = 19583 new Parcelable.Creator<BaseSavedState>() { 19584 public BaseSavedState createFromParcel(Parcel in) { 19585 return new BaseSavedState(in); 19586 } 19587 19588 public BaseSavedState[] newArray(int size) { 19589 return new BaseSavedState[size]; 19590 } 19591 }; 19592 } 19593 19594 /** 19595 * A set of information given to a view when it is attached to its parent 19596 * window. 19597 */ 19598 final static class AttachInfo { 19599 interface Callbacks { 19600 void playSoundEffect(int effectId); 19601 boolean performHapticFeedback(int effectId, boolean always); 19602 } 19603 19604 /** 19605 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 19606 * to a Handler. This class contains the target (View) to invalidate and 19607 * the coordinates of the dirty rectangle. 19608 * 19609 * For performance purposes, this class also implements a pool of up to 19610 * POOL_LIMIT objects that get reused. This reduces memory allocations 19611 * whenever possible. 19612 */ 19613 static class InvalidateInfo { 19614 private static final int POOL_LIMIT = 10; 19615 19616 private static final SynchronizedPool<InvalidateInfo> sPool = 19617 new SynchronizedPool<InvalidateInfo>(POOL_LIMIT); 19618 19619 View target; 19620 19621 int left; 19622 int top; 19623 int right; 19624 int bottom; 19625 19626 public static InvalidateInfo obtain() { 19627 InvalidateInfo instance = sPool.acquire(); 19628 return (instance != null) ? instance : new InvalidateInfo(); 19629 } 19630 19631 public void recycle() { 19632 target = null; 19633 sPool.release(this); 19634 } 19635 } 19636 19637 final IWindowSession mSession; 19638 19639 final IWindow mWindow; 19640 19641 final IBinder mWindowToken; 19642 19643 final Display mDisplay; 19644 19645 final Callbacks mRootCallbacks; 19646 19647 IWindowId mIWindowId; 19648 WindowId mWindowId; 19649 19650 /** 19651 * The top view of the hierarchy. 19652 */ 19653 View mRootView; 19654 19655 IBinder mPanelParentWindowToken; 19656 19657 boolean mHardwareAccelerated; 19658 boolean mHardwareAccelerationRequested; 19659 HardwareRenderer mHardwareRenderer; 19660 19661 /** 19662 * The state of the display to which the window is attached, as reported 19663 * by {@link Display#getState()}. Note that the display state constants 19664 * declared by {@link Display} do not exactly line up with the screen state 19665 * constants declared by {@link View} (there are more display states than 19666 * screen states). 19667 */ 19668 int mDisplayState = Display.STATE_UNKNOWN; 19669 19670 /** 19671 * Scale factor used by the compatibility mode 19672 */ 19673 float mApplicationScale; 19674 19675 /** 19676 * Indicates whether the application is in compatibility mode 19677 */ 19678 boolean mScalingRequired; 19679 19680 /** 19681 * If set, ViewRootImpl doesn't use its lame animation for when the window resizes. 19682 */ 19683 boolean mTurnOffWindowResizeAnim; 19684 19685 /** 19686 * Left position of this view's window 19687 */ 19688 int mWindowLeft; 19689 19690 /** 19691 * Top position of this view's window 19692 */ 19693 int mWindowTop; 19694 19695 /** 19696 * Indicates whether views need to use 32-bit drawing caches 19697 */ 19698 boolean mUse32BitDrawingCache; 19699 19700 /** 19701 * For windows that are full-screen but using insets to layout inside 19702 * of the screen areas, these are the current insets to appear inside 19703 * the overscan area of the display. 19704 */ 19705 final Rect mOverscanInsets = new Rect(); 19706 19707 /** 19708 * For windows that are full-screen but using insets to layout inside 19709 * of the screen decorations, these are the current insets for the 19710 * content of the window. 19711 */ 19712 final Rect mContentInsets = new Rect(); 19713 19714 /** 19715 * For windows that are full-screen but using insets to layout inside 19716 * of the screen decorations, these are the current insets for the 19717 * actual visible parts of the window. 19718 */ 19719 final Rect mVisibleInsets = new Rect(); 19720 19721 /** 19722 * The internal insets given by this window. This value is 19723 * supplied by the client (through 19724 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 19725 * be given to the window manager when changed to be used in laying 19726 * out windows behind it. 19727 */ 19728 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 19729 = new ViewTreeObserver.InternalInsetsInfo(); 19730 19731 /** 19732 * Set to true when mGivenInternalInsets is non-empty. 19733 */ 19734 boolean mHasNonEmptyGivenInternalInsets; 19735 19736 /** 19737 * All views in the window's hierarchy that serve as scroll containers, 19738 * used to determine if the window can be resized or must be panned 19739 * to adjust for a soft input area. 19740 */ 19741 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 19742 19743 final KeyEvent.DispatcherState mKeyDispatchState 19744 = new KeyEvent.DispatcherState(); 19745 19746 /** 19747 * Indicates whether the view's window currently has the focus. 19748 */ 19749 boolean mHasWindowFocus; 19750 19751 /** 19752 * The current visibility of the window. 19753 */ 19754 int mWindowVisibility; 19755 19756 /** 19757 * Indicates the time at which drawing started to occur. 19758 */ 19759 long mDrawingTime; 19760 19761 /** 19762 * Indicates whether or not ignoring the DIRTY_MASK flags. 19763 */ 19764 boolean mIgnoreDirtyState; 19765 19766 /** 19767 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 19768 * to avoid clearing that flag prematurely. 19769 */ 19770 boolean mSetIgnoreDirtyState = false; 19771 19772 /** 19773 * Indicates whether the view's window is currently in touch mode. 19774 */ 19775 boolean mInTouchMode; 19776 19777 /** 19778 * Indicates whether the view has requested unbuffered input dispatching for the current 19779 * event stream. 19780 */ 19781 boolean mUnbufferedDispatchRequested; 19782 19783 /** 19784 * Indicates that ViewAncestor should trigger a global layout change 19785 * the next time it performs a traversal 19786 */ 19787 boolean mRecomputeGlobalAttributes; 19788 19789 /** 19790 * Always report new attributes at next traversal. 19791 */ 19792 boolean mForceReportNewAttributes; 19793 19794 /** 19795 * Set during a traveral if any views want to keep the screen on. 19796 */ 19797 boolean mKeepScreenOn; 19798 19799 /** 19800 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 19801 */ 19802 int mSystemUiVisibility; 19803 19804 /** 19805 * Hack to force certain system UI visibility flags to be cleared. 19806 */ 19807 int mDisabledSystemUiVisibility; 19808 19809 /** 19810 * Last global system UI visibility reported by the window manager. 19811 */ 19812 int mGlobalSystemUiVisibility; 19813 19814 /** 19815 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 19816 * attached. 19817 */ 19818 boolean mHasSystemUiListeners; 19819 19820 /** 19821 * Set if the window has requested to extend into the overscan region 19822 * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN. 19823 */ 19824 boolean mOverscanRequested; 19825 19826 /** 19827 * Set if the visibility of any views has changed. 19828 */ 19829 boolean mViewVisibilityChanged; 19830 19831 /** 19832 * Set to true if a view has been scrolled. 19833 */ 19834 boolean mViewScrollChanged; 19835 19836 /** 19837 * Global to the view hierarchy used as a temporary for dealing with 19838 * x/y points in the transparent region computations. 19839 */ 19840 final int[] mTransparentLocation = new int[2]; 19841 19842 /** 19843 * Global to the view hierarchy used as a temporary for dealing with 19844 * x/y points in the ViewGroup.invalidateChild implementation. 19845 */ 19846 final int[] mInvalidateChildLocation = new int[2]; 19847 19848 19849 /** 19850 * Global to the view hierarchy used as a temporary for dealing with 19851 * x/y location when view is transformed. 19852 */ 19853 final float[] mTmpTransformLocation = new float[2]; 19854 19855 /** 19856 * The view tree observer used to dispatch global events like 19857 * layout, pre-draw, touch mode change, etc. 19858 */ 19859 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 19860 19861 /** 19862 * A Canvas used by the view hierarchy to perform bitmap caching. 19863 */ 19864 Canvas mCanvas; 19865 19866 /** 19867 * The view root impl. 19868 */ 19869 final ViewRootImpl mViewRootImpl; 19870 19871 /** 19872 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 19873 * handler can be used to pump events in the UI events queue. 19874 */ 19875 final Handler mHandler; 19876 19877 /** 19878 * Temporary for use in computing invalidate rectangles while 19879 * calling up the hierarchy. 19880 */ 19881 final Rect mTmpInvalRect = new Rect(); 19882 19883 /** 19884 * Temporary for use in computing hit areas with transformed views 19885 */ 19886 final RectF mTmpTransformRect = new RectF(); 19887 19888 /** 19889 * Temporary for use in transforming invalidation rect 19890 */ 19891 final Matrix mTmpMatrix = new Matrix(); 19892 19893 /** 19894 * Temporary for use in transforming invalidation rect 19895 */ 19896 final Transformation mTmpTransformation = new Transformation(); 19897 19898 /** 19899 * Temporary list for use in collecting focusable descendents of a view. 19900 */ 19901 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 19902 19903 /** 19904 * The id of the window for accessibility purposes. 19905 */ 19906 int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 19907 19908 /** 19909 * Flags related to accessibility processing. 19910 * 19911 * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 19912 * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS 19913 */ 19914 int mAccessibilityFetchFlags; 19915 19916 /** 19917 * The drawable for highlighting accessibility focus. 19918 */ 19919 Drawable mAccessibilityFocusDrawable; 19920 19921 /** 19922 * Show where the margins, bounds and layout bounds are for each view. 19923 */ 19924 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 19925 19926 /** 19927 * Point used to compute visible regions. 19928 */ 19929 final Point mPoint = new Point(); 19930 19931 /** 19932 * Used to track which View originated a requestLayout() call, used when 19933 * requestLayout() is called during layout. 19934 */ 19935 View mViewRequestingLayout; 19936 19937 /** 19938 * Creates a new set of attachment information with the specified 19939 * events handler and thread. 19940 * 19941 * @param handler the events handler the view must use 19942 */ 19943 AttachInfo(IWindowSession session, IWindow window, Display display, 19944 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) { 19945 mSession = session; 19946 mWindow = window; 19947 mWindowToken = window.asBinder(); 19948 mDisplay = display; 19949 mViewRootImpl = viewRootImpl; 19950 mHandler = handler; 19951 mRootCallbacks = effectPlayer; 19952 } 19953 } 19954 19955 /** 19956 * <p>ScrollabilityCache holds various fields used by a View when scrolling 19957 * is supported. This avoids keeping too many unused fields in most 19958 * instances of View.</p> 19959 */ 19960 private static class ScrollabilityCache implements Runnable { 19961 19962 /** 19963 * Scrollbars are not visible 19964 */ 19965 public static final int OFF = 0; 19966 19967 /** 19968 * Scrollbars are visible 19969 */ 19970 public static final int ON = 1; 19971 19972 /** 19973 * Scrollbars are fading away 19974 */ 19975 public static final int FADING = 2; 19976 19977 public boolean fadeScrollBars; 19978 19979 public int fadingEdgeLength; 19980 public int scrollBarDefaultDelayBeforeFade; 19981 public int scrollBarFadeDuration; 19982 19983 public int scrollBarSize; 19984 public ScrollBarDrawable scrollBar; 19985 public float[] interpolatorValues; 19986 public View host; 19987 19988 public final Paint paint; 19989 public final Matrix matrix; 19990 public Shader shader; 19991 19992 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 19993 19994 private static final float[] OPAQUE = { 255 }; 19995 private static final float[] TRANSPARENT = { 0.0f }; 19996 19997 /** 19998 * When fading should start. This time moves into the future every time 19999 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 20000 */ 20001 public long fadeStartTime; 20002 20003 20004 /** 20005 * The current state of the scrollbars: ON, OFF, or FADING 20006 */ 20007 public int state = OFF; 20008 20009 private int mLastColor; 20010 20011 public ScrollabilityCache(ViewConfiguration configuration, View host) { 20012 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 20013 scrollBarSize = configuration.getScaledScrollBarSize(); 20014 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 20015 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 20016 20017 paint = new Paint(); 20018 matrix = new Matrix(); 20019 // use use a height of 1, and then wack the matrix each time we 20020 // actually use it. 20021 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 20022 paint.setShader(shader); 20023 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 20024 20025 this.host = host; 20026 } 20027 20028 public void setFadeColor(int color) { 20029 if (color != mLastColor) { 20030 mLastColor = color; 20031 20032 if (color != 0) { 20033 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 20034 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 20035 paint.setShader(shader); 20036 // Restore the default transfer mode (src_over) 20037 paint.setXfermode(null); 20038 } else { 20039 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 20040 paint.setShader(shader); 20041 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 20042 } 20043 } 20044 } 20045 20046 public void run() { 20047 long now = AnimationUtils.currentAnimationTimeMillis(); 20048 if (now >= fadeStartTime) { 20049 20050 // the animation fades the scrollbars out by changing 20051 // the opacity (alpha) from fully opaque to fully 20052 // transparent 20053 int nextFrame = (int) now; 20054 int framesCount = 0; 20055 20056 Interpolator interpolator = scrollBarInterpolator; 20057 20058 // Start opaque 20059 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 20060 20061 // End transparent 20062 nextFrame += scrollBarFadeDuration; 20063 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 20064 20065 state = FADING; 20066 20067 // Kick off the fade animation 20068 host.invalidate(true); 20069 } 20070 } 20071 } 20072 20073 /** 20074 * Resuable callback for sending 20075 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 20076 */ 20077 private class SendViewScrolledAccessibilityEvent implements Runnable { 20078 public volatile boolean mIsPending; 20079 20080 public void run() { 20081 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 20082 mIsPending = false; 20083 } 20084 } 20085 20086 /** 20087 * <p> 20088 * This class represents a delegate that can be registered in a {@link View} 20089 * to enhance accessibility support via composition rather via inheritance. 20090 * It is specifically targeted to widget developers that extend basic View 20091 * classes i.e. classes in package android.view, that would like their 20092 * applications to be backwards compatible. 20093 * </p> 20094 * <div class="special reference"> 20095 * <h3>Developer Guides</h3> 20096 * <p>For more information about making applications accessible, read the 20097 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 20098 * developer guide.</p> 20099 * </div> 20100 * <p> 20101 * A scenario in which a developer would like to use an accessibility delegate 20102 * is overriding a method introduced in a later API version then the minimal API 20103 * version supported by the application. For example, the method 20104 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 20105 * in API version 4 when the accessibility APIs were first introduced. If a 20106 * developer would like his application to run on API version 4 devices (assuming 20107 * all other APIs used by the application are version 4 or lower) and take advantage 20108 * of this method, instead of overriding the method which would break the application's 20109 * backwards compatibility, he can override the corresponding method in this 20110 * delegate and register the delegate in the target View if the API version of 20111 * the system is high enough i.e. the API version is same or higher to the API 20112 * version that introduced 20113 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 20114 * </p> 20115 * <p> 20116 * Here is an example implementation: 20117 * </p> 20118 * <code><pre><p> 20119 * if (Build.VERSION.SDK_INT >= 14) { 20120 * // If the API version is equal of higher than the version in 20121 * // which onInitializeAccessibilityNodeInfo was introduced we 20122 * // register a delegate with a customized implementation. 20123 * View view = findViewById(R.id.view_id); 20124 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 20125 * public void onInitializeAccessibilityNodeInfo(View host, 20126 * AccessibilityNodeInfo info) { 20127 * // Let the default implementation populate the info. 20128 * super.onInitializeAccessibilityNodeInfo(host, info); 20129 * // Set some other information. 20130 * info.setEnabled(host.isEnabled()); 20131 * } 20132 * }); 20133 * } 20134 * </code></pre></p> 20135 * <p> 20136 * This delegate contains methods that correspond to the accessibility methods 20137 * in View. If a delegate has been specified the implementation in View hands 20138 * off handling to the corresponding method in this delegate. The default 20139 * implementation the delegate methods behaves exactly as the corresponding 20140 * method in View for the case of no accessibility delegate been set. Hence, 20141 * to customize the behavior of a View method, clients can override only the 20142 * corresponding delegate method without altering the behavior of the rest 20143 * accessibility related methods of the host view. 20144 * </p> 20145 */ 20146 public static class AccessibilityDelegate { 20147 20148 /** 20149 * Sends an accessibility event of the given type. If accessibility is not 20150 * enabled this method has no effect. 20151 * <p> 20152 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 20153 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 20154 * been set. 20155 * </p> 20156 * 20157 * @param host The View hosting the delegate. 20158 * @param eventType The type of the event to send. 20159 * 20160 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 20161 */ 20162 public void sendAccessibilityEvent(View host, int eventType) { 20163 host.sendAccessibilityEventInternal(eventType); 20164 } 20165 20166 /** 20167 * Performs the specified accessibility action on the view. For 20168 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 20169 * <p> 20170 * The default implementation behaves as 20171 * {@link View#performAccessibilityAction(int, Bundle) 20172 * View#performAccessibilityAction(int, Bundle)} for the case of 20173 * no accessibility delegate been set. 20174 * </p> 20175 * 20176 * @param action The action to perform. 20177 * @return Whether the action was performed. 20178 * 20179 * @see View#performAccessibilityAction(int, Bundle) 20180 * View#performAccessibilityAction(int, Bundle) 20181 */ 20182 public boolean performAccessibilityAction(View host, int action, Bundle args) { 20183 return host.performAccessibilityActionInternal(action, args); 20184 } 20185 20186 /** 20187 * Sends an accessibility event. This method behaves exactly as 20188 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 20189 * empty {@link AccessibilityEvent} and does not perform a check whether 20190 * accessibility is enabled. 20191 * <p> 20192 * The default implementation behaves as 20193 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20194 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 20195 * the case of no accessibility delegate been set. 20196 * </p> 20197 * 20198 * @param host The View hosting the delegate. 20199 * @param event The event to send. 20200 * 20201 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20202 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20203 */ 20204 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 20205 host.sendAccessibilityEventUncheckedInternal(event); 20206 } 20207 20208 /** 20209 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 20210 * to its children for adding their text content to the event. 20211 * <p> 20212 * The default implementation behaves as 20213 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20214 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 20215 * the case of no accessibility delegate been set. 20216 * </p> 20217 * 20218 * @param host The View hosting the delegate. 20219 * @param event The event. 20220 * @return True if the event population was completed. 20221 * 20222 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20223 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20224 */ 20225 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 20226 return host.dispatchPopulateAccessibilityEventInternal(event); 20227 } 20228 20229 /** 20230 * Gives a chance to the host View to populate the accessibility event with its 20231 * text content. 20232 * <p> 20233 * The default implementation behaves as 20234 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 20235 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 20236 * the case of no accessibility delegate been set. 20237 * </p> 20238 * 20239 * @param host The View hosting the delegate. 20240 * @param event The accessibility event which to populate. 20241 * 20242 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 20243 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 20244 */ 20245 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 20246 host.onPopulateAccessibilityEventInternal(event); 20247 } 20248 20249 /** 20250 * Initializes an {@link AccessibilityEvent} with information about the 20251 * the host View which is the event source. 20252 * <p> 20253 * The default implementation behaves as 20254 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 20255 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 20256 * the case of no accessibility delegate been set. 20257 * </p> 20258 * 20259 * @param host The View hosting the delegate. 20260 * @param event The event to initialize. 20261 * 20262 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 20263 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 20264 */ 20265 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 20266 host.onInitializeAccessibilityEventInternal(event); 20267 } 20268 20269 /** 20270 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 20271 * <p> 20272 * The default implementation behaves as 20273 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20274 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 20275 * the case of no accessibility delegate been set. 20276 * </p> 20277 * 20278 * @param host The View hosting the delegate. 20279 * @param info The instance to initialize. 20280 * 20281 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20282 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20283 */ 20284 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 20285 host.onInitializeAccessibilityNodeInfoInternal(info); 20286 } 20287 20288 /** 20289 * Called when a child of the host View has requested sending an 20290 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 20291 * to augment the event. 20292 * <p> 20293 * The default implementation behaves as 20294 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20295 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 20296 * the case of no accessibility delegate been set. 20297 * </p> 20298 * 20299 * @param host The View hosting the delegate. 20300 * @param child The child which requests sending the event. 20301 * @param event The event to be sent. 20302 * @return True if the event should be sent 20303 * 20304 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20305 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20306 */ 20307 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 20308 AccessibilityEvent event) { 20309 return host.onRequestSendAccessibilityEventInternal(child, event); 20310 } 20311 20312 /** 20313 * Gets the provider for managing a virtual view hierarchy rooted at this View 20314 * and reported to {@link android.accessibilityservice.AccessibilityService}s 20315 * that explore the window content. 20316 * <p> 20317 * The default implementation behaves as 20318 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 20319 * the case of no accessibility delegate been set. 20320 * </p> 20321 * 20322 * @return The provider. 20323 * 20324 * @see AccessibilityNodeProvider 20325 */ 20326 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 20327 return null; 20328 } 20329 20330 /** 20331 * Returns an {@link AccessibilityNodeInfo} representing the host view from the 20332 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 20333 * This method is responsible for obtaining an accessibility node info from a 20334 * pool of reusable instances and calling 20335 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host 20336 * view to initialize the former. 20337 * <p> 20338 * <strong>Note:</strong> The client is responsible for recycling the obtained 20339 * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object 20340 * creation. 20341 * </p> 20342 * <p> 20343 * The default implementation behaves as 20344 * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for 20345 * the case of no accessibility delegate been set. 20346 * </p> 20347 * @return A populated {@link AccessibilityNodeInfo}. 20348 * 20349 * @see AccessibilityNodeInfo 20350 * 20351 * @hide 20352 */ 20353 public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) { 20354 return host.createAccessibilityNodeInfoInternal(); 20355 } 20356 } 20357 20358 private class MatchIdPredicate implements Predicate<View> { 20359 public int mId; 20360 20361 @Override 20362 public boolean apply(View view) { 20363 return (view.mID == mId); 20364 } 20365 } 20366 20367 private class MatchLabelForPredicate implements Predicate<View> { 20368 private int mLabeledId; 20369 20370 @Override 20371 public boolean apply(View view) { 20372 return (view.mLabelForId == mLabeledId); 20373 } 20374 } 20375 20376 private class SendViewStateChangedAccessibilityEvent implements Runnable { 20377 private int mChangeTypes = 0; 20378 private boolean mPosted; 20379 private boolean mPostedWithDelay; 20380 private long mLastEventTimeMillis; 20381 20382 @Override 20383 public void run() { 20384 mPosted = false; 20385 mPostedWithDelay = false; 20386 mLastEventTimeMillis = SystemClock.uptimeMillis(); 20387 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 20388 final AccessibilityEvent event = AccessibilityEvent.obtain(); 20389 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 20390 event.setContentChangeTypes(mChangeTypes); 20391 sendAccessibilityEventUnchecked(event); 20392 } 20393 mChangeTypes = 0; 20394 } 20395 20396 public void runOrPost(int changeType) { 20397 mChangeTypes |= changeType; 20398 20399 // If this is a live region or the child of a live region, collect 20400 // all events from this frame and send them on the next frame. 20401 if (inLiveRegion()) { 20402 // If we're already posted with a delay, remove that. 20403 if (mPostedWithDelay) { 20404 removeCallbacks(this); 20405 mPostedWithDelay = false; 20406 } 20407 // Only post if we're not already posted. 20408 if (!mPosted) { 20409 post(this); 20410 mPosted = true; 20411 } 20412 return; 20413 } 20414 20415 if (mPosted) { 20416 return; 20417 } 20418 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 20419 final long minEventIntevalMillis = 20420 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 20421 if (timeSinceLastMillis >= minEventIntevalMillis) { 20422 removeCallbacks(this); 20423 run(); 20424 } else { 20425 postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 20426 mPosted = true; 20427 mPostedWithDelay = true; 20428 } 20429 } 20430 } 20431 20432 private boolean inLiveRegion() { 20433 if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) { 20434 return true; 20435 } 20436 20437 ViewParent parent = getParent(); 20438 while (parent instanceof View) { 20439 if (((View) parent).getAccessibilityLiveRegion() 20440 != View.ACCESSIBILITY_LIVE_REGION_NONE) { 20441 return true; 20442 } 20443 parent = parent.getParent(); 20444 } 20445 20446 return false; 20447 } 20448 20449 /** 20450 * Dump all private flags in readable format, useful for documentation and 20451 * sanity checking. 20452 */ 20453 private static void dumpFlags() { 20454 final HashMap<String, String> found = Maps.newHashMap(); 20455 try { 20456 for (Field field : View.class.getDeclaredFields()) { 20457 final int modifiers = field.getModifiers(); 20458 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 20459 if (field.getType().equals(int.class)) { 20460 final int value = field.getInt(null); 20461 dumpFlag(found, field.getName(), value); 20462 } else if (field.getType().equals(int[].class)) { 20463 final int[] values = (int[]) field.get(null); 20464 for (int i = 0; i < values.length; i++) { 20465 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 20466 } 20467 } 20468 } 20469 } 20470 } catch (IllegalAccessException e) { 20471 throw new RuntimeException(e); 20472 } 20473 20474 final ArrayList<String> keys = Lists.newArrayList(); 20475 keys.addAll(found.keySet()); 20476 Collections.sort(keys); 20477 for (String key : keys) { 20478 Log.d(VIEW_LOG_TAG, found.get(key)); 20479 } 20480 } 20481 20482 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 20483 // Sort flags by prefix, then by bits, always keeping unique keys 20484 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 20485 final int prefix = name.indexOf('_'); 20486 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 20487 final String output = bits + " " + name; 20488 found.put(key, output); 20489 } 20490} 20491