View.java revision fb5899d6e08c231901cbaefa8156b27ff92b8801
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.StateListAnimator; 21import android.annotation.IntDef; 22import android.annotation.NonNull; 23import android.annotation.Nullable; 24import android.content.ClipData; 25import android.content.Context; 26import android.content.res.ColorStateList; 27import android.content.res.Configuration; 28import android.content.res.Resources; 29import android.content.res.TypedArray; 30import android.graphics.Bitmap; 31import android.graphics.Canvas; 32import android.graphics.Insets; 33import android.graphics.Interpolator; 34import android.graphics.LinearGradient; 35import android.graphics.Matrix; 36import android.graphics.Outline; 37import android.graphics.Paint; 38import android.graphics.PixelFormat; 39import android.graphics.Point; 40import android.graphics.PorterDuff; 41import android.graphics.PorterDuffXfermode; 42import android.graphics.Rect; 43import android.graphics.RectF; 44import android.graphics.Region; 45import android.graphics.Shader; 46import android.graphics.drawable.ColorDrawable; 47import android.graphics.drawable.Drawable; 48import android.hardware.display.DisplayManagerGlobal; 49import android.os.Bundle; 50import android.os.Handler; 51import android.os.IBinder; 52import android.os.Parcel; 53import android.os.Parcelable; 54import android.os.RemoteException; 55import android.os.SystemClock; 56import android.os.SystemProperties; 57import android.text.TextUtils; 58import android.util.AttributeSet; 59import android.util.FloatProperty; 60import android.util.LayoutDirection; 61import android.util.Log; 62import android.util.LongSparseLongArray; 63import android.util.Pools.SynchronizedPool; 64import android.util.Property; 65import android.util.SparseArray; 66import android.util.SuperNotCalledException; 67import android.util.TypedValue; 68import android.view.ContextMenu.ContextMenuInfo; 69import android.view.AccessibilityIterators.TextSegmentIterator; 70import android.view.AccessibilityIterators.CharacterTextSegmentIterator; 71import android.view.AccessibilityIterators.WordTextSegmentIterator; 72import android.view.AccessibilityIterators.ParagraphTextSegmentIterator; 73import android.view.accessibility.AccessibilityEvent; 74import android.view.accessibility.AccessibilityEventSource; 75import android.view.accessibility.AccessibilityManager; 76import android.view.accessibility.AccessibilityNodeInfo; 77import android.view.accessibility.AccessibilityNodeProvider; 78import android.view.animation.Animation; 79import android.view.animation.AnimationUtils; 80import android.view.animation.Transformation; 81import android.view.inputmethod.EditorInfo; 82import android.view.inputmethod.InputConnection; 83import android.view.inputmethod.InputMethodManager; 84import android.widget.ScrollBarDrawable; 85 86import static android.os.Build.VERSION_CODES.*; 87import static java.lang.Math.max; 88 89import com.android.internal.R; 90import com.android.internal.util.Predicate; 91import com.android.internal.view.menu.MenuBuilder; 92import com.google.android.collect.Lists; 93import com.google.android.collect.Maps; 94 95import java.lang.annotation.Retention; 96import java.lang.annotation.RetentionPolicy; 97import java.lang.ref.WeakReference; 98import java.lang.reflect.Field; 99import java.lang.reflect.InvocationTargetException; 100import java.lang.reflect.Method; 101import java.lang.reflect.Modifier; 102import java.util.ArrayList; 103import java.util.Arrays; 104import java.util.Collections; 105import java.util.HashMap; 106import java.util.List; 107import java.util.Locale; 108import java.util.Map; 109import java.util.concurrent.CopyOnWriteArrayList; 110import java.util.concurrent.atomic.AtomicInteger; 111 112/** 113 * <p> 114 * This class represents the basic building block for user interface components. A View 115 * occupies a rectangular area on the screen and is responsible for drawing and 116 * event handling. View is the base class for <em>widgets</em>, which are 117 * used to create interactive UI components (buttons, text fields, etc.). The 118 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 119 * are invisible containers that hold other Views (or other ViewGroups) and define 120 * their layout properties. 121 * </p> 122 * 123 * <div class="special reference"> 124 * <h3>Developer Guides</h3> 125 * <p>For information about using this class to develop your application's user interface, 126 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide. 127 * </div> 128 * 129 * <a name="Using"></a> 130 * <h3>Using Views</h3> 131 * <p> 132 * All of the views in a window are arranged in a single tree. You can add views 133 * either from code or by specifying a tree of views in one or more XML layout 134 * files. There are many specialized subclasses of views that act as controls or 135 * are capable of displaying text, images, or other content. 136 * </p> 137 * <p> 138 * Once you have created a tree of views, there are typically a few types of 139 * common operations you may wish to perform: 140 * <ul> 141 * <li><strong>Set properties:</strong> for example setting the text of a 142 * {@link android.widget.TextView}. The available properties and the methods 143 * that set them will vary among the different subclasses of views. Note that 144 * properties that are known at build time can be set in the XML layout 145 * files.</li> 146 * <li><strong>Set focus:</strong> The framework will handled moving focus in 147 * response to user input. To force focus to a specific view, call 148 * {@link #requestFocus}.</li> 149 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 150 * that will be notified when something interesting happens to the view. For 151 * example, all views will let you set a listener to be notified when the view 152 * gains or loses focus. You can register such a listener using 153 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 154 * Other view subclasses offer more specialized listeners. For example, a Button 155 * exposes a listener to notify clients when the button is clicked.</li> 156 * <li><strong>Set visibility:</strong> You can hide or show views using 157 * {@link #setVisibility(int)}.</li> 158 * </ul> 159 * </p> 160 * <p><em> 161 * Note: The Android framework is responsible for measuring, laying out and 162 * drawing views. You should not call methods that perform these actions on 163 * views yourself unless you are actually implementing a 164 * {@link android.view.ViewGroup}. 165 * </em></p> 166 * 167 * <a name="Lifecycle"></a> 168 * <h3>Implementing a Custom View</h3> 169 * 170 * <p> 171 * To implement a custom view, you will usually begin by providing overrides for 172 * some of the standard methods that the framework calls on all views. You do 173 * not need to override all of these methods. In fact, you can start by just 174 * overriding {@link #onDraw(android.graphics.Canvas)}. 175 * <table border="2" width="85%" align="center" cellpadding="5"> 176 * <thead> 177 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 178 * </thead> 179 * 180 * <tbody> 181 * <tr> 182 * <td rowspan="2">Creation</td> 183 * <td>Constructors</td> 184 * <td>There is a form of the constructor that are called when the view 185 * is created from code and a form that is called when the view is 186 * inflated from a layout file. The second form should parse and apply 187 * any attributes defined in the layout file. 188 * </td> 189 * </tr> 190 * <tr> 191 * <td><code>{@link #onFinishInflate()}</code></td> 192 * <td>Called after a view and all of its children has been inflated 193 * from XML.</td> 194 * </tr> 195 * 196 * <tr> 197 * <td rowspan="3">Layout</td> 198 * <td><code>{@link #onMeasure(int, int)}</code></td> 199 * <td>Called to determine the size requirements for this view and all 200 * of its children. 201 * </td> 202 * </tr> 203 * <tr> 204 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 205 * <td>Called when this view should assign a size and position to all 206 * of its children. 207 * </td> 208 * </tr> 209 * <tr> 210 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 211 * <td>Called when the size of this view has changed. 212 * </td> 213 * </tr> 214 * 215 * <tr> 216 * <td>Drawing</td> 217 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 218 * <td>Called when the view should render its content. 219 * </td> 220 * </tr> 221 * 222 * <tr> 223 * <td rowspan="4">Event processing</td> 224 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 225 * <td>Called when a new hardware key event occurs. 226 * </td> 227 * </tr> 228 * <tr> 229 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 230 * <td>Called when a hardware key up event occurs. 231 * </td> 232 * </tr> 233 * <tr> 234 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 235 * <td>Called when a trackball motion event occurs. 236 * </td> 237 * </tr> 238 * <tr> 239 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 240 * <td>Called when a touch screen motion event occurs. 241 * </td> 242 * </tr> 243 * 244 * <tr> 245 * <td rowspan="2">Focus</td> 246 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 247 * <td>Called when the view gains or loses focus. 248 * </td> 249 * </tr> 250 * 251 * <tr> 252 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 253 * <td>Called when the window containing the view gains or loses focus. 254 * </td> 255 * </tr> 256 * 257 * <tr> 258 * <td rowspan="3">Attaching</td> 259 * <td><code>{@link #onAttachedToWindow()}</code></td> 260 * <td>Called when the view is attached to a window. 261 * </td> 262 * </tr> 263 * 264 * <tr> 265 * <td><code>{@link #onDetachedFromWindow}</code></td> 266 * <td>Called when the view is detached from its window. 267 * </td> 268 * </tr> 269 * 270 * <tr> 271 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 272 * <td>Called when the visibility of the window containing the view 273 * has changed. 274 * </td> 275 * </tr> 276 * </tbody> 277 * 278 * </table> 279 * </p> 280 * 281 * <a name="IDs"></a> 282 * <h3>IDs</h3> 283 * Views may have an integer id associated with them. These ids are typically 284 * assigned in the layout XML files, and are used to find specific views within 285 * the view tree. A common pattern is to: 286 * <ul> 287 * <li>Define a Button in the layout file and assign it a unique ID. 288 * <pre> 289 * <Button 290 * android:id="@+id/my_button" 291 * android:layout_width="wrap_content" 292 * android:layout_height="wrap_content" 293 * android:text="@string/my_button_text"/> 294 * </pre></li> 295 * <li>From the onCreate method of an Activity, find the Button 296 * <pre class="prettyprint"> 297 * Button myButton = (Button) findViewById(R.id.my_button); 298 * </pre></li> 299 * </ul> 300 * <p> 301 * View IDs need not be unique throughout the tree, but it is good practice to 302 * ensure that they are at least unique within the part of the tree you are 303 * searching. 304 * </p> 305 * 306 * <a name="Position"></a> 307 * <h3>Position</h3> 308 * <p> 309 * The geometry of a view is that of a rectangle. A view has a location, 310 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 311 * two dimensions, expressed as a width and a height. The unit for location 312 * and dimensions is the pixel. 313 * </p> 314 * 315 * <p> 316 * It is possible to retrieve the location of a view by invoking the methods 317 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 318 * coordinate of the rectangle representing the view. The latter returns the 319 * top, or Y, coordinate of the rectangle representing the view. These methods 320 * both return the location of the view relative to its parent. For instance, 321 * when getLeft() returns 20, that means the view is located 20 pixels to the 322 * right of the left edge of its direct parent. 323 * </p> 324 * 325 * <p> 326 * In addition, several convenience methods are offered to avoid unnecessary 327 * computations, namely {@link #getRight()} and {@link #getBottom()}. 328 * These methods return the coordinates of the right and bottom edges of the 329 * rectangle representing the view. For instance, calling {@link #getRight()} 330 * is similar to the following computation: <code>getLeft() + getWidth()</code> 331 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 332 * </p> 333 * 334 * <a name="SizePaddingMargins"></a> 335 * <h3>Size, padding and margins</h3> 336 * <p> 337 * The size of a view is expressed with a width and a height. A view actually 338 * possess two pairs of width and height values. 339 * </p> 340 * 341 * <p> 342 * The first pair is known as <em>measured width</em> and 343 * <em>measured height</em>. These dimensions define how big a view wants to be 344 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 345 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 346 * and {@link #getMeasuredHeight()}. 347 * </p> 348 * 349 * <p> 350 * The second pair is simply known as <em>width</em> and <em>height</em>, or 351 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 352 * dimensions define the actual size of the view on screen, at drawing time and 353 * after layout. These values may, but do not have to, be different from the 354 * measured width and height. The width and height can be obtained by calling 355 * {@link #getWidth()} and {@link #getHeight()}. 356 * </p> 357 * 358 * <p> 359 * To measure its dimensions, a view takes into account its padding. The padding 360 * is expressed in pixels for the left, top, right and bottom parts of the view. 361 * Padding can be used to offset the content of the view by a specific amount of 362 * pixels. For instance, a left padding of 2 will push the view's content by 363 * 2 pixels to the right of the left edge. Padding can be set using the 364 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)} 365 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 366 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()}, 367 * {@link #getPaddingEnd()}. 368 * </p> 369 * 370 * <p> 371 * Even though a view can define a padding, it does not provide any support for 372 * margins. However, view groups provide such a support. Refer to 373 * {@link android.view.ViewGroup} and 374 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 375 * </p> 376 * 377 * <a name="Layout"></a> 378 * <h3>Layout</h3> 379 * <p> 380 * Layout is a two pass process: a measure pass and a layout pass. The measuring 381 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 382 * of the view tree. Each view pushes dimension specifications down the tree 383 * during the recursion. At the end of the measure pass, every view has stored 384 * its measurements. The second pass happens in 385 * {@link #layout(int,int,int,int)} and is also top-down. During 386 * this pass each parent is responsible for positioning all of its children 387 * using the sizes computed in the measure pass. 388 * </p> 389 * 390 * <p> 391 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 392 * {@link #getMeasuredHeight()} values must be set, along with those for all of 393 * that view's descendants. A view's measured width and measured height values 394 * must respect the constraints imposed by the view's parents. This guarantees 395 * that at the end of the measure pass, all parents accept all of their 396 * children's measurements. A parent view may call measure() more than once on 397 * its children. For example, the parent may measure each child once with 398 * unspecified dimensions to find out how big they want to be, then call 399 * measure() on them again with actual numbers if the sum of all the children's 400 * unconstrained sizes is too big or too small. 401 * </p> 402 * 403 * <p> 404 * The measure pass uses two classes to communicate dimensions. The 405 * {@link MeasureSpec} class is used by views to tell their parents how they 406 * want to be measured and positioned. The base LayoutParams class just 407 * describes how big the view wants to be for both width and height. For each 408 * dimension, it can specify one of: 409 * <ul> 410 * <li> an exact number 411 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 412 * (minus padding) 413 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 414 * enclose its content (plus padding). 415 * </ul> 416 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 417 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 418 * an X and Y value. 419 * </p> 420 * 421 * <p> 422 * MeasureSpecs are used to push requirements down the tree from parent to 423 * child. A MeasureSpec can be in one of three modes: 424 * <ul> 425 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 426 * of a child view. For example, a LinearLayout may call measure() on its child 427 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 428 * tall the child view wants to be given a width of 240 pixels. 429 * <li>EXACTLY: This is used by the parent to impose an exact size on the 430 * child. The child must use this size, and guarantee that all of its 431 * descendants will fit within this size. 432 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 433 * child. The child must guarantee that it and all of its descendants will fit 434 * within this size. 435 * </ul> 436 * </p> 437 * 438 * <p> 439 * To intiate a layout, call {@link #requestLayout}. This method is typically 440 * called by a view on itself when it believes that is can no longer fit within 441 * its current bounds. 442 * </p> 443 * 444 * <a name="Drawing"></a> 445 * <h3>Drawing</h3> 446 * <p> 447 * Drawing is handled by walking the tree and rendering each view that 448 * intersects the invalid region. Because the tree is traversed in-order, 449 * this means that parents will draw before (i.e., behind) their children, with 450 * siblings drawn in the order they appear in the tree. 451 * If you set a background drawable for a View, then the View will draw it for you 452 * before calling back to its <code>onDraw()</code> method. 453 * </p> 454 * 455 * <p> 456 * Note that the framework will not draw views that are not in the invalid region. 457 * </p> 458 * 459 * <p> 460 * To force a view to draw, call {@link #invalidate()}. 461 * </p> 462 * 463 * <a name="EventHandlingThreading"></a> 464 * <h3>Event Handling and Threading</h3> 465 * <p> 466 * The basic cycle of a view is as follows: 467 * <ol> 468 * <li>An event comes in and is dispatched to the appropriate view. The view 469 * handles the event and notifies any listeners.</li> 470 * <li>If in the course of processing the event, the view's bounds may need 471 * to be changed, the view will call {@link #requestLayout()}.</li> 472 * <li>Similarly, if in the course of processing the event the view's appearance 473 * may need to be changed, the view will call {@link #invalidate()}.</li> 474 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 475 * the framework will take care of measuring, laying out, and drawing the tree 476 * as appropriate.</li> 477 * </ol> 478 * </p> 479 * 480 * <p><em>Note: The entire view tree is single threaded. You must always be on 481 * the UI thread when calling any method on any view.</em> 482 * If you are doing work on other threads and want to update the state of a view 483 * from that thread, you should use a {@link Handler}. 484 * </p> 485 * 486 * <a name="FocusHandling"></a> 487 * <h3>Focus Handling</h3> 488 * <p> 489 * The framework will handle routine focus movement in response to user input. 490 * This includes changing the focus as views are removed or hidden, or as new 491 * views become available. Views indicate their willingness to take focus 492 * through the {@link #isFocusable} method. To change whether a view can take 493 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 494 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 495 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 496 * </p> 497 * <p> 498 * Focus movement is based on an algorithm which finds the nearest neighbor in a 499 * given direction. In rare cases, the default algorithm may not match the 500 * intended behavior of the developer. In these situations, you can provide 501 * explicit overrides by using these XML attributes in the layout file: 502 * <pre> 503 * nextFocusDown 504 * nextFocusLeft 505 * nextFocusRight 506 * nextFocusUp 507 * </pre> 508 * </p> 509 * 510 * 511 * <p> 512 * To get a particular view to take focus, call {@link #requestFocus()}. 513 * </p> 514 * 515 * <a name="TouchMode"></a> 516 * <h3>Touch Mode</h3> 517 * <p> 518 * When a user is navigating a user interface via directional keys such as a D-pad, it is 519 * necessary to give focus to actionable items such as buttons so the user can see 520 * what will take input. If the device has touch capabilities, however, and the user 521 * begins interacting with the interface by touching it, it is no longer necessary to 522 * always highlight, or give focus to, a particular view. This motivates a mode 523 * for interaction named 'touch mode'. 524 * </p> 525 * <p> 526 * For a touch capable device, once the user touches the screen, the device 527 * will enter touch mode. From this point onward, only views for which 528 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 529 * Other views that are touchable, like buttons, will not take focus when touched; they will 530 * only fire the on click listeners. 531 * </p> 532 * <p> 533 * Any time a user hits a directional key, such as a D-pad direction, the view device will 534 * exit touch mode, and find a view to take focus, so that the user may resume interacting 535 * with the user interface without touching the screen again. 536 * </p> 537 * <p> 538 * The touch mode state is maintained across {@link android.app.Activity}s. Call 539 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 540 * </p> 541 * 542 * <a name="Scrolling"></a> 543 * <h3>Scrolling</h3> 544 * <p> 545 * The framework provides basic support for views that wish to internally 546 * scroll their content. This includes keeping track of the X and Y scroll 547 * offset as well as mechanisms for drawing scrollbars. See 548 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 549 * {@link #awakenScrollBars()} for more details. 550 * </p> 551 * 552 * <a name="Tags"></a> 553 * <h3>Tags</h3> 554 * <p> 555 * Unlike IDs, tags are not used to identify views. Tags are essentially an 556 * extra piece of information that can be associated with a view. They are most 557 * often used as a convenience to store data related to views in the views 558 * themselves rather than by putting them in a separate structure. 559 * </p> 560 * 561 * <a name="Properties"></a> 562 * <h3>Properties</h3> 563 * <p> 564 * The View class exposes an {@link #ALPHA} property, as well as several transform-related 565 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are 566 * available both in the {@link Property} form as well as in similarly-named setter/getter 567 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can 568 * be used to set persistent state associated with these rendering-related properties on the view. 569 * The properties and methods can also be used in conjunction with 570 * {@link android.animation.Animator Animator}-based animations, described more in the 571 * <a href="#Animation">Animation</a> section. 572 * </p> 573 * 574 * <a name="Animation"></a> 575 * <h3>Animation</h3> 576 * <p> 577 * Starting with Android 3.0, the preferred way of animating views is to use the 578 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based 579 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and 580 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0 581 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only 582 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class 583 * makes animating these View properties particularly easy and efficient. 584 * </p> 585 * <p> 586 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered. 587 * You can attach an {@link Animation} object to a view using 588 * {@link #setAnimation(Animation)} or 589 * {@link #startAnimation(Animation)}. The animation can alter the scale, 590 * rotation, translation and alpha of a view over time. If the animation is 591 * attached to a view that has children, the animation will affect the entire 592 * subtree rooted by that node. When an animation is started, the framework will 593 * take care of redrawing the appropriate views until the animation completes. 594 * </p> 595 * 596 * <a name="Security"></a> 597 * <h3>Security</h3> 598 * <p> 599 * Sometimes it is essential that an application be able to verify that an action 600 * is being performed with the full knowledge and consent of the user, such as 601 * granting a permission request, making a purchase or clicking on an advertisement. 602 * Unfortunately, a malicious application could try to spoof the user into 603 * performing these actions, unaware, by concealing the intended purpose of the view. 604 * As a remedy, the framework offers a touch filtering mechanism that can be used to 605 * improve the security of views that provide access to sensitive functionality. 606 * </p><p> 607 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 608 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 609 * will discard touches that are received whenever the view's window is obscured by 610 * another visible window. As a result, the view will not receive touches whenever a 611 * toast, dialog or other window appears above the view's window. 612 * </p><p> 613 * For more fine-grained control over security, consider overriding the 614 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 615 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 616 * </p> 617 * 618 * @attr ref android.R.styleable#View_alpha 619 * @attr ref android.R.styleable#View_background 620 * @attr ref android.R.styleable#View_clickable 621 * @attr ref android.R.styleable#View_contentDescription 622 * @attr ref android.R.styleable#View_drawingCacheQuality 623 * @attr ref android.R.styleable#View_duplicateParentState 624 * @attr ref android.R.styleable#View_id 625 * @attr ref android.R.styleable#View_requiresFadingEdge 626 * @attr ref android.R.styleable#View_fadeScrollbars 627 * @attr ref android.R.styleable#View_fadingEdgeLength 628 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 629 * @attr ref android.R.styleable#View_fitsSystemWindows 630 * @attr ref android.R.styleable#View_isScrollContainer 631 * @attr ref android.R.styleable#View_focusable 632 * @attr ref android.R.styleable#View_focusableInTouchMode 633 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 634 * @attr ref android.R.styleable#View_keepScreenOn 635 * @attr ref android.R.styleable#View_layerType 636 * @attr ref android.R.styleable#View_layoutDirection 637 * @attr ref android.R.styleable#View_longClickable 638 * @attr ref android.R.styleable#View_minHeight 639 * @attr ref android.R.styleable#View_minWidth 640 * @attr ref android.R.styleable#View_nextFocusDown 641 * @attr ref android.R.styleable#View_nextFocusLeft 642 * @attr ref android.R.styleable#View_nextFocusRight 643 * @attr ref android.R.styleable#View_nextFocusUp 644 * @attr ref android.R.styleable#View_onClick 645 * @attr ref android.R.styleable#View_padding 646 * @attr ref android.R.styleable#View_paddingBottom 647 * @attr ref android.R.styleable#View_paddingLeft 648 * @attr ref android.R.styleable#View_paddingRight 649 * @attr ref android.R.styleable#View_paddingTop 650 * @attr ref android.R.styleable#View_paddingStart 651 * @attr ref android.R.styleable#View_paddingEnd 652 * @attr ref android.R.styleable#View_saveEnabled 653 * @attr ref android.R.styleable#View_rotation 654 * @attr ref android.R.styleable#View_rotationX 655 * @attr ref android.R.styleable#View_rotationY 656 * @attr ref android.R.styleable#View_scaleX 657 * @attr ref android.R.styleable#View_scaleY 658 * @attr ref android.R.styleable#View_scrollX 659 * @attr ref android.R.styleable#View_scrollY 660 * @attr ref android.R.styleable#View_scrollbarSize 661 * @attr ref android.R.styleable#View_scrollbarStyle 662 * @attr ref android.R.styleable#View_scrollbars 663 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 664 * @attr ref android.R.styleable#View_scrollbarFadeDuration 665 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 666 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 667 * @attr ref android.R.styleable#View_scrollbarThumbVertical 668 * @attr ref android.R.styleable#View_scrollbarTrackVertical 669 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 670 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 671 * @attr ref android.R.styleable#View_stateListAnimator 672 * @attr ref android.R.styleable#View_transitionName 673 * @attr ref android.R.styleable#View_soundEffectsEnabled 674 * @attr ref android.R.styleable#View_tag 675 * @attr ref android.R.styleable#View_textAlignment 676 * @attr ref android.R.styleable#View_textDirection 677 * @attr ref android.R.styleable#View_transformPivotX 678 * @attr ref android.R.styleable#View_transformPivotY 679 * @attr ref android.R.styleable#View_translationX 680 * @attr ref android.R.styleable#View_translationY 681 * @attr ref android.R.styleable#View_translationZ 682 * @attr ref android.R.styleable#View_visibility 683 * 684 * @see android.view.ViewGroup 685 */ 686public class View implements Drawable.Callback, KeyEvent.Callback, 687 AccessibilityEventSource { 688 private static final boolean DBG = false; 689 690 /** 691 * The logging tag used by this class with android.util.Log. 692 */ 693 protected static final String VIEW_LOG_TAG = "View"; 694 695 /** 696 * When set to true, apps will draw debugging information about their layouts. 697 * 698 * @hide 699 */ 700 public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout"; 701 702 /** 703 * Used to mark a View that has no ID. 704 */ 705 public static final int NO_ID = -1; 706 707 /** 708 * Signals that compatibility booleans have been initialized according to 709 * target SDK versions. 710 */ 711 private static boolean sCompatibilityDone = false; 712 713 /** 714 * Use the old (broken) way of building MeasureSpecs. 715 */ 716 private static boolean sUseBrokenMakeMeasureSpec = false; 717 718 /** 719 * Ignore any optimizations using the measure cache. 720 */ 721 private static boolean sIgnoreMeasureCache = false; 722 723 /** 724 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 725 * calling setFlags. 726 */ 727 private static final int NOT_FOCUSABLE = 0x00000000; 728 729 /** 730 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 731 * setFlags. 732 */ 733 private static final int FOCUSABLE = 0x00000001; 734 735 /** 736 * Mask for use with setFlags indicating bits used for focus. 737 */ 738 private static final int FOCUSABLE_MASK = 0x00000001; 739 740 /** 741 * This view will adjust its padding to fit sytem windows (e.g. status bar) 742 */ 743 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 744 745 /** @hide */ 746 @IntDef({VISIBLE, INVISIBLE, GONE}) 747 @Retention(RetentionPolicy.SOURCE) 748 public @interface Visibility {} 749 750 /** 751 * This view is visible. 752 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 753 * android:visibility}. 754 */ 755 public static final int VISIBLE = 0x00000000; 756 757 /** 758 * This view is invisible, but it still takes up space for layout purposes. 759 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 760 * android:visibility}. 761 */ 762 public static final int INVISIBLE = 0x00000004; 763 764 /** 765 * This view is invisible, and it doesn't take any space for layout 766 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 767 * android:visibility}. 768 */ 769 public static final int GONE = 0x00000008; 770 771 /** 772 * Mask for use with setFlags indicating bits used for visibility. 773 * {@hide} 774 */ 775 static final int VISIBILITY_MASK = 0x0000000C; 776 777 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 778 779 /** 780 * This view is enabled. Interpretation varies by subclass. 781 * Use with ENABLED_MASK when calling setFlags. 782 * {@hide} 783 */ 784 static final int ENABLED = 0x00000000; 785 786 /** 787 * This view is disabled. Interpretation varies by subclass. 788 * Use with ENABLED_MASK when calling setFlags. 789 * {@hide} 790 */ 791 static final int DISABLED = 0x00000020; 792 793 /** 794 * Mask for use with setFlags indicating bits used for indicating whether 795 * this view is enabled 796 * {@hide} 797 */ 798 static final int ENABLED_MASK = 0x00000020; 799 800 /** 801 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 802 * called and further optimizations will be performed. It is okay to have 803 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 804 * {@hide} 805 */ 806 static final int WILL_NOT_DRAW = 0x00000080; 807 808 /** 809 * Mask for use with setFlags indicating bits used for indicating whether 810 * this view is will draw 811 * {@hide} 812 */ 813 static final int DRAW_MASK = 0x00000080; 814 815 /** 816 * <p>This view doesn't show scrollbars.</p> 817 * {@hide} 818 */ 819 static final int SCROLLBARS_NONE = 0x00000000; 820 821 /** 822 * <p>This view shows horizontal scrollbars.</p> 823 * {@hide} 824 */ 825 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 826 827 /** 828 * <p>This view shows vertical scrollbars.</p> 829 * {@hide} 830 */ 831 static final int SCROLLBARS_VERTICAL = 0x00000200; 832 833 /** 834 * <p>Mask for use with setFlags indicating bits used for indicating which 835 * scrollbars are enabled.</p> 836 * {@hide} 837 */ 838 static final int SCROLLBARS_MASK = 0x00000300; 839 840 /** 841 * Indicates that the view should filter touches when its window is obscured. 842 * Refer to the class comments for more information about this security feature. 843 * {@hide} 844 */ 845 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 846 847 /** 848 * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate 849 * that they are optional and should be skipped if the window has 850 * requested system UI flags that ignore those insets for layout. 851 */ 852 static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800; 853 854 /** 855 * <p>This view doesn't show fading edges.</p> 856 * {@hide} 857 */ 858 static final int FADING_EDGE_NONE = 0x00000000; 859 860 /** 861 * <p>This view shows horizontal fading edges.</p> 862 * {@hide} 863 */ 864 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 865 866 /** 867 * <p>This view shows vertical fading edges.</p> 868 * {@hide} 869 */ 870 static final int FADING_EDGE_VERTICAL = 0x00002000; 871 872 /** 873 * <p>Mask for use with setFlags indicating bits used for indicating which 874 * fading edges are enabled.</p> 875 * {@hide} 876 */ 877 static final int FADING_EDGE_MASK = 0x00003000; 878 879 /** 880 * <p>Indicates this view can be clicked. When clickable, a View reacts 881 * to clicks by notifying the OnClickListener.<p> 882 * {@hide} 883 */ 884 static final int CLICKABLE = 0x00004000; 885 886 /** 887 * <p>Indicates this view is caching its drawing into a bitmap.</p> 888 * {@hide} 889 */ 890 static final int DRAWING_CACHE_ENABLED = 0x00008000; 891 892 /** 893 * <p>Indicates that no icicle should be saved for this view.<p> 894 * {@hide} 895 */ 896 static final int SAVE_DISABLED = 0x000010000; 897 898 /** 899 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 900 * property.</p> 901 * {@hide} 902 */ 903 static final int SAVE_DISABLED_MASK = 0x000010000; 904 905 /** 906 * <p>Indicates that no drawing cache should ever be created for this view.<p> 907 * {@hide} 908 */ 909 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 910 911 /** 912 * <p>Indicates this view can take / keep focus when int touch mode.</p> 913 * {@hide} 914 */ 915 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 916 917 /** @hide */ 918 @Retention(RetentionPolicy.SOURCE) 919 @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO}) 920 public @interface DrawingCacheQuality {} 921 922 /** 923 * <p>Enables low quality mode for the drawing cache.</p> 924 */ 925 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 926 927 /** 928 * <p>Enables high quality mode for the drawing cache.</p> 929 */ 930 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 931 932 /** 933 * <p>Enables automatic quality mode for the drawing cache.</p> 934 */ 935 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 936 937 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 938 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 939 }; 940 941 /** 942 * <p>Mask for use with setFlags indicating bits used for the cache 943 * quality property.</p> 944 * {@hide} 945 */ 946 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 947 948 /** 949 * <p> 950 * Indicates this view can be long clicked. When long clickable, a View 951 * reacts to long clicks by notifying the OnLongClickListener or showing a 952 * context menu. 953 * </p> 954 * {@hide} 955 */ 956 static final int LONG_CLICKABLE = 0x00200000; 957 958 /** 959 * <p>Indicates that this view gets its drawable states from its direct parent 960 * and ignores its original internal states.</p> 961 * 962 * @hide 963 */ 964 static final int DUPLICATE_PARENT_STATE = 0x00400000; 965 966 /** @hide */ 967 @IntDef({ 968 SCROLLBARS_INSIDE_OVERLAY, 969 SCROLLBARS_INSIDE_INSET, 970 SCROLLBARS_OUTSIDE_OVERLAY, 971 SCROLLBARS_OUTSIDE_INSET 972 }) 973 @Retention(RetentionPolicy.SOURCE) 974 public @interface ScrollBarStyle {} 975 976 /** 977 * The scrollbar style to display the scrollbars inside the content area, 978 * without increasing the padding. The scrollbars will be overlaid with 979 * translucency on the view's content. 980 */ 981 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 982 983 /** 984 * The scrollbar style to display the scrollbars inside the padded area, 985 * increasing the padding of the view. The scrollbars will not overlap the 986 * content area of the view. 987 */ 988 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 989 990 /** 991 * The scrollbar style to display the scrollbars at the edge of the view, 992 * without increasing the padding. The scrollbars will be overlaid with 993 * translucency. 994 */ 995 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 996 997 /** 998 * The scrollbar style to display the scrollbars at the edge of the view, 999 * increasing the padding of the view. The scrollbars will only overlap the 1000 * background, if any. 1001 */ 1002 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 1003 1004 /** 1005 * Mask to check if the scrollbar style is overlay or inset. 1006 * {@hide} 1007 */ 1008 static final int SCROLLBARS_INSET_MASK = 0x01000000; 1009 1010 /** 1011 * Mask to check if the scrollbar style is inside or outside. 1012 * {@hide} 1013 */ 1014 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 1015 1016 /** 1017 * Mask for scrollbar style. 1018 * {@hide} 1019 */ 1020 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 1021 1022 /** 1023 * View flag indicating that the screen should remain on while the 1024 * window containing this view is visible to the user. This effectively 1025 * takes care of automatically setting the WindowManager's 1026 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 1027 */ 1028 public static final int KEEP_SCREEN_ON = 0x04000000; 1029 1030 /** 1031 * View flag indicating whether this view should have sound effects enabled 1032 * for events such as clicking and touching. 1033 */ 1034 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 1035 1036 /** 1037 * View flag indicating whether this view should have haptic feedback 1038 * enabled for events such as long presses. 1039 */ 1040 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 1041 1042 /** 1043 * <p>Indicates that the view hierarchy should stop saving state when 1044 * it reaches this view. If state saving is initiated immediately at 1045 * the view, it will be allowed. 1046 * {@hide} 1047 */ 1048 static final int PARENT_SAVE_DISABLED = 0x20000000; 1049 1050 /** 1051 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 1052 * {@hide} 1053 */ 1054 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 1055 1056 /** @hide */ 1057 @IntDef(flag = true, 1058 value = { 1059 FOCUSABLES_ALL, 1060 FOCUSABLES_TOUCH_MODE 1061 }) 1062 @Retention(RetentionPolicy.SOURCE) 1063 public @interface FocusableMode {} 1064 1065 /** 1066 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1067 * should add all focusable Views regardless if they are focusable in touch mode. 1068 */ 1069 public static final int FOCUSABLES_ALL = 0x00000000; 1070 1071 /** 1072 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1073 * should add only Views focusable in touch mode. 1074 */ 1075 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1076 1077 /** @hide */ 1078 @IntDef({ 1079 FOCUS_BACKWARD, 1080 FOCUS_FORWARD, 1081 FOCUS_LEFT, 1082 FOCUS_UP, 1083 FOCUS_RIGHT, 1084 FOCUS_DOWN 1085 }) 1086 @Retention(RetentionPolicy.SOURCE) 1087 public @interface FocusDirection {} 1088 1089 /** @hide */ 1090 @IntDef({ 1091 FOCUS_LEFT, 1092 FOCUS_UP, 1093 FOCUS_RIGHT, 1094 FOCUS_DOWN 1095 }) 1096 @Retention(RetentionPolicy.SOURCE) 1097 public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward 1098 1099 /** 1100 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1101 * item. 1102 */ 1103 public static final int FOCUS_BACKWARD = 0x00000001; 1104 1105 /** 1106 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1107 * item. 1108 */ 1109 public static final int FOCUS_FORWARD = 0x00000002; 1110 1111 /** 1112 * Use with {@link #focusSearch(int)}. Move focus to the left. 1113 */ 1114 public static final int FOCUS_LEFT = 0x00000011; 1115 1116 /** 1117 * Use with {@link #focusSearch(int)}. Move focus up. 1118 */ 1119 public static final int FOCUS_UP = 0x00000021; 1120 1121 /** 1122 * Use with {@link #focusSearch(int)}. Move focus to the right. 1123 */ 1124 public static final int FOCUS_RIGHT = 0x00000042; 1125 1126 /** 1127 * Use with {@link #focusSearch(int)}. Move focus down. 1128 */ 1129 public static final int FOCUS_DOWN = 0x00000082; 1130 1131 /** 1132 * Bits of {@link #getMeasuredWidthAndState()} and 1133 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1134 */ 1135 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1136 1137 /** 1138 * Bits of {@link #getMeasuredWidthAndState()} and 1139 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1140 */ 1141 public static final int MEASURED_STATE_MASK = 0xff000000; 1142 1143 /** 1144 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1145 * for functions that combine both width and height into a single int, 1146 * such as {@link #getMeasuredState()} and the childState argument of 1147 * {@link #resolveSizeAndState(int, int, int)}. 1148 */ 1149 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1150 1151 /** 1152 * Bit of {@link #getMeasuredWidthAndState()} and 1153 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1154 * is smaller that the space the view would like to have. 1155 */ 1156 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1157 1158 /** 1159 * Base View state sets 1160 */ 1161 // Singles 1162 /** 1163 * Indicates the view has no states set. States are used with 1164 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1165 * view depending on its state. 1166 * 1167 * @see android.graphics.drawable.Drawable 1168 * @see #getDrawableState() 1169 */ 1170 protected static final int[] EMPTY_STATE_SET; 1171 /** 1172 * Indicates the view is enabled. States are used with 1173 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1174 * view depending on its state. 1175 * 1176 * @see android.graphics.drawable.Drawable 1177 * @see #getDrawableState() 1178 */ 1179 protected static final int[] ENABLED_STATE_SET; 1180 /** 1181 * Indicates the view is focused. States are used with 1182 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1183 * view depending on its state. 1184 * 1185 * @see android.graphics.drawable.Drawable 1186 * @see #getDrawableState() 1187 */ 1188 protected static final int[] FOCUSED_STATE_SET; 1189 /** 1190 * Indicates the view is selected. States are used with 1191 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1192 * view depending on its state. 1193 * 1194 * @see android.graphics.drawable.Drawable 1195 * @see #getDrawableState() 1196 */ 1197 protected static final int[] SELECTED_STATE_SET; 1198 /** 1199 * Indicates the view is pressed. States are used with 1200 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1201 * view depending on its state. 1202 * 1203 * @see android.graphics.drawable.Drawable 1204 * @see #getDrawableState() 1205 */ 1206 protected static final int[] PRESSED_STATE_SET; 1207 /** 1208 * Indicates the view's window has focus. States are used with 1209 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1210 * view depending on its state. 1211 * 1212 * @see android.graphics.drawable.Drawable 1213 * @see #getDrawableState() 1214 */ 1215 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1216 // Doubles 1217 /** 1218 * Indicates the view is enabled and has the focus. 1219 * 1220 * @see #ENABLED_STATE_SET 1221 * @see #FOCUSED_STATE_SET 1222 */ 1223 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1224 /** 1225 * Indicates the view is enabled and selected. 1226 * 1227 * @see #ENABLED_STATE_SET 1228 * @see #SELECTED_STATE_SET 1229 */ 1230 protected static final int[] ENABLED_SELECTED_STATE_SET; 1231 /** 1232 * Indicates the view is enabled and that its window has focus. 1233 * 1234 * @see #ENABLED_STATE_SET 1235 * @see #WINDOW_FOCUSED_STATE_SET 1236 */ 1237 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1238 /** 1239 * Indicates the view is focused and selected. 1240 * 1241 * @see #FOCUSED_STATE_SET 1242 * @see #SELECTED_STATE_SET 1243 */ 1244 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1245 /** 1246 * Indicates the view has the focus and that its window has the focus. 1247 * 1248 * @see #FOCUSED_STATE_SET 1249 * @see #WINDOW_FOCUSED_STATE_SET 1250 */ 1251 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1252 /** 1253 * Indicates the view is selected and that its window has the focus. 1254 * 1255 * @see #SELECTED_STATE_SET 1256 * @see #WINDOW_FOCUSED_STATE_SET 1257 */ 1258 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1259 // Triples 1260 /** 1261 * Indicates the view is enabled, focused and selected. 1262 * 1263 * @see #ENABLED_STATE_SET 1264 * @see #FOCUSED_STATE_SET 1265 * @see #SELECTED_STATE_SET 1266 */ 1267 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1268 /** 1269 * Indicates the view is enabled, focused and its window has the focus. 1270 * 1271 * @see #ENABLED_STATE_SET 1272 * @see #FOCUSED_STATE_SET 1273 * @see #WINDOW_FOCUSED_STATE_SET 1274 */ 1275 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1276 /** 1277 * Indicates the view is enabled, selected and its window has the focus. 1278 * 1279 * @see #ENABLED_STATE_SET 1280 * @see #SELECTED_STATE_SET 1281 * @see #WINDOW_FOCUSED_STATE_SET 1282 */ 1283 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1284 /** 1285 * Indicates the view is focused, selected and its window has the focus. 1286 * 1287 * @see #FOCUSED_STATE_SET 1288 * @see #SELECTED_STATE_SET 1289 * @see #WINDOW_FOCUSED_STATE_SET 1290 */ 1291 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1292 /** 1293 * Indicates the view is enabled, focused, selected and its window 1294 * has the focus. 1295 * 1296 * @see #ENABLED_STATE_SET 1297 * @see #FOCUSED_STATE_SET 1298 * @see #SELECTED_STATE_SET 1299 * @see #WINDOW_FOCUSED_STATE_SET 1300 */ 1301 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1302 /** 1303 * Indicates the view is pressed and its window has the focus. 1304 * 1305 * @see #PRESSED_STATE_SET 1306 * @see #WINDOW_FOCUSED_STATE_SET 1307 */ 1308 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1309 /** 1310 * Indicates the view is pressed and selected. 1311 * 1312 * @see #PRESSED_STATE_SET 1313 * @see #SELECTED_STATE_SET 1314 */ 1315 protected static final int[] PRESSED_SELECTED_STATE_SET; 1316 /** 1317 * Indicates the view is pressed, selected and its window has the focus. 1318 * 1319 * @see #PRESSED_STATE_SET 1320 * @see #SELECTED_STATE_SET 1321 * @see #WINDOW_FOCUSED_STATE_SET 1322 */ 1323 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1324 /** 1325 * Indicates the view is pressed and focused. 1326 * 1327 * @see #PRESSED_STATE_SET 1328 * @see #FOCUSED_STATE_SET 1329 */ 1330 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1331 /** 1332 * Indicates the view is pressed, focused and its window has the focus. 1333 * 1334 * @see #PRESSED_STATE_SET 1335 * @see #FOCUSED_STATE_SET 1336 * @see #WINDOW_FOCUSED_STATE_SET 1337 */ 1338 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1339 /** 1340 * Indicates the view is pressed, focused and selected. 1341 * 1342 * @see #PRESSED_STATE_SET 1343 * @see #SELECTED_STATE_SET 1344 * @see #FOCUSED_STATE_SET 1345 */ 1346 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1347 /** 1348 * Indicates the view is pressed, focused, selected and its window has the focus. 1349 * 1350 * @see #PRESSED_STATE_SET 1351 * @see #FOCUSED_STATE_SET 1352 * @see #SELECTED_STATE_SET 1353 * @see #WINDOW_FOCUSED_STATE_SET 1354 */ 1355 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1356 /** 1357 * Indicates the view is pressed and enabled. 1358 * 1359 * @see #PRESSED_STATE_SET 1360 * @see #ENABLED_STATE_SET 1361 */ 1362 protected static final int[] PRESSED_ENABLED_STATE_SET; 1363 /** 1364 * Indicates the view is pressed, enabled and its window has the focus. 1365 * 1366 * @see #PRESSED_STATE_SET 1367 * @see #ENABLED_STATE_SET 1368 * @see #WINDOW_FOCUSED_STATE_SET 1369 */ 1370 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1371 /** 1372 * Indicates the view is pressed, enabled and selected. 1373 * 1374 * @see #PRESSED_STATE_SET 1375 * @see #ENABLED_STATE_SET 1376 * @see #SELECTED_STATE_SET 1377 */ 1378 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1379 /** 1380 * Indicates the view is pressed, enabled, selected and its window has the 1381 * focus. 1382 * 1383 * @see #PRESSED_STATE_SET 1384 * @see #ENABLED_STATE_SET 1385 * @see #SELECTED_STATE_SET 1386 * @see #WINDOW_FOCUSED_STATE_SET 1387 */ 1388 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1389 /** 1390 * Indicates the view is pressed, enabled and focused. 1391 * 1392 * @see #PRESSED_STATE_SET 1393 * @see #ENABLED_STATE_SET 1394 * @see #FOCUSED_STATE_SET 1395 */ 1396 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1397 /** 1398 * Indicates the view is pressed, enabled, focused and its window has the 1399 * focus. 1400 * 1401 * @see #PRESSED_STATE_SET 1402 * @see #ENABLED_STATE_SET 1403 * @see #FOCUSED_STATE_SET 1404 * @see #WINDOW_FOCUSED_STATE_SET 1405 */ 1406 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1407 /** 1408 * Indicates the view is pressed, enabled, focused and selected. 1409 * 1410 * @see #PRESSED_STATE_SET 1411 * @see #ENABLED_STATE_SET 1412 * @see #SELECTED_STATE_SET 1413 * @see #FOCUSED_STATE_SET 1414 */ 1415 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1416 /** 1417 * Indicates the view is pressed, enabled, focused, selected and its window 1418 * has the focus. 1419 * 1420 * @see #PRESSED_STATE_SET 1421 * @see #ENABLED_STATE_SET 1422 * @see #SELECTED_STATE_SET 1423 * @see #FOCUSED_STATE_SET 1424 * @see #WINDOW_FOCUSED_STATE_SET 1425 */ 1426 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1427 1428 /** 1429 * The order here is very important to {@link #getDrawableState()} 1430 */ 1431 private static final int[][] VIEW_STATE_SETS; 1432 1433 static final int VIEW_STATE_WINDOW_FOCUSED = 1; 1434 static final int VIEW_STATE_SELECTED = 1 << 1; 1435 static final int VIEW_STATE_FOCUSED = 1 << 2; 1436 static final int VIEW_STATE_ENABLED = 1 << 3; 1437 static final int VIEW_STATE_PRESSED = 1 << 4; 1438 static final int VIEW_STATE_ACTIVATED = 1 << 5; 1439 static final int VIEW_STATE_ACCELERATED = 1 << 6; 1440 static final int VIEW_STATE_HOVERED = 1 << 7; 1441 static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8; 1442 static final int VIEW_STATE_DRAG_HOVERED = 1 << 9; 1443 1444 static final int[] VIEW_STATE_IDS = new int[] { 1445 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED, 1446 R.attr.state_selected, VIEW_STATE_SELECTED, 1447 R.attr.state_focused, VIEW_STATE_FOCUSED, 1448 R.attr.state_enabled, VIEW_STATE_ENABLED, 1449 R.attr.state_pressed, VIEW_STATE_PRESSED, 1450 R.attr.state_activated, VIEW_STATE_ACTIVATED, 1451 R.attr.state_accelerated, VIEW_STATE_ACCELERATED, 1452 R.attr.state_hovered, VIEW_STATE_HOVERED, 1453 R.attr.state_drag_can_accept, VIEW_STATE_DRAG_CAN_ACCEPT, 1454 R.attr.state_drag_hovered, VIEW_STATE_DRAG_HOVERED 1455 }; 1456 1457 static { 1458 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) { 1459 throw new IllegalStateException( 1460 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array"); 1461 } 1462 int[] orderedIds = new int[VIEW_STATE_IDS.length]; 1463 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) { 1464 int viewState = R.styleable.ViewDrawableStates[i]; 1465 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) { 1466 if (VIEW_STATE_IDS[j] == viewState) { 1467 orderedIds[i * 2] = viewState; 1468 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1]; 1469 } 1470 } 1471 } 1472 final int NUM_BITS = VIEW_STATE_IDS.length / 2; 1473 VIEW_STATE_SETS = new int[1 << NUM_BITS][]; 1474 for (int i = 0; i < VIEW_STATE_SETS.length; i++) { 1475 int numBits = Integer.bitCount(i); 1476 int[] set = new int[numBits]; 1477 int pos = 0; 1478 for (int j = 0; j < orderedIds.length; j += 2) { 1479 if ((i & orderedIds[j+1]) != 0) { 1480 set[pos++] = orderedIds[j]; 1481 } 1482 } 1483 VIEW_STATE_SETS[i] = set; 1484 } 1485 1486 EMPTY_STATE_SET = VIEW_STATE_SETS[0]; 1487 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED]; 1488 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED]; 1489 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1490 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED]; 1491 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED]; 1492 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1493 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED]; 1494 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1495 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED]; 1496 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1497 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1498 | VIEW_STATE_FOCUSED]; 1499 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED]; 1500 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1501 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED]; 1502 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1503 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED]; 1504 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1505 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1506 | VIEW_STATE_ENABLED]; 1507 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1508 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED]; 1509 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1510 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1511 | VIEW_STATE_ENABLED]; 1512 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1513 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1514 | VIEW_STATE_ENABLED]; 1515 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1516 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1517 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED]; 1518 1519 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED]; 1520 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1521 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED]; 1522 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1523 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED]; 1524 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1525 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1526 | VIEW_STATE_PRESSED]; 1527 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1528 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1529 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1530 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1531 | VIEW_STATE_PRESSED]; 1532 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1533 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1534 | VIEW_STATE_PRESSED]; 1535 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1536 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1537 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1538 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[ 1539 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1540 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1541 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED 1542 | VIEW_STATE_PRESSED]; 1543 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1544 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED 1545 | VIEW_STATE_PRESSED]; 1546 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1547 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1548 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1549 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1550 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED 1551 | VIEW_STATE_PRESSED]; 1552 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1553 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1554 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1555 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1556 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1557 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1558 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1559 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1560 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED 1561 | VIEW_STATE_PRESSED]; 1562 } 1563 1564 /** 1565 * Accessibility event types that are dispatched for text population. 1566 */ 1567 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 1568 AccessibilityEvent.TYPE_VIEW_CLICKED 1569 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 1570 | AccessibilityEvent.TYPE_VIEW_SELECTED 1571 | AccessibilityEvent.TYPE_VIEW_FOCUSED 1572 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 1573 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 1574 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 1575 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 1576 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED 1577 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED 1578 | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY; 1579 1580 /** 1581 * Temporary Rect currently for use in setBackground(). This will probably 1582 * be extended in the future to hold our own class with more than just 1583 * a Rect. :) 1584 */ 1585 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1586 1587 /** 1588 * Map used to store views' tags. 1589 */ 1590 private SparseArray<Object> mKeyedTags; 1591 1592 /** 1593 * The next available accessibility id. 1594 */ 1595 private static int sNextAccessibilityViewId; 1596 1597 /** 1598 * The animation currently associated with this view. 1599 * @hide 1600 */ 1601 protected Animation mCurrentAnimation = null; 1602 1603 /** 1604 * Width as measured during measure pass. 1605 * {@hide} 1606 */ 1607 @ViewDebug.ExportedProperty(category = "measurement") 1608 int mMeasuredWidth; 1609 1610 /** 1611 * Height as measured during measure pass. 1612 * {@hide} 1613 */ 1614 @ViewDebug.ExportedProperty(category = "measurement") 1615 int mMeasuredHeight; 1616 1617 /** 1618 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1619 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1620 * its display list. This flag, used only when hw accelerated, allows us to clear the 1621 * flag while retaining this information until it's needed (at getDisplayList() time and 1622 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1623 * 1624 * {@hide} 1625 */ 1626 boolean mRecreateDisplayList = false; 1627 1628 /** 1629 * The view's identifier. 1630 * {@hide} 1631 * 1632 * @see #setId(int) 1633 * @see #getId() 1634 */ 1635 @ViewDebug.ExportedProperty(resolveId = true) 1636 int mID = NO_ID; 1637 1638 /** 1639 * The stable ID of this view for accessibility purposes. 1640 */ 1641 int mAccessibilityViewId = NO_ID; 1642 1643 private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 1644 1645 SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent; 1646 1647 /** 1648 * The view's tag. 1649 * {@hide} 1650 * 1651 * @see #setTag(Object) 1652 * @see #getTag() 1653 */ 1654 protected Object mTag = null; 1655 1656 // for mPrivateFlags: 1657 /** {@hide} */ 1658 static final int PFLAG_WANTS_FOCUS = 0x00000001; 1659 /** {@hide} */ 1660 static final int PFLAG_FOCUSED = 0x00000002; 1661 /** {@hide} */ 1662 static final int PFLAG_SELECTED = 0x00000004; 1663 /** {@hide} */ 1664 static final int PFLAG_IS_ROOT_NAMESPACE = 0x00000008; 1665 /** {@hide} */ 1666 static final int PFLAG_HAS_BOUNDS = 0x00000010; 1667 /** {@hide} */ 1668 static final int PFLAG_DRAWN = 0x00000020; 1669 /** 1670 * When this flag is set, this view is running an animation on behalf of its 1671 * children and should therefore not cancel invalidate requests, even if they 1672 * lie outside of this view's bounds. 1673 * 1674 * {@hide} 1675 */ 1676 static final int PFLAG_DRAW_ANIMATION = 0x00000040; 1677 /** {@hide} */ 1678 static final int PFLAG_SKIP_DRAW = 0x00000080; 1679 /** {@hide} */ 1680 static final int PFLAG_ONLY_DRAWS_BACKGROUND = 0x00000100; 1681 /** {@hide} */ 1682 static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1683 /** {@hide} */ 1684 static final int PFLAG_DRAWABLE_STATE_DIRTY = 0x00000400; 1685 /** {@hide} */ 1686 static final int PFLAG_MEASURED_DIMENSION_SET = 0x00000800; 1687 /** {@hide} */ 1688 static final int PFLAG_FORCE_LAYOUT = 0x00001000; 1689 /** {@hide} */ 1690 static final int PFLAG_LAYOUT_REQUIRED = 0x00002000; 1691 1692 private static final int PFLAG_PRESSED = 0x00004000; 1693 1694 /** {@hide} */ 1695 static final int PFLAG_DRAWING_CACHE_VALID = 0x00008000; 1696 /** 1697 * Flag used to indicate that this view should be drawn once more (and only once 1698 * more) after its animation has completed. 1699 * {@hide} 1700 */ 1701 static final int PFLAG_ANIMATION_STARTED = 0x00010000; 1702 1703 private static final int PFLAG_SAVE_STATE_CALLED = 0x00020000; 1704 1705 /** 1706 * Indicates that the View returned true when onSetAlpha() was called and that 1707 * the alpha must be restored. 1708 * {@hide} 1709 */ 1710 static final int PFLAG_ALPHA_SET = 0x00040000; 1711 1712 /** 1713 * Set by {@link #setScrollContainer(boolean)}. 1714 */ 1715 static final int PFLAG_SCROLL_CONTAINER = 0x00080000; 1716 1717 /** 1718 * Set by {@link #setScrollContainer(boolean)}. 1719 */ 1720 static final int PFLAG_SCROLL_CONTAINER_ADDED = 0x00100000; 1721 1722 /** 1723 * View flag indicating whether this view was invalidated (fully or partially.) 1724 * 1725 * @hide 1726 */ 1727 static final int PFLAG_DIRTY = 0x00200000; 1728 1729 /** 1730 * View flag indicating whether this view was invalidated by an opaque 1731 * invalidate request. 1732 * 1733 * @hide 1734 */ 1735 static final int PFLAG_DIRTY_OPAQUE = 0x00400000; 1736 1737 /** 1738 * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}. 1739 * 1740 * @hide 1741 */ 1742 static final int PFLAG_DIRTY_MASK = 0x00600000; 1743 1744 /** 1745 * Indicates whether the background is opaque. 1746 * 1747 * @hide 1748 */ 1749 static final int PFLAG_OPAQUE_BACKGROUND = 0x00800000; 1750 1751 /** 1752 * Indicates whether the scrollbars are opaque. 1753 * 1754 * @hide 1755 */ 1756 static final int PFLAG_OPAQUE_SCROLLBARS = 0x01000000; 1757 1758 /** 1759 * Indicates whether the view is opaque. 1760 * 1761 * @hide 1762 */ 1763 static final int PFLAG_OPAQUE_MASK = 0x01800000; 1764 1765 /** 1766 * Indicates a prepressed state; 1767 * the short time between ACTION_DOWN and recognizing 1768 * a 'real' press. Prepressed is used to recognize quick taps 1769 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1770 * 1771 * @hide 1772 */ 1773 private static final int PFLAG_PREPRESSED = 0x02000000; 1774 1775 /** 1776 * Indicates whether the view is temporarily detached. 1777 * 1778 * @hide 1779 */ 1780 static final int PFLAG_CANCEL_NEXT_UP_EVENT = 0x04000000; 1781 1782 /** 1783 * Indicates that we should awaken scroll bars once attached 1784 * 1785 * @hide 1786 */ 1787 private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1788 1789 /** 1790 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1791 * @hide 1792 */ 1793 private static final int PFLAG_HOVERED = 0x10000000; 1794 1795 /** 1796 * no longer needed, should be reused 1797 */ 1798 private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000; 1799 1800 /** {@hide} */ 1801 static final int PFLAG_ACTIVATED = 0x40000000; 1802 1803 /** 1804 * Indicates that this view was specifically invalidated, not just dirtied because some 1805 * child view was invalidated. The flag is used to determine when we need to recreate 1806 * a view's display list (as opposed to just returning a reference to its existing 1807 * display list). 1808 * 1809 * @hide 1810 */ 1811 static final int PFLAG_INVALIDATED = 0x80000000; 1812 1813 /** 1814 * Masks for mPrivateFlags2, as generated by dumpFlags(): 1815 * 1816 * |-------|-------|-------|-------| 1817 * 1 PFLAG2_DRAG_CAN_ACCEPT 1818 * 1 PFLAG2_DRAG_HOVERED 1819 * 11 PFLAG2_LAYOUT_DIRECTION_MASK 1820 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL 1821 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED 1822 * 11 PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK 1823 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[1] 1824 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[2] 1825 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[3] 1826 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[4] 1827 * 1 1 PFLAG2_TEXT_DIRECTION_FLAGS[5] 1828 * 111 PFLAG2_TEXT_DIRECTION_MASK 1829 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED 1830 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT 1831 * 111 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK 1832 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[1] 1833 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[2] 1834 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[3] 1835 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[4] 1836 * 1 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[5] 1837 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[6] 1838 * 111 PFLAG2_TEXT_ALIGNMENT_MASK 1839 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED 1840 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT 1841 * 111 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK 1842 * 111 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK 1843 * 11 PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK 1844 * 1 PFLAG2_ACCESSIBILITY_FOCUSED 1845 * 1 PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED 1846 * 1 PFLAG2_VIEW_QUICK_REJECTED 1847 * 1 PFLAG2_PADDING_RESOLVED 1848 * 1 PFLAG2_DRAWABLE_RESOLVED 1849 * 1 PFLAG2_HAS_TRANSIENT_STATE 1850 * |-------|-------|-------|-------| 1851 */ 1852 1853 /** 1854 * Indicates that this view has reported that it can accept the current drag's content. 1855 * Cleared when the drag operation concludes. 1856 * @hide 1857 */ 1858 static final int PFLAG2_DRAG_CAN_ACCEPT = 0x00000001; 1859 1860 /** 1861 * Indicates that this view is currently directly under the drag location in a 1862 * drag-and-drop operation involving content that it can accept. Cleared when 1863 * the drag exits the view, or when the drag operation concludes. 1864 * @hide 1865 */ 1866 static final int PFLAG2_DRAG_HOVERED = 0x00000002; 1867 1868 /** @hide */ 1869 @IntDef({ 1870 LAYOUT_DIRECTION_LTR, 1871 LAYOUT_DIRECTION_RTL, 1872 LAYOUT_DIRECTION_INHERIT, 1873 LAYOUT_DIRECTION_LOCALE 1874 }) 1875 @Retention(RetentionPolicy.SOURCE) 1876 // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection 1877 public @interface LayoutDir {} 1878 1879 /** @hide */ 1880 @IntDef({ 1881 LAYOUT_DIRECTION_LTR, 1882 LAYOUT_DIRECTION_RTL 1883 }) 1884 @Retention(RetentionPolicy.SOURCE) 1885 public @interface ResolvedLayoutDir {} 1886 1887 /** 1888 * Horizontal layout direction of this view is from Left to Right. 1889 * Use with {@link #setLayoutDirection}. 1890 */ 1891 public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR; 1892 1893 /** 1894 * Horizontal layout direction of this view is from Right to Left. 1895 * Use with {@link #setLayoutDirection}. 1896 */ 1897 public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL; 1898 1899 /** 1900 * Horizontal layout direction of this view is inherited from its parent. 1901 * Use with {@link #setLayoutDirection}. 1902 */ 1903 public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT; 1904 1905 /** 1906 * Horizontal layout direction of this view is from deduced from the default language 1907 * script for the locale. Use with {@link #setLayoutDirection}. 1908 */ 1909 public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE; 1910 1911 /** 1912 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1913 * @hide 1914 */ 1915 static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2; 1916 1917 /** 1918 * Mask for use with private flags indicating bits used for horizontal layout direction. 1919 * @hide 1920 */ 1921 static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1922 1923 /** 1924 * Indicates whether the view horizontal layout direction has been resolved and drawn to the 1925 * right-to-left direction. 1926 * @hide 1927 */ 1928 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1929 1930 /** 1931 * Indicates whether the view horizontal layout direction has been resolved. 1932 * @hide 1933 */ 1934 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1935 1936 /** 1937 * Mask for use with private flags indicating bits used for resolved horizontal layout direction. 1938 * @hide 1939 */ 1940 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C 1941 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1942 1943 /* 1944 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct 1945 * flag value. 1946 * @hide 1947 */ 1948 private static final int[] LAYOUT_DIRECTION_FLAGS = { 1949 LAYOUT_DIRECTION_LTR, 1950 LAYOUT_DIRECTION_RTL, 1951 LAYOUT_DIRECTION_INHERIT, 1952 LAYOUT_DIRECTION_LOCALE 1953 }; 1954 1955 /** 1956 * Default horizontal layout direction. 1957 */ 1958 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 1959 1960 /** 1961 * Default horizontal layout direction. 1962 * @hide 1963 */ 1964 static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR; 1965 1966 /** 1967 * Text direction is inherited thru {@link ViewGroup} 1968 */ 1969 public static final int TEXT_DIRECTION_INHERIT = 0; 1970 1971 /** 1972 * Text direction is using "first strong algorithm". The first strong directional character 1973 * determines the paragraph direction. If there is no strong directional character, the 1974 * paragraph direction is the view's resolved layout direction. 1975 */ 1976 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 1977 1978 /** 1979 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 1980 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 1981 * If there are neither, the paragraph direction is the view's resolved layout direction. 1982 */ 1983 public static final int TEXT_DIRECTION_ANY_RTL = 2; 1984 1985 /** 1986 * Text direction is forced to LTR. 1987 */ 1988 public static final int TEXT_DIRECTION_LTR = 3; 1989 1990 /** 1991 * Text direction is forced to RTL. 1992 */ 1993 public static final int TEXT_DIRECTION_RTL = 4; 1994 1995 /** 1996 * Text direction is coming from the system Locale. 1997 */ 1998 public static final int TEXT_DIRECTION_LOCALE = 5; 1999 2000 /** 2001 * Default text direction is inherited 2002 */ 2003 private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT; 2004 2005 /** 2006 * Default resolved text direction 2007 * @hide 2008 */ 2009 static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG; 2010 2011 /** 2012 * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED) 2013 * @hide 2014 */ 2015 static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6; 2016 2017 /** 2018 * Mask for use with private flags indicating bits used for text direction. 2019 * @hide 2020 */ 2021 static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007 2022 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2023 2024 /** 2025 * Array of text direction flags for mapping attribute "textDirection" to correct 2026 * flag value. 2027 * @hide 2028 */ 2029 private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = { 2030 TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2031 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2032 TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2033 TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2034 TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2035 TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT 2036 }; 2037 2038 /** 2039 * Indicates whether the view text direction has been resolved. 2040 * @hide 2041 */ 2042 static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008 2043 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2044 2045 /** 2046 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2047 * @hide 2048 */ 2049 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10; 2050 2051 /** 2052 * Mask for use with private flags indicating bits used for resolved text direction. 2053 * @hide 2054 */ 2055 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 2056 << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2057 2058 /** 2059 * Indicates whether the view text direction has been resolved to the "first strong" heuristic. 2060 * @hide 2061 */ 2062 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT = 2063 TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2064 2065 /** @hide */ 2066 @IntDef({ 2067 TEXT_ALIGNMENT_INHERIT, 2068 TEXT_ALIGNMENT_GRAVITY, 2069 TEXT_ALIGNMENT_CENTER, 2070 TEXT_ALIGNMENT_TEXT_START, 2071 TEXT_ALIGNMENT_TEXT_END, 2072 TEXT_ALIGNMENT_VIEW_START, 2073 TEXT_ALIGNMENT_VIEW_END 2074 }) 2075 @Retention(RetentionPolicy.SOURCE) 2076 public @interface TextAlignment {} 2077 2078 /** 2079 * Default text alignment. The text alignment of this View is inherited from its parent. 2080 * Use with {@link #setTextAlignment(int)} 2081 */ 2082 public static final int TEXT_ALIGNMENT_INHERIT = 0; 2083 2084 /** 2085 * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL, 2086 * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction. 2087 * 2088 * Use with {@link #setTextAlignment(int)} 2089 */ 2090 public static final int TEXT_ALIGNMENT_GRAVITY = 1; 2091 2092 /** 2093 * Align to the start of the paragraph, e.g. ALIGN_NORMAL. 2094 * 2095 * Use with {@link #setTextAlignment(int)} 2096 */ 2097 public static final int TEXT_ALIGNMENT_TEXT_START = 2; 2098 2099 /** 2100 * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE. 2101 * 2102 * Use with {@link #setTextAlignment(int)} 2103 */ 2104 public static final int TEXT_ALIGNMENT_TEXT_END = 3; 2105 2106 /** 2107 * Center the paragraph, e.g. ALIGN_CENTER. 2108 * 2109 * Use with {@link #setTextAlignment(int)} 2110 */ 2111 public static final int TEXT_ALIGNMENT_CENTER = 4; 2112 2113 /** 2114 * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved 2115 * layoutDirection is LTR, and ALIGN_RIGHT otherwise. 2116 * 2117 * Use with {@link #setTextAlignment(int)} 2118 */ 2119 public static final int TEXT_ALIGNMENT_VIEW_START = 5; 2120 2121 /** 2122 * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved 2123 * layoutDirection is LTR, and ALIGN_LEFT otherwise. 2124 * 2125 * Use with {@link #setTextAlignment(int)} 2126 */ 2127 public static final int TEXT_ALIGNMENT_VIEW_END = 6; 2128 2129 /** 2130 * Default text alignment is inherited 2131 */ 2132 private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2133 2134 /** 2135 * Default resolved text alignment 2136 * @hide 2137 */ 2138 static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2139 2140 /** 2141 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2142 * @hide 2143 */ 2144 static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13; 2145 2146 /** 2147 * Mask for use with private flags indicating bits used for text alignment. 2148 * @hide 2149 */ 2150 static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2151 2152 /** 2153 * Array of text direction flags for mapping attribute "textAlignment" to correct 2154 * flag value. 2155 * @hide 2156 */ 2157 private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = { 2158 TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2159 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2160 TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2161 TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2162 TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2163 TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2164 TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 2165 }; 2166 2167 /** 2168 * Indicates whether the view text alignment has been resolved. 2169 * @hide 2170 */ 2171 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2172 2173 /** 2174 * Bit shift to get the resolved text alignment. 2175 * @hide 2176 */ 2177 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17; 2178 2179 /** 2180 * Mask for use with private flags indicating bits used for text alignment. 2181 * @hide 2182 */ 2183 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 2184 << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2185 2186 /** 2187 * Indicates whether if the view text alignment has been resolved to gravity 2188 */ 2189 private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT = 2190 TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2191 2192 // Accessiblity constants for mPrivateFlags2 2193 2194 /** 2195 * Shift for the bits in {@link #mPrivateFlags2} related to the 2196 * "importantForAccessibility" attribute. 2197 */ 2198 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20; 2199 2200 /** 2201 * Automatically determine whether a view is important for accessibility. 2202 */ 2203 public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000; 2204 2205 /** 2206 * The view is important for accessibility. 2207 */ 2208 public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001; 2209 2210 /** 2211 * The view is not important for accessibility. 2212 */ 2213 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002; 2214 2215 /** 2216 * The view is not important for accessibility, nor are any of its 2217 * descendant views. 2218 */ 2219 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004; 2220 2221 /** 2222 * The default whether the view is important for accessibility. 2223 */ 2224 static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO; 2225 2226 /** 2227 * Mask for obtainig the bits which specify how to determine 2228 * whether a view is important for accessibility. 2229 */ 2230 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO 2231 | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO 2232 | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) 2233 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2234 2235 /** 2236 * Shift for the bits in {@link #mPrivateFlags2} related to the 2237 * "accessibilityLiveRegion" attribute. 2238 */ 2239 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23; 2240 2241 /** 2242 * Live region mode specifying that accessibility services should not 2243 * automatically announce changes to this view. This is the default live 2244 * region mode for most views. 2245 * <p> 2246 * Use with {@link #setAccessibilityLiveRegion(int)}. 2247 */ 2248 public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000; 2249 2250 /** 2251 * Live region mode specifying that accessibility services should announce 2252 * changes to this view. 2253 * <p> 2254 * Use with {@link #setAccessibilityLiveRegion(int)}. 2255 */ 2256 public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001; 2257 2258 /** 2259 * Live region mode specifying that accessibility services should interrupt 2260 * ongoing speech to immediately announce changes to this view. 2261 * <p> 2262 * Use with {@link #setAccessibilityLiveRegion(int)}. 2263 */ 2264 public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002; 2265 2266 /** 2267 * The default whether the view is important for accessibility. 2268 */ 2269 static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE; 2270 2271 /** 2272 * Mask for obtaining the bits which specify a view's accessibility live 2273 * region mode. 2274 */ 2275 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE 2276 | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE) 2277 << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 2278 2279 /** 2280 * Flag indicating whether a view has accessibility focus. 2281 */ 2282 static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000; 2283 2284 /** 2285 * Flag whether the accessibility state of the subtree rooted at this view changed. 2286 */ 2287 static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000; 2288 2289 /** 2290 * Flag indicating whether a view failed the quickReject() check in draw(). This condition 2291 * is used to check whether later changes to the view's transform should invalidate the 2292 * view to force the quickReject test to run again. 2293 */ 2294 static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000; 2295 2296 /** 2297 * Flag indicating that start/end padding has been resolved into left/right padding 2298 * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()} 2299 * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved 2300 * during measurement. In some special cases this is required such as when an adapter-based 2301 * view measures prospective children without attaching them to a window. 2302 */ 2303 static final int PFLAG2_PADDING_RESOLVED = 0x20000000; 2304 2305 /** 2306 * Flag indicating that the start/end drawables has been resolved into left/right ones. 2307 */ 2308 static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000; 2309 2310 /** 2311 * Indicates that the view is tracking some sort of transient state 2312 * that the app should not need to be aware of, but that the framework 2313 * should take special care to preserve. 2314 */ 2315 static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000; 2316 2317 /** 2318 * Group of bits indicating that RTL properties resolution is done. 2319 */ 2320 static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED | 2321 PFLAG2_TEXT_DIRECTION_RESOLVED | 2322 PFLAG2_TEXT_ALIGNMENT_RESOLVED | 2323 PFLAG2_PADDING_RESOLVED | 2324 PFLAG2_DRAWABLE_RESOLVED; 2325 2326 // There are a couple of flags left in mPrivateFlags2 2327 2328 /* End of masks for mPrivateFlags2 */ 2329 2330 /** 2331 * Masks for mPrivateFlags3, as generated by dumpFlags(): 2332 * 2333 * |-------|-------|-------|-------| 2334 * 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM 2335 * 1 PFLAG3_VIEW_IS_ANIMATING_ALPHA 2336 * 1 PFLAG3_IS_LAID_OUT 2337 * 1 PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT 2338 * 1 PFLAG3_CALLED_SUPER 2339 * |-------|-------|-------|-------| 2340 */ 2341 2342 /** 2343 * Flag indicating that view has a transform animation set on it. This is used to track whether 2344 * an animation is cleared between successive frames, in order to tell the associated 2345 * DisplayList to clear its animation matrix. 2346 */ 2347 static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1; 2348 2349 /** 2350 * Flag indicating that view has an alpha animation set on it. This is used to track whether an 2351 * animation is cleared between successive frames, in order to tell the associated 2352 * DisplayList to restore its alpha value. 2353 */ 2354 static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2; 2355 2356 /** 2357 * Flag indicating that the view has been through at least one layout since it 2358 * was last attached to a window. 2359 */ 2360 static final int PFLAG3_IS_LAID_OUT = 0x4; 2361 2362 /** 2363 * Flag indicating that a call to measure() was skipped and should be done 2364 * instead when layout() is invoked. 2365 */ 2366 static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8; 2367 2368 /** 2369 * Flag indicating that an overridden method correctly called down to 2370 * the superclass implementation as required by the API spec. 2371 */ 2372 static final int PFLAG3_CALLED_SUPER = 0x10; 2373 2374 /** 2375 * Flag indicating that we're in the process of applying window insets. 2376 */ 2377 static final int PFLAG3_APPLYING_INSETS = 0x20; 2378 2379 /** 2380 * Flag indicating that we're in the process of fitting system windows using the old method. 2381 */ 2382 static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40; 2383 2384 /** 2385 * Flag indicating that nested scrolling is enabled for this view. 2386 * The view will optionally cooperate with views up its parent chain to allow for 2387 * integrated nested scrolling along the same axis. 2388 */ 2389 static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80; 2390 2391 /* End of masks for mPrivateFlags3 */ 2392 2393 static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED; 2394 2395 /** 2396 * Always allow a user to over-scroll this view, provided it is a 2397 * view that can scroll. 2398 * 2399 * @see #getOverScrollMode() 2400 * @see #setOverScrollMode(int) 2401 */ 2402 public static final int OVER_SCROLL_ALWAYS = 0; 2403 2404 /** 2405 * Allow a user to over-scroll this view only if the content is large 2406 * enough to meaningfully scroll, provided it is a view that can scroll. 2407 * 2408 * @see #getOverScrollMode() 2409 * @see #setOverScrollMode(int) 2410 */ 2411 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 2412 2413 /** 2414 * Never allow a user to over-scroll this view. 2415 * 2416 * @see #getOverScrollMode() 2417 * @see #setOverScrollMode(int) 2418 */ 2419 public static final int OVER_SCROLL_NEVER = 2; 2420 2421 /** 2422 * Special constant for {@link #setSystemUiVisibility(int)}: View has 2423 * requested the system UI (status bar) to be visible (the default). 2424 * 2425 * @see #setSystemUiVisibility(int) 2426 */ 2427 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 2428 2429 /** 2430 * Flag for {@link #setSystemUiVisibility(int)}: View has requested the 2431 * system UI to enter an unobtrusive "low profile" mode. 2432 * 2433 * <p>This is for use in games, book readers, video players, or any other 2434 * "immersive" application where the usual system chrome is deemed too distracting. 2435 * 2436 * <p>In low profile mode, the status bar and/or navigation icons may dim. 2437 * 2438 * @see #setSystemUiVisibility(int) 2439 */ 2440 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 2441 2442 /** 2443 * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the 2444 * system navigation be temporarily hidden. 2445 * 2446 * <p>This is an even less obtrusive state than that called for by 2447 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 2448 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 2449 * those to disappear. This is useful (in conjunction with the 2450 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 2451 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 2452 * window flags) for displaying content using every last pixel on the display. 2453 * 2454 * <p>There is a limitation: because navigation controls are so important, the least user 2455 * interaction will cause them to reappear immediately. When this happens, both 2456 * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically, 2457 * so that both elements reappear at the same time. 2458 * 2459 * @see #setSystemUiVisibility(int) 2460 */ 2461 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 2462 2463 /** 2464 * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go 2465 * into the normal fullscreen mode so that its content can take over the screen 2466 * while still allowing the user to interact with the application. 2467 * 2468 * <p>This has the same visual effect as 2469 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN 2470 * WindowManager.LayoutParams.FLAG_FULLSCREEN}, 2471 * meaning that non-critical screen decorations (such as the status bar) will be 2472 * hidden while the user is in the View's window, focusing the experience on 2473 * that content. Unlike the window flag, if you are using ActionBar in 2474 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2475 * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also 2476 * hide the action bar. 2477 * 2478 * <p>This approach to going fullscreen is best used over the window flag when 2479 * it is a transient state -- that is, the application does this at certain 2480 * points in its user interaction where it wants to allow the user to focus 2481 * on content, but not as a continuous state. For situations where the application 2482 * would like to simply stay full screen the entire time (such as a game that 2483 * wants to take over the screen), the 2484 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag} 2485 * is usually a better approach. The state set here will be removed by the system 2486 * in various situations (such as the user moving to another application) like 2487 * the other system UI states. 2488 * 2489 * <p>When using this flag, the application should provide some easy facility 2490 * for the user to go out of it. A common example would be in an e-book 2491 * reader, where tapping on the screen brings back whatever screen and UI 2492 * decorations that had been hidden while the user was immersed in reading 2493 * the book. 2494 * 2495 * @see #setSystemUiVisibility(int) 2496 */ 2497 public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004; 2498 2499 /** 2500 * Flag for {@link #setSystemUiVisibility(int)}: When using other layout 2501 * flags, we would like a stable view of the content insets given to 2502 * {@link #fitSystemWindows(Rect)}. This means that the insets seen there 2503 * will always represent the worst case that the application can expect 2504 * as a continuous state. In the stock Android UI this is the space for 2505 * the system bar, nav bar, and status bar, but not more transient elements 2506 * such as an input method. 2507 * 2508 * The stable layout your UI sees is based on the system UI modes you can 2509 * switch to. That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 2510 * then you will get a stable layout for changes of the 2511 * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify 2512 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and 2513 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition 2514 * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} 2515 * with a stable layout. (Note that you should avoid using 2516 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.) 2517 * 2518 * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN} 2519 * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}), 2520 * then a hidden status bar will be considered a "stable" state for purposes 2521 * here. This allows your UI to continually hide the status bar, while still 2522 * using the system UI flags to hide the action bar while still retaining 2523 * a stable layout. Note that changing the window fullscreen flag will never 2524 * provide a stable layout for a clean transition. 2525 * 2526 * <p>If you are using ActionBar in 2527 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2528 * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the 2529 * insets it adds to those given to the application. 2530 */ 2531 public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100; 2532 2533 /** 2534 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2535 * to be layed out as if it has requested 2536 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't. This 2537 * allows it to avoid artifacts when switching in and out of that mode, at 2538 * the expense that some of its user interface may be covered by screen 2539 * decorations when they are shown. You can perform layout of your inner 2540 * UI elements to account for the navigation system UI through the 2541 * {@link #fitSystemWindows(Rect)} method. 2542 */ 2543 public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200; 2544 2545 /** 2546 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2547 * to be layed out as if it has requested 2548 * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't. This 2549 * allows it to avoid artifacts when switching in and out of that mode, at 2550 * the expense that some of its user interface may be covered by screen 2551 * decorations when they are shown. You can perform layout of your inner 2552 * UI elements to account for non-fullscreen system UI through the 2553 * {@link #fitSystemWindows(Rect)} method. 2554 */ 2555 public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400; 2556 2557 /** 2558 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2559 * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. If this flag is 2560 * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any 2561 * user interaction. 2562 * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only 2563 * has an effect when used in combination with that flag.</p> 2564 */ 2565 public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800; 2566 2567 /** 2568 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2569 * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation 2570 * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. Use this flag to create an immersive 2571 * experience while also hiding the system bars. If this flag is not set, 2572 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user 2573 * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system 2574 * if the user swipes from the top of the screen. 2575 * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with 2576 * system gestures, such as swiping from the top of the screen. These transient system bars 2577 * will overlay app’s content, may have some degree of transparency, and will automatically 2578 * hide after a short timeout. 2579 * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and 2580 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination 2581 * with one or both of those flags.</p> 2582 */ 2583 public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000; 2584 2585 /** 2586 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 2587 */ 2588 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 2589 2590 /** 2591 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 2592 */ 2593 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 2594 2595 /** 2596 * @hide 2597 * 2598 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2599 * out of the public fields to keep the undefined bits out of the developer's way. 2600 * 2601 * Flag to make the status bar not expandable. Unless you also 2602 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 2603 */ 2604 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 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 hide notification icons and scrolling ticker text. 2613 */ 2614 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 2615 2616 /** 2617 * @hide 2618 * 2619 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2620 * out of the public fields to keep the undefined bits out of the developer's way. 2621 * 2622 * Flag to disable incoming notification alerts. This will not block 2623 * icons, but it will block sound, vibrating and other visual or aural notifications. 2624 */ 2625 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 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 hide only the scrolling ticker. Note that 2634 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 2635 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 2636 */ 2637 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 2638 2639 /** 2640 * @hide 2641 * 2642 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2643 * out of the public fields to keep the undefined bits out of the developer's way. 2644 * 2645 * Flag to hide the center system info area. 2646 */ 2647 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 2648 2649 /** 2650 * @hide 2651 * 2652 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2653 * out of the public fields to keep the undefined bits out of the developer's way. 2654 * 2655 * Flag to hide only the home button. Don't use this 2656 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2657 */ 2658 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 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 back 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_BACK = 0x00400000; 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 clock. You might use this if your activity has 2678 * its own clock making the status bar's clock redundant. 2679 */ 2680 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 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 recent apps button. Don't use this 2689 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2690 */ 2691 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 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 disable the global search gesture. 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_SEARCH = 0x02000000; 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 specify that the status bar is displayed in transient mode. 2711 */ 2712 public static final int STATUS_BAR_TRANSIENT = 0x04000000; 2713 2714 /** 2715 * @hide 2716 * 2717 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2718 * out of the public fields to keep the undefined bits out of the developer's way. 2719 * 2720 * Flag to specify that the navigation bar is displayed in transient mode. 2721 */ 2722 public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000; 2723 2724 /** 2725 * @hide 2726 * 2727 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2728 * out of the public fields to keep the undefined bits out of the developer's way. 2729 * 2730 * Flag to specify that the hidden status bar would like to be shown. 2731 */ 2732 public static final int STATUS_BAR_UNHIDE = 0x10000000; 2733 2734 /** 2735 * @hide 2736 * 2737 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2738 * out of the public fields to keep the undefined bits out of the developer's way. 2739 * 2740 * Flag to specify that the hidden navigation bar would like to be shown. 2741 */ 2742 public static final int NAVIGATION_BAR_UNHIDE = 0x20000000; 2743 2744 /** 2745 * @hide 2746 * 2747 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2748 * out of the public fields to keep the undefined bits out of the developer's way. 2749 * 2750 * Flag to specify that the status bar is displayed in translucent mode. 2751 */ 2752 public static final int STATUS_BAR_TRANSLUCENT = 0x40000000; 2753 2754 /** 2755 * @hide 2756 * 2757 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2758 * out of the public fields to keep the undefined bits out of the developer's way. 2759 * 2760 * Flag to specify that the navigation bar is displayed in translucent mode. 2761 */ 2762 public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000; 2763 2764 /** 2765 * @hide 2766 * 2767 * Whether Recents is visible or not. 2768 */ 2769 public static final int RECENT_APPS_VISIBLE = 0x00004000; 2770 2771 /** 2772 * @hide 2773 * 2774 * Makes system ui transparent. 2775 */ 2776 public static final int SYSTEM_UI_TRANSPARENT = 0x00008000; 2777 2778 /** 2779 * @hide 2780 */ 2781 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FFF; 2782 2783 /** 2784 * These are the system UI flags that can be cleared by events outside 2785 * of an application. Currently this is just the ability to tap on the 2786 * screen while hiding the navigation bar to have it return. 2787 * @hide 2788 */ 2789 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 2790 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 2791 | SYSTEM_UI_FLAG_FULLSCREEN; 2792 2793 /** 2794 * Flags that can impact the layout in relation to system UI. 2795 */ 2796 public static final int SYSTEM_UI_LAYOUT_FLAGS = 2797 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 2798 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 2799 2800 /** @hide */ 2801 @IntDef(flag = true, 2802 value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION }) 2803 @Retention(RetentionPolicy.SOURCE) 2804 public @interface FindViewFlags {} 2805 2806 /** 2807 * Find views that render the specified text. 2808 * 2809 * @see #findViewsWithText(ArrayList, CharSequence, int) 2810 */ 2811 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 2812 2813 /** 2814 * Find find views that contain the specified content description. 2815 * 2816 * @see #findViewsWithText(ArrayList, CharSequence, int) 2817 */ 2818 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 2819 2820 /** 2821 * Find views that contain {@link AccessibilityNodeProvider}. Such 2822 * a View is a root of virtual view hierarchy and may contain the searched 2823 * text. If this flag is set Views with providers are automatically 2824 * added and it is a responsibility of the client to call the APIs of 2825 * the provider to determine whether the virtual tree rooted at this View 2826 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 2827 * representing the virtual views with this text. 2828 * 2829 * @see #findViewsWithText(ArrayList, CharSequence, int) 2830 * 2831 * @hide 2832 */ 2833 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 2834 2835 /** 2836 * The undefined cursor position. 2837 * 2838 * @hide 2839 */ 2840 public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1; 2841 2842 /** 2843 * Indicates that the screen has changed state and is now off. 2844 * 2845 * @see #onScreenStateChanged(int) 2846 */ 2847 public static final int SCREEN_STATE_OFF = 0x0; 2848 2849 /** 2850 * Indicates that the screen has changed state and is now on. 2851 * 2852 * @see #onScreenStateChanged(int) 2853 */ 2854 public static final int SCREEN_STATE_ON = 0x1; 2855 2856 /** 2857 * Indicates no axis of view scrolling. 2858 */ 2859 public static final int SCROLL_AXIS_NONE = 0; 2860 2861 /** 2862 * Indicates scrolling along the horizontal axis. 2863 */ 2864 public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0; 2865 2866 /** 2867 * Indicates scrolling along the vertical axis. 2868 */ 2869 public static final int SCROLL_AXIS_VERTICAL = 1 << 1; 2870 2871 /** 2872 * Controls the over-scroll mode for this view. 2873 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 2874 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 2875 * and {@link #OVER_SCROLL_NEVER}. 2876 */ 2877 private int mOverScrollMode; 2878 2879 /** 2880 * The parent this view is attached to. 2881 * {@hide} 2882 * 2883 * @see #getParent() 2884 */ 2885 protected ViewParent mParent; 2886 2887 /** 2888 * {@hide} 2889 */ 2890 AttachInfo mAttachInfo; 2891 2892 /** 2893 * {@hide} 2894 */ 2895 @ViewDebug.ExportedProperty(flagMapping = { 2896 @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT, 2897 name = "FORCE_LAYOUT"), 2898 @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED, 2899 name = "LAYOUT_REQUIRED"), 2900 @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID, 2901 name = "DRAWING_CACHE_INVALID", outputIf = false), 2902 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true), 2903 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false), 2904 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 2905 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY") 2906 }, formatToHexString = true) 2907 int mPrivateFlags; 2908 int mPrivateFlags2; 2909 int mPrivateFlags3; 2910 2911 /** 2912 * This view's request for the visibility of the status bar. 2913 * @hide 2914 */ 2915 @ViewDebug.ExportedProperty(flagMapping = { 2916 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 2917 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 2918 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 2919 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2920 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2921 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 2922 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 2923 equals = SYSTEM_UI_FLAG_VISIBLE, 2924 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 2925 }, formatToHexString = true) 2926 int mSystemUiVisibility; 2927 2928 /** 2929 * Reference count for transient state. 2930 * @see #setHasTransientState(boolean) 2931 */ 2932 int mTransientStateCount = 0; 2933 2934 /** 2935 * Count of how many windows this view has been attached to. 2936 */ 2937 int mWindowAttachCount; 2938 2939 /** 2940 * The layout parameters associated with this view and used by the parent 2941 * {@link android.view.ViewGroup} to determine how this view should be 2942 * laid out. 2943 * {@hide} 2944 */ 2945 protected ViewGroup.LayoutParams mLayoutParams; 2946 2947 /** 2948 * The view flags hold various views states. 2949 * {@hide} 2950 */ 2951 @ViewDebug.ExportedProperty(formatToHexString = true) 2952 int mViewFlags; 2953 2954 static class TransformationInfo { 2955 /** 2956 * The transform matrix for the View. This transform is calculated internally 2957 * based on the translation, rotation, and scale properties. 2958 * 2959 * Do *not* use this variable directly; instead call getMatrix(), which will 2960 * load the value from the View's RenderNode. 2961 */ 2962 private final Matrix mMatrix = new Matrix(); 2963 2964 /** 2965 * The inverse transform matrix for the View. This transform is calculated 2966 * internally based on the translation, rotation, and scale properties. 2967 * 2968 * Do *not* use this variable directly; instead call getInverseMatrix(), 2969 * which will load the value from the View's RenderNode. 2970 */ 2971 private Matrix mInverseMatrix; 2972 2973 /** 2974 * The opacity of the View. This is a value from 0 to 1, where 0 means 2975 * completely transparent and 1 means completely opaque. 2976 */ 2977 @ViewDebug.ExportedProperty 2978 float mAlpha = 1f; 2979 2980 /** 2981 * The opacity of the view as manipulated by the Fade transition. This is a hidden 2982 * property only used by transitions, which is composited with the other alpha 2983 * values to calculate the final visual alpha value. 2984 */ 2985 float mTransitionAlpha = 1f; 2986 } 2987 2988 TransformationInfo mTransformationInfo; 2989 2990 /** 2991 * Current clip bounds. to which all drawing of this view are constrained. 2992 */ 2993 Rect mClipBounds = null; 2994 2995 private boolean mLastIsOpaque; 2996 2997 /** 2998 * The distance in pixels from the left edge of this view's parent 2999 * to the left edge of this view. 3000 * {@hide} 3001 */ 3002 @ViewDebug.ExportedProperty(category = "layout") 3003 protected int mLeft; 3004 /** 3005 * The distance in pixels from the left edge of this view's parent 3006 * to the right edge of this view. 3007 * {@hide} 3008 */ 3009 @ViewDebug.ExportedProperty(category = "layout") 3010 protected int mRight; 3011 /** 3012 * The distance in pixels from the top edge of this view's parent 3013 * to the top edge of this view. 3014 * {@hide} 3015 */ 3016 @ViewDebug.ExportedProperty(category = "layout") 3017 protected int mTop; 3018 /** 3019 * The distance in pixels from the top edge of this view's parent 3020 * to the bottom edge of this view. 3021 * {@hide} 3022 */ 3023 @ViewDebug.ExportedProperty(category = "layout") 3024 protected int mBottom; 3025 3026 /** 3027 * The offset, in pixels, by which the content of this view is scrolled 3028 * horizontally. 3029 * {@hide} 3030 */ 3031 @ViewDebug.ExportedProperty(category = "scrolling") 3032 protected int mScrollX; 3033 /** 3034 * The offset, in pixels, by which the content of this view is scrolled 3035 * vertically. 3036 * {@hide} 3037 */ 3038 @ViewDebug.ExportedProperty(category = "scrolling") 3039 protected int mScrollY; 3040 3041 /** 3042 * The left padding in pixels, that is the distance in pixels between the 3043 * left edge of this view and the left edge of its content. 3044 * {@hide} 3045 */ 3046 @ViewDebug.ExportedProperty(category = "padding") 3047 protected int mPaddingLeft = 0; 3048 /** 3049 * The right padding in pixels, that is the distance in pixels between the 3050 * right edge of this view and the right edge of its content. 3051 * {@hide} 3052 */ 3053 @ViewDebug.ExportedProperty(category = "padding") 3054 protected int mPaddingRight = 0; 3055 /** 3056 * The top padding in pixels, that is the distance in pixels between the 3057 * top edge of this view and the top edge of its content. 3058 * {@hide} 3059 */ 3060 @ViewDebug.ExportedProperty(category = "padding") 3061 protected int mPaddingTop; 3062 /** 3063 * The bottom padding in pixels, that is the distance in pixels between the 3064 * bottom edge of this view and the bottom edge of its content. 3065 * {@hide} 3066 */ 3067 @ViewDebug.ExportedProperty(category = "padding") 3068 protected int mPaddingBottom; 3069 3070 /** 3071 * The layout insets in pixels, that is the distance in pixels between the 3072 * visible edges of this view its bounds. 3073 */ 3074 private Insets mLayoutInsets; 3075 3076 /** 3077 * Briefly describes the view and is primarily used for accessibility support. 3078 */ 3079 private CharSequence mContentDescription; 3080 3081 /** 3082 * Specifies the id of a view for which this view serves as a label for 3083 * accessibility purposes. 3084 */ 3085 private int mLabelForId = View.NO_ID; 3086 3087 /** 3088 * Predicate for matching labeled view id with its label for 3089 * accessibility purposes. 3090 */ 3091 private MatchLabelForPredicate mMatchLabelForPredicate; 3092 3093 /** 3094 * Predicate for matching a view by its id. 3095 */ 3096 private MatchIdPredicate mMatchIdPredicate; 3097 3098 /** 3099 * Cache the paddingRight set by the user to append to the scrollbar's size. 3100 * 3101 * @hide 3102 */ 3103 @ViewDebug.ExportedProperty(category = "padding") 3104 protected int mUserPaddingRight; 3105 3106 /** 3107 * Cache the paddingBottom set by the user to append to the scrollbar's size. 3108 * 3109 * @hide 3110 */ 3111 @ViewDebug.ExportedProperty(category = "padding") 3112 protected int mUserPaddingBottom; 3113 3114 /** 3115 * Cache the paddingLeft set by the user to append to the scrollbar's size. 3116 * 3117 * @hide 3118 */ 3119 @ViewDebug.ExportedProperty(category = "padding") 3120 protected int mUserPaddingLeft; 3121 3122 /** 3123 * Cache the paddingStart set by the user to append to the scrollbar's size. 3124 * 3125 */ 3126 @ViewDebug.ExportedProperty(category = "padding") 3127 int mUserPaddingStart; 3128 3129 /** 3130 * Cache the paddingEnd set by the user to append to the scrollbar's size. 3131 * 3132 */ 3133 @ViewDebug.ExportedProperty(category = "padding") 3134 int mUserPaddingEnd; 3135 3136 /** 3137 * Cache initial left padding. 3138 * 3139 * @hide 3140 */ 3141 int mUserPaddingLeftInitial; 3142 3143 /** 3144 * Cache initial right padding. 3145 * 3146 * @hide 3147 */ 3148 int mUserPaddingRightInitial; 3149 3150 /** 3151 * Default undefined padding 3152 */ 3153 private static final int UNDEFINED_PADDING = Integer.MIN_VALUE; 3154 3155 /** 3156 * Cache if a left padding has been defined 3157 */ 3158 private boolean mLeftPaddingDefined = false; 3159 3160 /** 3161 * Cache if a right padding has been defined 3162 */ 3163 private boolean mRightPaddingDefined = false; 3164 3165 /** 3166 * @hide 3167 */ 3168 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 3169 /** 3170 * @hide 3171 */ 3172 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 3173 3174 private LongSparseLongArray mMeasureCache; 3175 3176 @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_") 3177 private Drawable mBackground; 3178 private ColorStateList mBackgroundTintList = null; 3179 private PorterDuff.Mode mBackgroundTintMode = PorterDuff.Mode.SRC_ATOP; 3180 private boolean mHasBackgroundTint = false; 3181 3182 /** 3183 * RenderNode used for backgrounds. 3184 * <p> 3185 * When non-null and valid, this is expected to contain an up-to-date copy 3186 * of the background drawable. It is cleared on temporary detach, and reset 3187 * on cleanup. 3188 */ 3189 private RenderNode mBackgroundRenderNode; 3190 3191 private int mBackgroundResource; 3192 private boolean mBackgroundSizeChanged; 3193 3194 private String mTransitionName; 3195 3196 static class ListenerInfo { 3197 /** 3198 * Listener used to dispatch focus change events. 3199 * This field should be made private, so it is hidden from the SDK. 3200 * {@hide} 3201 */ 3202 protected OnFocusChangeListener mOnFocusChangeListener; 3203 3204 /** 3205 * Listeners for layout change events. 3206 */ 3207 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 3208 3209 /** 3210 * Listeners for attach events. 3211 */ 3212 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 3213 3214 /** 3215 * Listener used to dispatch click events. 3216 * This field should be made private, so it is hidden from the SDK. 3217 * {@hide} 3218 */ 3219 public OnClickListener mOnClickListener; 3220 3221 /** 3222 * Listener used to dispatch long click events. 3223 * This field should be made private, so it is hidden from the SDK. 3224 * {@hide} 3225 */ 3226 protected OnLongClickListener mOnLongClickListener; 3227 3228 /** 3229 * Listener used to build the context menu. 3230 * This field should be made private, so it is hidden from the SDK. 3231 * {@hide} 3232 */ 3233 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 3234 3235 private OnKeyListener mOnKeyListener; 3236 3237 private OnTouchListener mOnTouchListener; 3238 3239 private OnHoverListener mOnHoverListener; 3240 3241 private OnGenericMotionListener mOnGenericMotionListener; 3242 3243 private OnDragListener mOnDragListener; 3244 3245 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 3246 3247 OnApplyWindowInsetsListener mOnApplyWindowInsetsListener; 3248 } 3249 3250 ListenerInfo mListenerInfo; 3251 3252 /** 3253 * The application environment this view lives in. 3254 * This field should be made private, so it is hidden from the SDK. 3255 * {@hide} 3256 */ 3257 protected Context mContext; 3258 3259 private final Resources mResources; 3260 3261 private ScrollabilityCache mScrollCache; 3262 3263 private int[] mDrawableState = null; 3264 3265 ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND; 3266 3267 /** 3268 * Animator that automatically runs based on state changes. 3269 */ 3270 private StateListAnimator mStateListAnimator; 3271 3272 /** 3273 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 3274 * the user may specify which view to go to next. 3275 */ 3276 private int mNextFocusLeftId = View.NO_ID; 3277 3278 /** 3279 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 3280 * the user may specify which view to go to next. 3281 */ 3282 private int mNextFocusRightId = View.NO_ID; 3283 3284 /** 3285 * When this view has focus and the next focus is {@link #FOCUS_UP}, 3286 * the user may specify which view to go to next. 3287 */ 3288 private int mNextFocusUpId = View.NO_ID; 3289 3290 /** 3291 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 3292 * the user may specify which view to go to next. 3293 */ 3294 private int mNextFocusDownId = View.NO_ID; 3295 3296 /** 3297 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 3298 * the user may specify which view to go to next. 3299 */ 3300 int mNextFocusForwardId = View.NO_ID; 3301 3302 private CheckForLongPress mPendingCheckForLongPress; 3303 private CheckForTap mPendingCheckForTap = null; 3304 private PerformClick mPerformClick; 3305 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 3306 3307 private UnsetPressedState mUnsetPressedState; 3308 3309 /** 3310 * Whether the long press's action has been invoked. The tap's action is invoked on the 3311 * up event while a long press is invoked as soon as the long press duration is reached, so 3312 * a long press could be performed before the tap is checked, in which case the tap's action 3313 * should not be invoked. 3314 */ 3315 private boolean mHasPerformedLongPress; 3316 3317 /** 3318 * The minimum height of the view. We'll try our best to have the height 3319 * of this view to at least this amount. 3320 */ 3321 @ViewDebug.ExportedProperty(category = "measurement") 3322 private int mMinHeight; 3323 3324 /** 3325 * The minimum width of the view. We'll try our best to have the width 3326 * of this view to at least this amount. 3327 */ 3328 @ViewDebug.ExportedProperty(category = "measurement") 3329 private int mMinWidth; 3330 3331 /** 3332 * The delegate to handle touch events that are physically in this view 3333 * but should be handled by another view. 3334 */ 3335 private TouchDelegate mTouchDelegate = null; 3336 3337 /** 3338 * Solid color to use as a background when creating the drawing cache. Enables 3339 * the cache to use 16 bit bitmaps instead of 32 bit. 3340 */ 3341 private int mDrawingCacheBackgroundColor = 0; 3342 3343 /** 3344 * Special tree observer used when mAttachInfo is null. 3345 */ 3346 private ViewTreeObserver mFloatingTreeObserver; 3347 3348 /** 3349 * Cache the touch slop from the context that created the view. 3350 */ 3351 private int mTouchSlop; 3352 3353 /** 3354 * Object that handles automatic animation of view properties. 3355 */ 3356 private ViewPropertyAnimator mAnimator = null; 3357 3358 /** 3359 * Flag indicating that a drag can cross window boundaries. When 3360 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 3361 * with this flag set, all visible applications will be able to participate 3362 * in the drag operation and receive the dragged content. 3363 * 3364 * @hide 3365 */ 3366 public static final int DRAG_FLAG_GLOBAL = 1; 3367 3368 /** 3369 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 3370 */ 3371 private float mVerticalScrollFactor; 3372 3373 /** 3374 * Position of the vertical scroll bar. 3375 */ 3376 private int mVerticalScrollbarPosition; 3377 3378 /** 3379 * Position the scroll bar at the default position as determined by the system. 3380 */ 3381 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 3382 3383 /** 3384 * Position the scroll bar along the left edge. 3385 */ 3386 public static final int SCROLLBAR_POSITION_LEFT = 1; 3387 3388 /** 3389 * Position the scroll bar along the right edge. 3390 */ 3391 public static final int SCROLLBAR_POSITION_RIGHT = 2; 3392 3393 /** 3394 * Indicates that the view does not have a layer. 3395 * 3396 * @see #getLayerType() 3397 * @see #setLayerType(int, android.graphics.Paint) 3398 * @see #LAYER_TYPE_SOFTWARE 3399 * @see #LAYER_TYPE_HARDWARE 3400 */ 3401 public static final int LAYER_TYPE_NONE = 0; 3402 3403 /** 3404 * <p>Indicates that the view has a software layer. A software layer is backed 3405 * by a bitmap and causes the view to be rendered using Android's software 3406 * rendering pipeline, even if hardware acceleration is enabled.</p> 3407 * 3408 * <p>Software layers have various usages:</p> 3409 * <p>When the application is not using hardware acceleration, a software layer 3410 * is useful to apply a specific color filter and/or blending mode and/or 3411 * translucency to a view and all its children.</p> 3412 * <p>When the application is using hardware acceleration, a software layer 3413 * is useful to render drawing primitives not supported by the hardware 3414 * accelerated pipeline. It can also be used to cache a complex view tree 3415 * into a texture and reduce the complexity of drawing operations. For instance, 3416 * when animating a complex view tree with a translation, a software layer can 3417 * be used to render the view tree only once.</p> 3418 * <p>Software layers should be avoided when the affected view tree updates 3419 * often. Every update will require to re-render the software layer, which can 3420 * potentially be slow (particularly when hardware acceleration is turned on 3421 * since the layer will have to be uploaded into a hardware texture after every 3422 * update.)</p> 3423 * 3424 * @see #getLayerType() 3425 * @see #setLayerType(int, android.graphics.Paint) 3426 * @see #LAYER_TYPE_NONE 3427 * @see #LAYER_TYPE_HARDWARE 3428 */ 3429 public static final int LAYER_TYPE_SOFTWARE = 1; 3430 3431 /** 3432 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 3433 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 3434 * OpenGL hardware) and causes the view to be rendered using Android's hardware 3435 * rendering pipeline, but only if hardware acceleration is turned on for the 3436 * view hierarchy. When hardware acceleration is turned off, hardware layers 3437 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 3438 * 3439 * <p>A hardware layer is useful to apply a specific color filter and/or 3440 * blending mode and/or translucency to a view and all its children.</p> 3441 * <p>A hardware layer can be used to cache a complex view tree into a 3442 * texture and reduce the complexity of drawing operations. For instance, 3443 * when animating a complex view tree with a translation, a hardware layer can 3444 * be used to render the view tree only once.</p> 3445 * <p>A hardware layer can also be used to increase the rendering quality when 3446 * rotation transformations are applied on a view. It can also be used to 3447 * prevent potential clipping issues when applying 3D transforms on a view.</p> 3448 * 3449 * @see #getLayerType() 3450 * @see #setLayerType(int, android.graphics.Paint) 3451 * @see #LAYER_TYPE_NONE 3452 * @see #LAYER_TYPE_SOFTWARE 3453 */ 3454 public static final int LAYER_TYPE_HARDWARE = 2; 3455 3456 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 3457 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 3458 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 3459 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 3460 }) 3461 int mLayerType = LAYER_TYPE_NONE; 3462 Paint mLayerPaint; 3463 3464 /** 3465 * Set to true when drawing cache is enabled and cannot be created. 3466 * 3467 * @hide 3468 */ 3469 public boolean mCachingFailed; 3470 private Bitmap mDrawingCache; 3471 private Bitmap mUnscaledDrawingCache; 3472 3473 /** 3474 * RenderNode holding View properties, potentially holding a DisplayList of View content. 3475 * <p> 3476 * When non-null and valid, this is expected to contain an up-to-date copy 3477 * of the View content. Its DisplayList content is cleared on temporary detach and reset on 3478 * cleanup. 3479 */ 3480 final RenderNode mRenderNode; 3481 3482 /** 3483 * Set to true when the view is sending hover accessibility events because it 3484 * is the innermost hovered view. 3485 */ 3486 private boolean mSendingHoverAccessibilityEvents; 3487 3488 /** 3489 * Delegate for injecting accessibility functionality. 3490 */ 3491 AccessibilityDelegate mAccessibilityDelegate; 3492 3493 /** 3494 * The view's overlay layer. Developers get a reference to the overlay via getOverlay() 3495 * and add/remove objects to/from the overlay directly through the Overlay methods. 3496 */ 3497 ViewOverlay mOverlay; 3498 3499 /** 3500 * The currently active parent view for receiving delegated nested scrolling events. 3501 * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared 3502 * by {@link #stopNestedScroll()} at the same point where we clear 3503 * requestDisallowInterceptTouchEvent. 3504 */ 3505 private ViewParent mNestedScrollingParent; 3506 3507 /** 3508 * Consistency verifier for debugging purposes. 3509 * @hide 3510 */ 3511 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 3512 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 3513 new InputEventConsistencyVerifier(this, 0) : null; 3514 3515 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); 3516 3517 private int[] mTempNestedScrollConsumed; 3518 3519 /** 3520 * An overlay is going to draw this View instead of being drawn as part of this 3521 * View's parent. mGhostView is the View in the Overlay that must be invalidated 3522 * when this view is invalidated. 3523 */ 3524 GhostView mGhostView; 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 sCompatibilityDone = true; 3561 } 3562 } 3563 3564 /** 3565 * Constructor that is called when inflating a view from XML. This is called 3566 * when a view is being constructed from an XML file, supplying attributes 3567 * that were specified in the XML file. This version uses a default style of 3568 * 0, so the only attribute values applied are those in the Context's Theme 3569 * and the given AttributeSet. 3570 * 3571 * <p> 3572 * The method onFinishInflate() will be called after all children have been 3573 * added. 3574 * 3575 * @param context The Context the view is running in, through which it can 3576 * access the current theme, resources, etc. 3577 * @param attrs The attributes of the XML tag that is inflating the view. 3578 * @see #View(Context, AttributeSet, int) 3579 */ 3580 public View(Context context, AttributeSet attrs) { 3581 this(context, attrs, 0); 3582 } 3583 3584 /** 3585 * Perform inflation from XML and apply a class-specific base style from a 3586 * theme attribute. This constructor of View allows subclasses to use their 3587 * own base style when they are inflating. For example, a Button class's 3588 * constructor would call this version of the super class constructor and 3589 * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this 3590 * allows the theme's button style to modify all of the base view attributes 3591 * (in particular its background) as well as the Button class's attributes. 3592 * 3593 * @param context The Context the view is running in, through which it can 3594 * access the current theme, resources, etc. 3595 * @param attrs The attributes of the XML tag that is inflating the view. 3596 * @param defStyleAttr An attribute in the current theme that contains a 3597 * reference to a style resource that supplies default values for 3598 * the view. Can be 0 to not look for defaults. 3599 * @see #View(Context, AttributeSet) 3600 */ 3601 public View(Context context, AttributeSet attrs, int defStyleAttr) { 3602 this(context, attrs, defStyleAttr, 0); 3603 } 3604 3605 /** 3606 * Perform inflation from XML and apply a class-specific base style from a 3607 * theme attribute or style resource. This constructor of View allows 3608 * subclasses to use their own base style when they are inflating. 3609 * <p> 3610 * When determining the final value of a particular attribute, there are 3611 * four inputs that come into play: 3612 * <ol> 3613 * <li>Any attribute values in the given AttributeSet. 3614 * <li>The style resource specified in the AttributeSet (named "style"). 3615 * <li>The default style specified by <var>defStyleAttr</var>. 3616 * <li>The default style specified by <var>defStyleRes</var>. 3617 * <li>The base values in this theme. 3618 * </ol> 3619 * <p> 3620 * Each of these inputs is considered in-order, with the first listed taking 3621 * precedence over the following ones. In other words, if in the 3622 * AttributeSet you have supplied <code><Button * textColor="#ff000000"></code> 3623 * , then the button's text will <em>always</em> be black, regardless of 3624 * what is specified in any of the styles. 3625 * 3626 * @param context The Context the view is running in, through which it can 3627 * access the current theme, resources, etc. 3628 * @param attrs The attributes of the XML tag that is inflating the view. 3629 * @param defStyleAttr An attribute in the current theme that contains a 3630 * reference to a style resource that supplies default values for 3631 * the view. Can be 0 to not look for defaults. 3632 * @param defStyleRes A resource identifier of a style resource that 3633 * supplies default values for the view, used only if 3634 * defStyleAttr is 0 or can not be found in the theme. Can be 0 3635 * to not look for defaults. 3636 * @see #View(Context, AttributeSet, int) 3637 */ 3638 public View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 3639 this(context); 3640 3641 final TypedArray a = context.obtainStyledAttributes( 3642 attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes); 3643 3644 Drawable background = null; 3645 3646 int leftPadding = -1; 3647 int topPadding = -1; 3648 int rightPadding = -1; 3649 int bottomPadding = -1; 3650 int startPadding = UNDEFINED_PADDING; 3651 int endPadding = UNDEFINED_PADDING; 3652 3653 int padding = -1; 3654 3655 int viewFlagValues = 0; 3656 int viewFlagMasks = 0; 3657 3658 boolean setScrollContainer = false; 3659 3660 int x = 0; 3661 int y = 0; 3662 3663 float tx = 0; 3664 float ty = 0; 3665 float tz = 0; 3666 float elevation = 0; 3667 float rotation = 0; 3668 float rotationX = 0; 3669 float rotationY = 0; 3670 float sx = 1f; 3671 float sy = 1f; 3672 boolean transformSet = false; 3673 3674 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 3675 int overScrollMode = mOverScrollMode; 3676 boolean initializeScrollbars = false; 3677 3678 boolean startPaddingDefined = false; 3679 boolean endPaddingDefined = false; 3680 boolean leftPaddingDefined = false; 3681 boolean rightPaddingDefined = false; 3682 3683 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3684 3685 final int N = a.getIndexCount(); 3686 for (int i = 0; i < N; i++) { 3687 int attr = a.getIndex(i); 3688 switch (attr) { 3689 case com.android.internal.R.styleable.View_background: 3690 background = a.getDrawable(attr); 3691 break; 3692 case com.android.internal.R.styleable.View_padding: 3693 padding = a.getDimensionPixelSize(attr, -1); 3694 mUserPaddingLeftInitial = padding; 3695 mUserPaddingRightInitial = padding; 3696 leftPaddingDefined = true; 3697 rightPaddingDefined = true; 3698 break; 3699 case com.android.internal.R.styleable.View_paddingLeft: 3700 leftPadding = a.getDimensionPixelSize(attr, -1); 3701 mUserPaddingLeftInitial = leftPadding; 3702 leftPaddingDefined = true; 3703 break; 3704 case com.android.internal.R.styleable.View_paddingTop: 3705 topPadding = a.getDimensionPixelSize(attr, -1); 3706 break; 3707 case com.android.internal.R.styleable.View_paddingRight: 3708 rightPadding = a.getDimensionPixelSize(attr, -1); 3709 mUserPaddingRightInitial = rightPadding; 3710 rightPaddingDefined = true; 3711 break; 3712 case com.android.internal.R.styleable.View_paddingBottom: 3713 bottomPadding = a.getDimensionPixelSize(attr, -1); 3714 break; 3715 case com.android.internal.R.styleable.View_paddingStart: 3716 startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3717 startPaddingDefined = (startPadding != UNDEFINED_PADDING); 3718 break; 3719 case com.android.internal.R.styleable.View_paddingEnd: 3720 endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3721 endPaddingDefined = (endPadding != UNDEFINED_PADDING); 3722 break; 3723 case com.android.internal.R.styleable.View_scrollX: 3724 x = a.getDimensionPixelOffset(attr, 0); 3725 break; 3726 case com.android.internal.R.styleable.View_scrollY: 3727 y = a.getDimensionPixelOffset(attr, 0); 3728 break; 3729 case com.android.internal.R.styleable.View_alpha: 3730 setAlpha(a.getFloat(attr, 1f)); 3731 break; 3732 case com.android.internal.R.styleable.View_transformPivotX: 3733 setPivotX(a.getDimensionPixelOffset(attr, 0)); 3734 break; 3735 case com.android.internal.R.styleable.View_transformPivotY: 3736 setPivotY(a.getDimensionPixelOffset(attr, 0)); 3737 break; 3738 case com.android.internal.R.styleable.View_translationX: 3739 tx = a.getDimensionPixelOffset(attr, 0); 3740 transformSet = true; 3741 break; 3742 case com.android.internal.R.styleable.View_translationY: 3743 ty = a.getDimensionPixelOffset(attr, 0); 3744 transformSet = true; 3745 break; 3746 case com.android.internal.R.styleable.View_translationZ: 3747 tz = a.getDimensionPixelOffset(attr, 0); 3748 transformSet = true; 3749 break; 3750 case com.android.internal.R.styleable.View_elevation: 3751 elevation = a.getDimensionPixelOffset(attr, 0); 3752 transformSet = true; 3753 break; 3754 case com.android.internal.R.styleable.View_rotation: 3755 rotation = a.getFloat(attr, 0); 3756 transformSet = true; 3757 break; 3758 case com.android.internal.R.styleable.View_rotationX: 3759 rotationX = a.getFloat(attr, 0); 3760 transformSet = true; 3761 break; 3762 case com.android.internal.R.styleable.View_rotationY: 3763 rotationY = a.getFloat(attr, 0); 3764 transformSet = true; 3765 break; 3766 case com.android.internal.R.styleable.View_scaleX: 3767 sx = a.getFloat(attr, 1f); 3768 transformSet = true; 3769 break; 3770 case com.android.internal.R.styleable.View_scaleY: 3771 sy = a.getFloat(attr, 1f); 3772 transformSet = true; 3773 break; 3774 case com.android.internal.R.styleable.View_id: 3775 mID = a.getResourceId(attr, NO_ID); 3776 break; 3777 case com.android.internal.R.styleable.View_tag: 3778 mTag = a.getText(attr); 3779 break; 3780 case com.android.internal.R.styleable.View_fitsSystemWindows: 3781 if (a.getBoolean(attr, false)) { 3782 viewFlagValues |= FITS_SYSTEM_WINDOWS; 3783 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 3784 } 3785 break; 3786 case com.android.internal.R.styleable.View_focusable: 3787 if (a.getBoolean(attr, false)) { 3788 viewFlagValues |= FOCUSABLE; 3789 viewFlagMasks |= FOCUSABLE_MASK; 3790 } 3791 break; 3792 case com.android.internal.R.styleable.View_focusableInTouchMode: 3793 if (a.getBoolean(attr, false)) { 3794 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 3795 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 3796 } 3797 break; 3798 case com.android.internal.R.styleable.View_clickable: 3799 if (a.getBoolean(attr, false)) { 3800 viewFlagValues |= CLICKABLE; 3801 viewFlagMasks |= CLICKABLE; 3802 } 3803 break; 3804 case com.android.internal.R.styleable.View_longClickable: 3805 if (a.getBoolean(attr, false)) { 3806 viewFlagValues |= LONG_CLICKABLE; 3807 viewFlagMasks |= LONG_CLICKABLE; 3808 } 3809 break; 3810 case com.android.internal.R.styleable.View_saveEnabled: 3811 if (!a.getBoolean(attr, true)) { 3812 viewFlagValues |= SAVE_DISABLED; 3813 viewFlagMasks |= SAVE_DISABLED_MASK; 3814 } 3815 break; 3816 case com.android.internal.R.styleable.View_duplicateParentState: 3817 if (a.getBoolean(attr, false)) { 3818 viewFlagValues |= DUPLICATE_PARENT_STATE; 3819 viewFlagMasks |= DUPLICATE_PARENT_STATE; 3820 } 3821 break; 3822 case com.android.internal.R.styleable.View_visibility: 3823 final int visibility = a.getInt(attr, 0); 3824 if (visibility != 0) { 3825 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 3826 viewFlagMasks |= VISIBILITY_MASK; 3827 } 3828 break; 3829 case com.android.internal.R.styleable.View_layoutDirection: 3830 // Clear any layout direction flags (included resolved bits) already set 3831 mPrivateFlags2 &= 3832 ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK); 3833 // Set the layout direction flags depending on the value of the attribute 3834 final int layoutDirection = a.getInt(attr, -1); 3835 final int value = (layoutDirection != -1) ? 3836 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 3837 mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT); 3838 break; 3839 case com.android.internal.R.styleable.View_drawingCacheQuality: 3840 final int cacheQuality = a.getInt(attr, 0); 3841 if (cacheQuality != 0) { 3842 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 3843 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 3844 } 3845 break; 3846 case com.android.internal.R.styleable.View_contentDescription: 3847 setContentDescription(a.getString(attr)); 3848 break; 3849 case com.android.internal.R.styleable.View_labelFor: 3850 setLabelFor(a.getResourceId(attr, NO_ID)); 3851 break; 3852 case com.android.internal.R.styleable.View_soundEffectsEnabled: 3853 if (!a.getBoolean(attr, true)) { 3854 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 3855 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 3856 } 3857 break; 3858 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 3859 if (!a.getBoolean(attr, true)) { 3860 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 3861 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 3862 } 3863 break; 3864 case R.styleable.View_scrollbars: 3865 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 3866 if (scrollbars != SCROLLBARS_NONE) { 3867 viewFlagValues |= scrollbars; 3868 viewFlagMasks |= SCROLLBARS_MASK; 3869 initializeScrollbars = true; 3870 } 3871 break; 3872 //noinspection deprecation 3873 case R.styleable.View_fadingEdge: 3874 if (targetSdkVersion >= ICE_CREAM_SANDWICH) { 3875 // Ignore the attribute starting with ICS 3876 break; 3877 } 3878 // With builds < ICS, fall through and apply fading edges 3879 case R.styleable.View_requiresFadingEdge: 3880 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 3881 if (fadingEdge != FADING_EDGE_NONE) { 3882 viewFlagValues |= fadingEdge; 3883 viewFlagMasks |= FADING_EDGE_MASK; 3884 initializeFadingEdgeInternal(a); 3885 } 3886 break; 3887 case R.styleable.View_scrollbarStyle: 3888 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 3889 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3890 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 3891 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 3892 } 3893 break; 3894 case R.styleable.View_isScrollContainer: 3895 setScrollContainer = true; 3896 if (a.getBoolean(attr, false)) { 3897 setScrollContainer(true); 3898 } 3899 break; 3900 case com.android.internal.R.styleable.View_keepScreenOn: 3901 if (a.getBoolean(attr, false)) { 3902 viewFlagValues |= KEEP_SCREEN_ON; 3903 viewFlagMasks |= KEEP_SCREEN_ON; 3904 } 3905 break; 3906 case R.styleable.View_filterTouchesWhenObscured: 3907 if (a.getBoolean(attr, false)) { 3908 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 3909 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 3910 } 3911 break; 3912 case R.styleable.View_nextFocusLeft: 3913 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 3914 break; 3915 case R.styleable.View_nextFocusRight: 3916 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 3917 break; 3918 case R.styleable.View_nextFocusUp: 3919 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 3920 break; 3921 case R.styleable.View_nextFocusDown: 3922 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 3923 break; 3924 case R.styleable.View_nextFocusForward: 3925 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 3926 break; 3927 case R.styleable.View_minWidth: 3928 mMinWidth = a.getDimensionPixelSize(attr, 0); 3929 break; 3930 case R.styleable.View_minHeight: 3931 mMinHeight = a.getDimensionPixelSize(attr, 0); 3932 break; 3933 case R.styleable.View_onClick: 3934 if (context.isRestricted()) { 3935 throw new IllegalStateException("The android:onClick attribute cannot " 3936 + "be used within a restricted context"); 3937 } 3938 3939 final String handlerName = a.getString(attr); 3940 if (handlerName != null) { 3941 setOnClickListener(new OnClickListener() { 3942 private Method mHandler; 3943 3944 public void onClick(View v) { 3945 if (mHandler == null) { 3946 try { 3947 mHandler = getContext().getClass().getMethod(handlerName, 3948 View.class); 3949 } catch (NoSuchMethodException e) { 3950 int id = getId(); 3951 String idText = id == NO_ID ? "" : " with id '" 3952 + getContext().getResources().getResourceEntryName( 3953 id) + "'"; 3954 throw new IllegalStateException("Could not find a method " + 3955 handlerName + "(View) in the activity " 3956 + getContext().getClass() + " for onClick handler" 3957 + " on view " + View.this.getClass() + idText, e); 3958 } 3959 } 3960 3961 try { 3962 mHandler.invoke(getContext(), View.this); 3963 } catch (IllegalAccessException e) { 3964 throw new IllegalStateException("Could not execute non " 3965 + "public method of the activity", e); 3966 } catch (InvocationTargetException e) { 3967 throw new IllegalStateException("Could not execute " 3968 + "method of the activity", e); 3969 } 3970 } 3971 }); 3972 } 3973 break; 3974 case R.styleable.View_overScrollMode: 3975 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 3976 break; 3977 case R.styleable.View_verticalScrollbarPosition: 3978 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 3979 break; 3980 case R.styleable.View_layerType: 3981 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 3982 break; 3983 case R.styleable.View_textDirection: 3984 // Clear any text direction flag already set 3985 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 3986 // Set the text direction flags depending on the value of the attribute 3987 final int textDirection = a.getInt(attr, -1); 3988 if (textDirection != -1) { 3989 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection]; 3990 } 3991 break; 3992 case R.styleable.View_textAlignment: 3993 // Clear any text alignment flag already set 3994 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 3995 // Set the text alignment flag depending on the value of the attribute 3996 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); 3997 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment]; 3998 break; 3999 case R.styleable.View_importantForAccessibility: 4000 setImportantForAccessibility(a.getInt(attr, 4001 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); 4002 break; 4003 case R.styleable.View_accessibilityLiveRegion: 4004 setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT)); 4005 break; 4006 case R.styleable.View_transitionName: 4007 setTransitionName(a.getString(attr)); 4008 break; 4009 case R.styleable.View_nestedScrollingEnabled: 4010 setNestedScrollingEnabled(a.getBoolean(attr, false)); 4011 break; 4012 case R.styleable.View_stateListAnimator: 4013 setStateListAnimator(AnimatorInflater.loadStateListAnimator(context, 4014 a.getResourceId(attr, 0))); 4015 break; 4016 case R.styleable.View_backgroundTint: 4017 // This will get applied later during setBackground(). 4018 mBackgroundTintList = a.getColorStateList(R.styleable.View_backgroundTint); 4019 mHasBackgroundTint = true; 4020 break; 4021 case R.styleable.View_backgroundTintMode: 4022 // This will get applied later during setBackground(). 4023 mBackgroundTintMode = Drawable.parseTintMode(a.getInt( 4024 R.styleable.View_backgroundTintMode, -1), mBackgroundTintMode); 4025 break; 4026 } 4027 } 4028 4029 setOverScrollMode(overScrollMode); 4030 4031 // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet 4032 // the resolved layout direction). Those cached values will be used later during padding 4033 // resolution. 4034 mUserPaddingStart = startPadding; 4035 mUserPaddingEnd = endPadding; 4036 4037 if (background != null) { 4038 setBackground(background); 4039 } 4040 4041 // setBackground above will record that padding is currently provided by the background. 4042 // If we have padding specified via xml, record that here instead and use it. 4043 mLeftPaddingDefined = leftPaddingDefined; 4044 mRightPaddingDefined = rightPaddingDefined; 4045 4046 if (padding >= 0) { 4047 leftPadding = padding; 4048 topPadding = padding; 4049 rightPadding = padding; 4050 bottomPadding = padding; 4051 mUserPaddingLeftInitial = padding; 4052 mUserPaddingRightInitial = padding; 4053 } 4054 4055 if (isRtlCompatibilityMode()) { 4056 // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case. 4057 // left / right padding are used if defined (meaning here nothing to do). If they are not 4058 // defined and start / end padding are defined (e.g. in Frameworks resources), then we use 4059 // start / end and resolve them as left / right (layout direction is not taken into account). 4060 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4061 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4062 // defined. 4063 if (!mLeftPaddingDefined && startPaddingDefined) { 4064 leftPadding = startPadding; 4065 } 4066 mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial; 4067 if (!mRightPaddingDefined && endPaddingDefined) { 4068 rightPadding = endPadding; 4069 } 4070 mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial; 4071 } else { 4072 // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right 4073 // values defined. Otherwise, left /right values are used. 4074 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4075 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4076 // defined. 4077 final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined; 4078 4079 if (mLeftPaddingDefined && !hasRelativePadding) { 4080 mUserPaddingLeftInitial = leftPadding; 4081 } 4082 if (mRightPaddingDefined && !hasRelativePadding) { 4083 mUserPaddingRightInitial = rightPadding; 4084 } 4085 } 4086 4087 internalSetPadding( 4088 mUserPaddingLeftInitial, 4089 topPadding >= 0 ? topPadding : mPaddingTop, 4090 mUserPaddingRightInitial, 4091 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 4092 4093 if (viewFlagMasks != 0) { 4094 setFlags(viewFlagValues, viewFlagMasks); 4095 } 4096 4097 if (initializeScrollbars) { 4098 initializeScrollbarsInternal(a); 4099 } 4100 4101 a.recycle(); 4102 4103 // Needs to be called after mViewFlags is set 4104 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 4105 recomputePadding(); 4106 } 4107 4108 if (x != 0 || y != 0) { 4109 scrollTo(x, y); 4110 } 4111 4112 if (transformSet) { 4113 setTranslationX(tx); 4114 setTranslationY(ty); 4115 setTranslationZ(tz); 4116 setElevation(elevation); 4117 setRotation(rotation); 4118 setRotationX(rotationX); 4119 setRotationY(rotationY); 4120 setScaleX(sx); 4121 setScaleY(sy); 4122 } 4123 4124 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 4125 setScrollContainer(true); 4126 } 4127 4128 computeOpaqueFlags(); 4129 } 4130 4131 /** 4132 * Non-public constructor for use in testing 4133 */ 4134 View() { 4135 mResources = null; 4136 mRenderNode = RenderNode.create(getClass().getName()); 4137 } 4138 4139 public String toString() { 4140 StringBuilder out = new StringBuilder(128); 4141 out.append(getClass().getName()); 4142 out.append('{'); 4143 out.append(Integer.toHexString(System.identityHashCode(this))); 4144 out.append(' '); 4145 switch (mViewFlags&VISIBILITY_MASK) { 4146 case VISIBLE: out.append('V'); break; 4147 case INVISIBLE: out.append('I'); break; 4148 case GONE: out.append('G'); break; 4149 default: out.append('.'); break; 4150 } 4151 out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.'); 4152 out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.'); 4153 out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D'); 4154 out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.'); 4155 out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.'); 4156 out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.'); 4157 out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.'); 4158 out.append(' '); 4159 out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.'); 4160 out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.'); 4161 out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.'); 4162 if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) { 4163 out.append('p'); 4164 } else { 4165 out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.'); 4166 } 4167 out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.'); 4168 out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.'); 4169 out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.'); 4170 out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.'); 4171 out.append(' '); 4172 out.append(mLeft); 4173 out.append(','); 4174 out.append(mTop); 4175 out.append('-'); 4176 out.append(mRight); 4177 out.append(','); 4178 out.append(mBottom); 4179 final int id = getId(); 4180 if (id != NO_ID) { 4181 out.append(" #"); 4182 out.append(Integer.toHexString(id)); 4183 final Resources r = mResources; 4184 if (Resources.resourceHasPackage(id) && r != null) { 4185 try { 4186 String pkgname; 4187 switch (id&0xff000000) { 4188 case 0x7f000000: 4189 pkgname="app"; 4190 break; 4191 case 0x01000000: 4192 pkgname="android"; 4193 break; 4194 default: 4195 pkgname = r.getResourcePackageName(id); 4196 break; 4197 } 4198 String typename = r.getResourceTypeName(id); 4199 String entryname = r.getResourceEntryName(id); 4200 out.append(" "); 4201 out.append(pkgname); 4202 out.append(":"); 4203 out.append(typename); 4204 out.append("/"); 4205 out.append(entryname); 4206 } catch (Resources.NotFoundException e) { 4207 } 4208 } 4209 } 4210 out.append("}"); 4211 return out.toString(); 4212 } 4213 4214 /** 4215 * <p> 4216 * Initializes the fading edges from a given set of styled attributes. This 4217 * method should be called by subclasses that need fading edges and when an 4218 * instance of these subclasses is created programmatically rather than 4219 * being inflated from XML. This method is automatically called when the XML 4220 * is inflated. 4221 * </p> 4222 * 4223 * @param a the styled attributes set to initialize the fading edges from 4224 */ 4225 protected void initializeFadingEdge(TypedArray a) { 4226 // This method probably shouldn't have been included in the SDK to begin with. 4227 // It relies on 'a' having been initialized using an attribute filter array that is 4228 // not publicly available to the SDK. The old method has been renamed 4229 // to initializeFadingEdgeInternal and hidden for framework use only; 4230 // this one initializes using defaults to make it safe to call for apps. 4231 4232 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 4233 4234 initializeFadingEdgeInternal(arr); 4235 4236 arr.recycle(); 4237 } 4238 4239 /** 4240 * <p> 4241 * Initializes the fading edges from a given set of styled attributes. This 4242 * method should be called by subclasses that need fading edges and when an 4243 * instance of these subclasses is created programmatically rather than 4244 * being inflated from XML. This method is automatically called when the XML 4245 * is inflated. 4246 * </p> 4247 * 4248 * @param a the styled attributes set to initialize the fading edges from 4249 * @hide This is the real method; the public one is shimmed to be safe to call from apps. 4250 */ 4251 protected void initializeFadingEdgeInternal(TypedArray a) { 4252 initScrollCache(); 4253 4254 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 4255 R.styleable.View_fadingEdgeLength, 4256 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 4257 } 4258 4259 /** 4260 * Returns the size of the vertical faded edges used to indicate that more 4261 * content in this view is visible. 4262 * 4263 * @return The size in pixels of the vertical faded edge or 0 if vertical 4264 * faded edges are not enabled for this view. 4265 * @attr ref android.R.styleable#View_fadingEdgeLength 4266 */ 4267 public int getVerticalFadingEdgeLength() { 4268 if (isVerticalFadingEdgeEnabled()) { 4269 ScrollabilityCache cache = mScrollCache; 4270 if (cache != null) { 4271 return cache.fadingEdgeLength; 4272 } 4273 } 4274 return 0; 4275 } 4276 4277 /** 4278 * Set the size of the faded edge used to indicate that more content in this 4279 * view is available. Will not change whether the fading edge is enabled; use 4280 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 4281 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 4282 * for the vertical or horizontal fading edges. 4283 * 4284 * @param length The size in pixels of the faded edge used to indicate that more 4285 * content in this view is visible. 4286 */ 4287 public void setFadingEdgeLength(int length) { 4288 initScrollCache(); 4289 mScrollCache.fadingEdgeLength = length; 4290 } 4291 4292 /** 4293 * Returns the size of the horizontal faded edges used to indicate that more 4294 * content in this view is visible. 4295 * 4296 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 4297 * faded edges are not enabled for this view. 4298 * @attr ref android.R.styleable#View_fadingEdgeLength 4299 */ 4300 public int getHorizontalFadingEdgeLength() { 4301 if (isHorizontalFadingEdgeEnabled()) { 4302 ScrollabilityCache cache = mScrollCache; 4303 if (cache != null) { 4304 return cache.fadingEdgeLength; 4305 } 4306 } 4307 return 0; 4308 } 4309 4310 /** 4311 * Returns the width of the vertical scrollbar. 4312 * 4313 * @return The width in pixels of the vertical scrollbar or 0 if there 4314 * is no vertical scrollbar. 4315 */ 4316 public int getVerticalScrollbarWidth() { 4317 ScrollabilityCache cache = mScrollCache; 4318 if (cache != null) { 4319 ScrollBarDrawable scrollBar = cache.scrollBar; 4320 if (scrollBar != null) { 4321 int size = scrollBar.getSize(true); 4322 if (size <= 0) { 4323 size = cache.scrollBarSize; 4324 } 4325 return size; 4326 } 4327 return 0; 4328 } 4329 return 0; 4330 } 4331 4332 /** 4333 * Returns the height of the horizontal scrollbar. 4334 * 4335 * @return The height in pixels of the horizontal scrollbar or 0 if 4336 * there is no horizontal scrollbar. 4337 */ 4338 protected int getHorizontalScrollbarHeight() { 4339 ScrollabilityCache cache = mScrollCache; 4340 if (cache != null) { 4341 ScrollBarDrawable scrollBar = cache.scrollBar; 4342 if (scrollBar != null) { 4343 int size = scrollBar.getSize(false); 4344 if (size <= 0) { 4345 size = cache.scrollBarSize; 4346 } 4347 return size; 4348 } 4349 return 0; 4350 } 4351 return 0; 4352 } 4353 4354 /** 4355 * <p> 4356 * Initializes the scrollbars from a given set of styled attributes. This 4357 * method should be called by subclasses that need scrollbars and when an 4358 * instance of these subclasses is created programmatically rather than 4359 * being inflated from XML. This method is automatically called when the XML 4360 * is inflated. 4361 * </p> 4362 * 4363 * @param a the styled attributes set to initialize the scrollbars from 4364 */ 4365 protected void initializeScrollbars(TypedArray a) { 4366 // It's not safe to use this method from apps. The parameter 'a' must have been obtained 4367 // using the View filter array which is not available to the SDK. As such, internal 4368 // framework usage now uses initializeScrollbarsInternal and we grab a default 4369 // TypedArray with the right filter instead here. 4370 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 4371 4372 initializeScrollbarsInternal(arr); 4373 4374 // We ignored the method parameter. Recycle the one we actually did use. 4375 arr.recycle(); 4376 } 4377 4378 /** 4379 * <p> 4380 * Initializes the scrollbars from a given set of styled attributes. This 4381 * method should be called by subclasses that need scrollbars and when an 4382 * instance of these subclasses is created programmatically rather than 4383 * being inflated from XML. This method is automatically called when the XML 4384 * is inflated. 4385 * </p> 4386 * 4387 * @param a the styled attributes set to initialize the scrollbars from 4388 * @hide 4389 */ 4390 protected void initializeScrollbarsInternal(TypedArray a) { 4391 initScrollCache(); 4392 4393 final ScrollabilityCache scrollabilityCache = mScrollCache; 4394 4395 if (scrollabilityCache.scrollBar == null) { 4396 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 4397 } 4398 4399 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 4400 4401 if (!fadeScrollbars) { 4402 scrollabilityCache.state = ScrollabilityCache.ON; 4403 } 4404 scrollabilityCache.fadeScrollBars = fadeScrollbars; 4405 4406 4407 scrollabilityCache.scrollBarFadeDuration = a.getInt( 4408 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 4409 .getScrollBarFadeDuration()); 4410 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 4411 R.styleable.View_scrollbarDefaultDelayBeforeFade, 4412 ViewConfiguration.getScrollDefaultDelay()); 4413 4414 4415 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 4416 com.android.internal.R.styleable.View_scrollbarSize, 4417 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 4418 4419 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 4420 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 4421 4422 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 4423 if (thumb != null) { 4424 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 4425 } 4426 4427 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 4428 false); 4429 if (alwaysDraw) { 4430 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 4431 } 4432 4433 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 4434 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 4435 4436 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 4437 if (thumb != null) { 4438 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 4439 } 4440 4441 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 4442 false); 4443 if (alwaysDraw) { 4444 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 4445 } 4446 4447 // Apply layout direction to the new Drawables if needed 4448 final int layoutDirection = getLayoutDirection(); 4449 if (track != null) { 4450 track.setLayoutDirection(layoutDirection); 4451 } 4452 if (thumb != null) { 4453 thumb.setLayoutDirection(layoutDirection); 4454 } 4455 4456 // Re-apply user/background padding so that scrollbar(s) get added 4457 resolvePadding(); 4458 } 4459 4460 /** 4461 * <p> 4462 * Initalizes the scrollability cache if necessary. 4463 * </p> 4464 */ 4465 private void initScrollCache() { 4466 if (mScrollCache == null) { 4467 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 4468 } 4469 } 4470 4471 private ScrollabilityCache getScrollCache() { 4472 initScrollCache(); 4473 return mScrollCache; 4474 } 4475 4476 /** 4477 * Set the position of the vertical scroll bar. Should be one of 4478 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 4479 * {@link #SCROLLBAR_POSITION_RIGHT}. 4480 * 4481 * @param position Where the vertical scroll bar should be positioned. 4482 */ 4483 public void setVerticalScrollbarPosition(int position) { 4484 if (mVerticalScrollbarPosition != position) { 4485 mVerticalScrollbarPosition = position; 4486 computeOpaqueFlags(); 4487 resolvePadding(); 4488 } 4489 } 4490 4491 /** 4492 * @return The position where the vertical scroll bar will show, if applicable. 4493 * @see #setVerticalScrollbarPosition(int) 4494 */ 4495 public int getVerticalScrollbarPosition() { 4496 return mVerticalScrollbarPosition; 4497 } 4498 4499 ListenerInfo getListenerInfo() { 4500 if (mListenerInfo != null) { 4501 return mListenerInfo; 4502 } 4503 mListenerInfo = new ListenerInfo(); 4504 return mListenerInfo; 4505 } 4506 4507 /** 4508 * Register a callback to be invoked when focus of this view changed. 4509 * 4510 * @param l The callback that will run. 4511 */ 4512 public void setOnFocusChangeListener(OnFocusChangeListener l) { 4513 getListenerInfo().mOnFocusChangeListener = l; 4514 } 4515 4516 /** 4517 * Add a listener that will be called when the bounds of the view change due to 4518 * layout processing. 4519 * 4520 * @param listener The listener that will be called when layout bounds change. 4521 */ 4522 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 4523 ListenerInfo li = getListenerInfo(); 4524 if (li.mOnLayoutChangeListeners == null) { 4525 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 4526 } 4527 if (!li.mOnLayoutChangeListeners.contains(listener)) { 4528 li.mOnLayoutChangeListeners.add(listener); 4529 } 4530 } 4531 4532 /** 4533 * Remove a listener for layout changes. 4534 * 4535 * @param listener The listener for layout bounds change. 4536 */ 4537 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 4538 ListenerInfo li = mListenerInfo; 4539 if (li == null || li.mOnLayoutChangeListeners == null) { 4540 return; 4541 } 4542 li.mOnLayoutChangeListeners.remove(listener); 4543 } 4544 4545 /** 4546 * Add a listener for attach state changes. 4547 * 4548 * This listener will be called whenever this view is attached or detached 4549 * from a window. Remove the listener using 4550 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 4551 * 4552 * @param listener Listener to attach 4553 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 4554 */ 4555 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4556 ListenerInfo li = getListenerInfo(); 4557 if (li.mOnAttachStateChangeListeners == null) { 4558 li.mOnAttachStateChangeListeners 4559 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 4560 } 4561 li.mOnAttachStateChangeListeners.add(listener); 4562 } 4563 4564 /** 4565 * Remove a listener for attach state changes. The listener will receive no further 4566 * notification of window attach/detach events. 4567 * 4568 * @param listener Listener to remove 4569 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 4570 */ 4571 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4572 ListenerInfo li = mListenerInfo; 4573 if (li == null || li.mOnAttachStateChangeListeners == null) { 4574 return; 4575 } 4576 li.mOnAttachStateChangeListeners.remove(listener); 4577 } 4578 4579 /** 4580 * Returns the focus-change callback registered for this view. 4581 * 4582 * @return The callback, or null if one is not registered. 4583 */ 4584 public OnFocusChangeListener getOnFocusChangeListener() { 4585 ListenerInfo li = mListenerInfo; 4586 return li != null ? li.mOnFocusChangeListener : null; 4587 } 4588 4589 /** 4590 * Register a callback to be invoked when this view is clicked. If this view is not 4591 * clickable, it becomes clickable. 4592 * 4593 * @param l The callback that will run 4594 * 4595 * @see #setClickable(boolean) 4596 */ 4597 public void setOnClickListener(OnClickListener l) { 4598 if (!isClickable()) { 4599 setClickable(true); 4600 } 4601 getListenerInfo().mOnClickListener = l; 4602 } 4603 4604 /** 4605 * Return whether this view has an attached OnClickListener. Returns 4606 * true if there is a listener, false if there is none. 4607 */ 4608 public boolean hasOnClickListeners() { 4609 ListenerInfo li = mListenerInfo; 4610 return (li != null && li.mOnClickListener != null); 4611 } 4612 4613 /** 4614 * Register a callback to be invoked when this view is clicked and held. If this view is not 4615 * long clickable, it becomes long clickable. 4616 * 4617 * @param l The callback that will run 4618 * 4619 * @see #setLongClickable(boolean) 4620 */ 4621 public void setOnLongClickListener(OnLongClickListener l) { 4622 if (!isLongClickable()) { 4623 setLongClickable(true); 4624 } 4625 getListenerInfo().mOnLongClickListener = l; 4626 } 4627 4628 /** 4629 * Register a callback to be invoked when the context menu for this view is 4630 * being built. If this view is not long clickable, it becomes long clickable. 4631 * 4632 * @param l The callback that will run 4633 * 4634 */ 4635 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 4636 if (!isLongClickable()) { 4637 setLongClickable(true); 4638 } 4639 getListenerInfo().mOnCreateContextMenuListener = l; 4640 } 4641 4642 /** 4643 * Call this view's OnClickListener, if it is defined. Performs all normal 4644 * actions associated with clicking: reporting accessibility event, playing 4645 * a sound, etc. 4646 * 4647 * @return True there was an assigned OnClickListener that was called, false 4648 * otherwise is returned. 4649 */ 4650 public boolean performClick() { 4651 final boolean result; 4652 final ListenerInfo li = mListenerInfo; 4653 if (li != null && li.mOnClickListener != null) { 4654 playSoundEffect(SoundEffectConstants.CLICK); 4655 li.mOnClickListener.onClick(this); 4656 result = true; 4657 } else { 4658 result = false; 4659 } 4660 4661 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 4662 return result; 4663 } 4664 4665 /** 4666 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 4667 * this only calls the listener, and does not do any associated clicking 4668 * actions like reporting an accessibility event. 4669 * 4670 * @return True there was an assigned OnClickListener that was called, false 4671 * otherwise is returned. 4672 */ 4673 public boolean callOnClick() { 4674 ListenerInfo li = mListenerInfo; 4675 if (li != null && li.mOnClickListener != null) { 4676 li.mOnClickListener.onClick(this); 4677 return true; 4678 } 4679 return false; 4680 } 4681 4682 /** 4683 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 4684 * OnLongClickListener did not consume the event. 4685 * 4686 * @return True if one of the above receivers consumed the event, false otherwise. 4687 */ 4688 public boolean performLongClick() { 4689 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 4690 4691 boolean handled = false; 4692 ListenerInfo li = mListenerInfo; 4693 if (li != null && li.mOnLongClickListener != null) { 4694 handled = li.mOnLongClickListener.onLongClick(View.this); 4695 } 4696 if (!handled) { 4697 handled = showContextMenu(); 4698 } 4699 if (handled) { 4700 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 4701 } 4702 return handled; 4703 } 4704 4705 /** 4706 * Performs button-related actions during a touch down event. 4707 * 4708 * @param event The event. 4709 * @return True if the down was consumed. 4710 * 4711 * @hide 4712 */ 4713 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 4714 if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 4715 if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) { 4716 return true; 4717 } 4718 } 4719 return false; 4720 } 4721 4722 /** 4723 * Bring up the context menu for this view. 4724 * 4725 * @return Whether a context menu was displayed. 4726 */ 4727 public boolean showContextMenu() { 4728 return getParent().showContextMenuForChild(this); 4729 } 4730 4731 /** 4732 * Bring up the context menu for this view, referring to the item under the specified point. 4733 * 4734 * @param x The referenced x coordinate. 4735 * @param y The referenced y coordinate. 4736 * @param metaState The keyboard modifiers that were pressed. 4737 * @return Whether a context menu was displayed. 4738 * 4739 * @hide 4740 */ 4741 public boolean showContextMenu(float x, float y, int metaState) { 4742 return showContextMenu(); 4743 } 4744 4745 /** 4746 * Start an action mode. 4747 * 4748 * @param callback Callback that will control the lifecycle of the action mode 4749 * @return The new action mode if it is started, null otherwise 4750 * 4751 * @see ActionMode 4752 */ 4753 public ActionMode startActionMode(ActionMode.Callback callback) { 4754 ViewParent parent = getParent(); 4755 if (parent == null) return null; 4756 return parent.startActionModeForChild(this, callback); 4757 } 4758 4759 /** 4760 * Register a callback to be invoked when a hardware key is pressed in this view. 4761 * Key presses in software input methods will generally not trigger the methods of 4762 * this listener. 4763 * @param l the key listener to attach to this view 4764 */ 4765 public void setOnKeyListener(OnKeyListener l) { 4766 getListenerInfo().mOnKeyListener = l; 4767 } 4768 4769 /** 4770 * Register a callback to be invoked when a touch event is sent to this view. 4771 * @param l the touch listener to attach to this view 4772 */ 4773 public void setOnTouchListener(OnTouchListener l) { 4774 getListenerInfo().mOnTouchListener = l; 4775 } 4776 4777 /** 4778 * Register a callback to be invoked when a generic motion event is sent to this view. 4779 * @param l the generic motion listener to attach to this view 4780 */ 4781 public void setOnGenericMotionListener(OnGenericMotionListener l) { 4782 getListenerInfo().mOnGenericMotionListener = l; 4783 } 4784 4785 /** 4786 * Register a callback to be invoked when a hover event is sent to this view. 4787 * @param l the hover listener to attach to this view 4788 */ 4789 public void setOnHoverListener(OnHoverListener l) { 4790 getListenerInfo().mOnHoverListener = l; 4791 } 4792 4793 /** 4794 * Register a drag event listener callback object for this View. The parameter is 4795 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 4796 * View, the system calls the 4797 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 4798 * @param l An implementation of {@link android.view.View.OnDragListener}. 4799 */ 4800 public void setOnDragListener(OnDragListener l) { 4801 getListenerInfo().mOnDragListener = l; 4802 } 4803 4804 /** 4805 * Give this view focus. This will cause 4806 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 4807 * 4808 * Note: this does not check whether this {@link View} should get focus, it just 4809 * gives it focus no matter what. It should only be called internally by framework 4810 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 4811 * 4812 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 4813 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 4814 * focus moved when requestFocus() is called. It may not always 4815 * apply, in which case use the default View.FOCUS_DOWN. 4816 * @param previouslyFocusedRect The rectangle of the view that had focus 4817 * prior in this View's coordinate system. 4818 */ 4819 void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) { 4820 if (DBG) { 4821 System.out.println(this + " requestFocus()"); 4822 } 4823 4824 if ((mPrivateFlags & PFLAG_FOCUSED) == 0) { 4825 mPrivateFlags |= PFLAG_FOCUSED; 4826 4827 View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null; 4828 4829 if (mParent != null) { 4830 mParent.requestChildFocus(this, this); 4831 } 4832 4833 if (mAttachInfo != null) { 4834 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this); 4835 } 4836 4837 onFocusChanged(true, direction, previouslyFocusedRect); 4838 manageFocusHotspot(true, oldFocus); 4839 refreshDrawableState(); 4840 } 4841 } 4842 4843 /** 4844 * Forwards focus information to the background drawable, if necessary. When 4845 * the view is gaining focus, <code>v</code> is the previous focus holder. 4846 * When the view is losing focus, <code>v</code> is the next focus holder. 4847 * 4848 * @param focused whether this view is focused 4849 * @param v previous or the next focus holder, or null if none 4850 */ 4851 private void manageFocusHotspot(boolean focused, View v) { 4852 final Rect r = new Rect(); 4853 if (v != null && mAttachInfo != null) { 4854 v.getHotspotBounds(r); 4855 final int[] location = mAttachInfo.mTmpLocation; 4856 getLocationOnScreen(location); 4857 r.offset(-location[0], -location[1]); 4858 } else { 4859 r.set(0, 0, mRight - mLeft, mBottom - mTop); 4860 } 4861 4862 final float x = r.exactCenterX(); 4863 final float y = r.exactCenterY(); 4864 drawableHotspotChanged(x, y); 4865 } 4866 4867 /** 4868 * Populates <code>outRect</code> with the hotspot bounds. By default, 4869 * the hotspot bounds are identical to the screen bounds. 4870 * 4871 * @param outRect rect to populate with hotspot bounds 4872 * @hide Only for internal use by views and widgets. 4873 */ 4874 public void getHotspotBounds(Rect outRect) { 4875 final Drawable background = getBackground(); 4876 if (background != null) { 4877 background.getHotspotBounds(outRect); 4878 } else { 4879 getBoundsOnScreen(outRect); 4880 } 4881 } 4882 4883 /** 4884 * Request that a rectangle of this view be visible on the screen, 4885 * scrolling if necessary just enough. 4886 * 4887 * <p>A View should call this if it maintains some notion of which part 4888 * of its content is interesting. For example, a text editing view 4889 * should call this when its cursor moves. 4890 * 4891 * @param rectangle The rectangle. 4892 * @return Whether any parent scrolled. 4893 */ 4894 public boolean requestRectangleOnScreen(Rect rectangle) { 4895 return requestRectangleOnScreen(rectangle, false); 4896 } 4897 4898 /** 4899 * Request that a rectangle of this view be visible on the screen, 4900 * scrolling if necessary just enough. 4901 * 4902 * <p>A View should call this if it maintains some notion of which part 4903 * of its content is interesting. For example, a text editing view 4904 * should call this when its cursor moves. 4905 * 4906 * <p>When <code>immediate</code> is set to true, scrolling will not be 4907 * animated. 4908 * 4909 * @param rectangle The rectangle. 4910 * @param immediate True to forbid animated scrolling, false otherwise 4911 * @return Whether any parent scrolled. 4912 */ 4913 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 4914 if (mParent == null) { 4915 return false; 4916 } 4917 4918 View child = this; 4919 4920 RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF(); 4921 position.set(rectangle); 4922 4923 ViewParent parent = mParent; 4924 boolean scrolled = false; 4925 while (parent != null) { 4926 rectangle.set((int) position.left, (int) position.top, 4927 (int) position.right, (int) position.bottom); 4928 4929 scrolled |= parent.requestChildRectangleOnScreen(child, 4930 rectangle, immediate); 4931 4932 if (!child.hasIdentityMatrix()) { 4933 child.getMatrix().mapRect(position); 4934 } 4935 4936 position.offset(child.mLeft, child.mTop); 4937 4938 if (!(parent instanceof View)) { 4939 break; 4940 } 4941 4942 View parentView = (View) parent; 4943 4944 position.offset(-parentView.getScrollX(), -parentView.getScrollY()); 4945 4946 child = parentView; 4947 parent = child.getParent(); 4948 } 4949 4950 return scrolled; 4951 } 4952 4953 /** 4954 * Called when this view wants to give up focus. If focus is cleared 4955 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 4956 * <p> 4957 * <strong>Note:</strong> When a View clears focus the framework is trying 4958 * to give focus to the first focusable View from the top. Hence, if this 4959 * View is the first from the top that can take focus, then all callbacks 4960 * related to clearing focus will be invoked after wich the framework will 4961 * give focus to this view. 4962 * </p> 4963 */ 4964 public void clearFocus() { 4965 if (DBG) { 4966 System.out.println(this + " clearFocus()"); 4967 } 4968 4969 clearFocusInternal(null, true, true); 4970 } 4971 4972 /** 4973 * Clears focus from the view, optionally propagating the change up through 4974 * the parent hierarchy and requesting that the root view place new focus. 4975 * 4976 * @param propagate whether to propagate the change up through the parent 4977 * hierarchy 4978 * @param refocus when propagate is true, specifies whether to request the 4979 * root view place new focus 4980 */ 4981 void clearFocusInternal(View focused, boolean propagate, boolean refocus) { 4982 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 4983 mPrivateFlags &= ~PFLAG_FOCUSED; 4984 4985 if (propagate && mParent != null) { 4986 mParent.clearChildFocus(this); 4987 } 4988 4989 onFocusChanged(false, 0, null); 4990 4991 manageFocusHotspot(false, focused); 4992 refreshDrawableState(); 4993 4994 if (propagate && (!refocus || !rootViewRequestFocus())) { 4995 notifyGlobalFocusCleared(this); 4996 } 4997 } 4998 } 4999 5000 void notifyGlobalFocusCleared(View oldFocus) { 5001 if (oldFocus != null && mAttachInfo != null) { 5002 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null); 5003 } 5004 } 5005 5006 boolean rootViewRequestFocus() { 5007 final View root = getRootView(); 5008 return root != null && root.requestFocus(); 5009 } 5010 5011 /** 5012 * Called internally by the view system when a new view is getting focus. 5013 * This is what clears the old focus. 5014 * <p> 5015 * <b>NOTE:</b> The parent view's focused child must be updated manually 5016 * after calling this method. Otherwise, the view hierarchy may be left in 5017 * an inconstent state. 5018 */ 5019 void unFocus(View focused) { 5020 if (DBG) { 5021 System.out.println(this + " unFocus()"); 5022 } 5023 5024 clearFocusInternal(focused, false, false); 5025 } 5026 5027 /** 5028 * Returns true if this view has focus iteself, or is the ancestor of the 5029 * view that has focus. 5030 * 5031 * @return True if this view has or contains focus, false otherwise. 5032 */ 5033 @ViewDebug.ExportedProperty(category = "focus") 5034 public boolean hasFocus() { 5035 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 5036 } 5037 5038 /** 5039 * Returns true if this view is focusable or if it contains a reachable View 5040 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 5041 * is a View whose parents do not block descendants focus. 5042 * 5043 * Only {@link #VISIBLE} views are considered focusable. 5044 * 5045 * @return True if the view is focusable or if the view contains a focusable 5046 * View, false otherwise. 5047 * 5048 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 5049 * @see ViewGroup#getTouchscreenBlocksFocus() 5050 */ 5051 public boolean hasFocusable() { 5052 if (!isFocusableInTouchMode()) { 5053 for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) { 5054 final ViewGroup g = (ViewGroup) p; 5055 if (g.shouldBlockFocusForTouchscreen()) { 5056 return false; 5057 } 5058 } 5059 } 5060 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 5061 } 5062 5063 /** 5064 * Called by the view system when the focus state of this view changes. 5065 * When the focus change event is caused by directional navigation, direction 5066 * and previouslyFocusedRect provide insight into where the focus is coming from. 5067 * When overriding, be sure to call up through to the super class so that 5068 * the standard focus handling will occur. 5069 * 5070 * @param gainFocus True if the View has focus; false otherwise. 5071 * @param direction The direction focus has moved when requestFocus() 5072 * is called to give this view focus. Values are 5073 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 5074 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 5075 * It may not always apply, in which case use the default. 5076 * @param previouslyFocusedRect The rectangle, in this view's coordinate 5077 * system, of the previously focused view. If applicable, this will be 5078 * passed in as finer grained information about where the focus is coming 5079 * from (in addition to direction). Will be <code>null</code> otherwise. 5080 */ 5081 protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction, 5082 @Nullable Rect previouslyFocusedRect) { 5083 if (gainFocus) { 5084 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 5085 } else { 5086 notifyViewAccessibilityStateChangedIfNeeded( 5087 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 5088 } 5089 5090 InputMethodManager imm = InputMethodManager.peekInstance(); 5091 if (!gainFocus) { 5092 if (isPressed()) { 5093 setPressed(false); 5094 } 5095 if (imm != null && mAttachInfo != null 5096 && mAttachInfo.mHasWindowFocus) { 5097 imm.focusOut(this); 5098 } 5099 onFocusLost(); 5100 } else if (imm != null && mAttachInfo != null 5101 && mAttachInfo.mHasWindowFocus) { 5102 imm.focusIn(this); 5103 } 5104 5105 invalidate(true); 5106 ListenerInfo li = mListenerInfo; 5107 if (li != null && li.mOnFocusChangeListener != null) { 5108 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 5109 } 5110 5111 if (mAttachInfo != null) { 5112 mAttachInfo.mKeyDispatchState.reset(this); 5113 } 5114 } 5115 5116 /** 5117 * Sends an accessibility event of the given type. If accessibility is 5118 * not enabled this method has no effect. The default implementation calls 5119 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 5120 * to populate information about the event source (this View), then calls 5121 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 5122 * populate the text content of the event source including its descendants, 5123 * and last calls 5124 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 5125 * on its parent to resuest sending of the event to interested parties. 5126 * <p> 5127 * If an {@link AccessibilityDelegate} has been specified via calling 5128 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5129 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 5130 * responsible for handling this call. 5131 * </p> 5132 * 5133 * @param eventType The type of the event to send, as defined by several types from 5134 * {@link android.view.accessibility.AccessibilityEvent}, such as 5135 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 5136 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 5137 * 5138 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5139 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5140 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 5141 * @see AccessibilityDelegate 5142 */ 5143 public void sendAccessibilityEvent(int eventType) { 5144 if (mAccessibilityDelegate != null) { 5145 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 5146 } else { 5147 sendAccessibilityEventInternal(eventType); 5148 } 5149 } 5150 5151 /** 5152 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 5153 * {@link AccessibilityEvent} to make an announcement which is related to some 5154 * sort of a context change for which none of the events representing UI transitions 5155 * is a good fit. For example, announcing a new page in a book. If accessibility 5156 * is not enabled this method does nothing. 5157 * 5158 * @param text The announcement text. 5159 */ 5160 public void announceForAccessibility(CharSequence text) { 5161 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) { 5162 AccessibilityEvent event = AccessibilityEvent.obtain( 5163 AccessibilityEvent.TYPE_ANNOUNCEMENT); 5164 onInitializeAccessibilityEvent(event); 5165 event.getText().add(text); 5166 event.setContentDescription(null); 5167 mParent.requestSendAccessibilityEvent(this, event); 5168 } 5169 } 5170 5171 /** 5172 * @see #sendAccessibilityEvent(int) 5173 * 5174 * Note: Called from the default {@link AccessibilityDelegate}. 5175 */ 5176 void sendAccessibilityEventInternal(int eventType) { 5177 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 5178 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 5179 } 5180 } 5181 5182 /** 5183 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 5184 * takes as an argument an empty {@link AccessibilityEvent} and does not 5185 * perform a check whether accessibility is enabled. 5186 * <p> 5187 * If an {@link AccessibilityDelegate} has been specified via calling 5188 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5189 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 5190 * is responsible for handling this call. 5191 * </p> 5192 * 5193 * @param event The event to send. 5194 * 5195 * @see #sendAccessibilityEvent(int) 5196 */ 5197 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 5198 if (mAccessibilityDelegate != null) { 5199 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 5200 } else { 5201 sendAccessibilityEventUncheckedInternal(event); 5202 } 5203 } 5204 5205 /** 5206 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 5207 * 5208 * Note: Called from the default {@link AccessibilityDelegate}. 5209 */ 5210 void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 5211 if (!isShown()) { 5212 return; 5213 } 5214 onInitializeAccessibilityEvent(event); 5215 // Only a subset of accessibility events populates text content. 5216 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 5217 dispatchPopulateAccessibilityEvent(event); 5218 } 5219 // In the beginning we called #isShown(), so we know that getParent() is not null. 5220 getParent().requestSendAccessibilityEvent(this, event); 5221 } 5222 5223 /** 5224 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 5225 * to its children for adding their text content to the event. Note that the 5226 * event text is populated in a separate dispatch path since we add to the 5227 * event not only the text of the source but also the text of all its descendants. 5228 * A typical implementation will call 5229 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 5230 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5231 * on each child. Override this method if custom population of the event text 5232 * content is required. 5233 * <p> 5234 * If an {@link AccessibilityDelegate} has been specified via calling 5235 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5236 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 5237 * is responsible for handling this call. 5238 * </p> 5239 * <p> 5240 * <em>Note:</em> Accessibility events of certain types are not dispatched for 5241 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 5242 * </p> 5243 * 5244 * @param event The event. 5245 * 5246 * @return True if the event population was completed. 5247 */ 5248 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 5249 if (mAccessibilityDelegate != null) { 5250 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 5251 } else { 5252 return dispatchPopulateAccessibilityEventInternal(event); 5253 } 5254 } 5255 5256 /** 5257 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5258 * 5259 * Note: Called from the default {@link AccessibilityDelegate}. 5260 */ 5261 boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5262 onPopulateAccessibilityEvent(event); 5263 return false; 5264 } 5265 5266 /** 5267 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5268 * giving a chance to this View to populate the accessibility event with its 5269 * text content. While this method is free to modify event 5270 * attributes other than text content, doing so should normally be performed in 5271 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 5272 * <p> 5273 * Example: Adding formatted date string to an accessibility event in addition 5274 * to the text added by the super implementation: 5275 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5276 * super.onPopulateAccessibilityEvent(event); 5277 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 5278 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 5279 * mCurrentDate.getTimeInMillis(), flags); 5280 * event.getText().add(selectedDateUtterance); 5281 * }</pre> 5282 * <p> 5283 * If an {@link AccessibilityDelegate} has been specified via calling 5284 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5285 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 5286 * is responsible for handling this call. 5287 * </p> 5288 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5289 * information to the event, in case the default implementation has basic information to add. 5290 * </p> 5291 * 5292 * @param event The accessibility event which to populate. 5293 * 5294 * @see #sendAccessibilityEvent(int) 5295 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5296 */ 5297 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5298 if (mAccessibilityDelegate != null) { 5299 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 5300 } else { 5301 onPopulateAccessibilityEventInternal(event); 5302 } 5303 } 5304 5305 /** 5306 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 5307 * 5308 * Note: Called from the default {@link AccessibilityDelegate}. 5309 */ 5310 void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5311 } 5312 5313 /** 5314 * Initializes an {@link AccessibilityEvent} with information about 5315 * this View which is the event source. In other words, the source of 5316 * an accessibility event is the view whose state change triggered firing 5317 * the event. 5318 * <p> 5319 * Example: Setting the password property of an event in addition 5320 * to properties set by the super implementation: 5321 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5322 * super.onInitializeAccessibilityEvent(event); 5323 * event.setPassword(true); 5324 * }</pre> 5325 * <p> 5326 * If an {@link AccessibilityDelegate} has been specified via calling 5327 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5328 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 5329 * is responsible for handling this call. 5330 * </p> 5331 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5332 * information to the event, in case the default implementation has basic information to add. 5333 * </p> 5334 * @param event The event to initialize. 5335 * 5336 * @see #sendAccessibilityEvent(int) 5337 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5338 */ 5339 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5340 if (mAccessibilityDelegate != null) { 5341 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 5342 } else { 5343 onInitializeAccessibilityEventInternal(event); 5344 } 5345 } 5346 5347 /** 5348 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5349 * 5350 * Note: Called from the default {@link AccessibilityDelegate}. 5351 */ 5352 void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 5353 event.setSource(this); 5354 event.setClassName(View.class.getName()); 5355 event.setPackageName(getContext().getPackageName()); 5356 event.setEnabled(isEnabled()); 5357 event.setContentDescription(mContentDescription); 5358 5359 switch (event.getEventType()) { 5360 case AccessibilityEvent.TYPE_VIEW_FOCUSED: { 5361 ArrayList<View> focusablesTempList = (mAttachInfo != null) 5362 ? mAttachInfo.mTempArrayList : new ArrayList<View>(); 5363 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL); 5364 event.setItemCount(focusablesTempList.size()); 5365 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 5366 if (mAttachInfo != null) { 5367 focusablesTempList.clear(); 5368 } 5369 } break; 5370 case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: { 5371 CharSequence text = getIterableTextForAccessibility(); 5372 if (text != null && text.length() > 0) { 5373 event.setFromIndex(getAccessibilitySelectionStart()); 5374 event.setToIndex(getAccessibilitySelectionEnd()); 5375 event.setItemCount(text.length()); 5376 } 5377 } break; 5378 } 5379 } 5380 5381 /** 5382 * Returns an {@link AccessibilityNodeInfo} representing this view from the 5383 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 5384 * This method is responsible for obtaining an accessibility node info from a 5385 * pool of reusable instances and calling 5386 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 5387 * initialize the former. 5388 * <p> 5389 * Note: The client is responsible for recycling the obtained instance by calling 5390 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 5391 * </p> 5392 * 5393 * @return A populated {@link AccessibilityNodeInfo}. 5394 * 5395 * @see AccessibilityNodeInfo 5396 */ 5397 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 5398 if (mAccessibilityDelegate != null) { 5399 return mAccessibilityDelegate.createAccessibilityNodeInfo(this); 5400 } else { 5401 return createAccessibilityNodeInfoInternal(); 5402 } 5403 } 5404 5405 /** 5406 * @see #createAccessibilityNodeInfo() 5407 */ 5408 AccessibilityNodeInfo createAccessibilityNodeInfoInternal() { 5409 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 5410 if (provider != null) { 5411 return provider.createAccessibilityNodeInfo(View.NO_ID); 5412 } else { 5413 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 5414 onInitializeAccessibilityNodeInfo(info); 5415 return info; 5416 } 5417 } 5418 5419 /** 5420 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 5421 * The base implementation sets: 5422 * <ul> 5423 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 5424 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 5425 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 5426 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 5427 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 5428 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 5429 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 5430 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 5431 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 5432 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 5433 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 5434 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 5435 * </ul> 5436 * <p> 5437 * Subclasses should override this method, call the super implementation, 5438 * and set additional attributes. 5439 * </p> 5440 * <p> 5441 * If an {@link AccessibilityDelegate} has been specified via calling 5442 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5443 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 5444 * is responsible for handling this call. 5445 * </p> 5446 * 5447 * @param info The instance to initialize. 5448 */ 5449 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 5450 if (mAccessibilityDelegate != null) { 5451 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 5452 } else { 5453 onInitializeAccessibilityNodeInfoInternal(info); 5454 } 5455 } 5456 5457 /** 5458 * Gets the location of this view in screen coordintates. 5459 * 5460 * @param outRect The output location 5461 * @hide 5462 */ 5463 public void getBoundsOnScreen(Rect outRect) { 5464 if (mAttachInfo == null) { 5465 return; 5466 } 5467 5468 RectF position = mAttachInfo.mTmpTransformRect; 5469 position.set(0, 0, mRight - mLeft, mBottom - mTop); 5470 5471 if (!hasIdentityMatrix()) { 5472 getMatrix().mapRect(position); 5473 } 5474 5475 position.offset(mLeft, mTop); 5476 5477 ViewParent parent = mParent; 5478 while (parent instanceof View) { 5479 View parentView = (View) parent; 5480 5481 position.offset(-parentView.mScrollX, -parentView.mScrollY); 5482 5483 if (!parentView.hasIdentityMatrix()) { 5484 parentView.getMatrix().mapRect(position); 5485 } 5486 5487 position.offset(parentView.mLeft, parentView.mTop); 5488 5489 parent = parentView.mParent; 5490 } 5491 5492 if (parent instanceof ViewRootImpl) { 5493 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 5494 position.offset(0, -viewRootImpl.mCurScrollY); 5495 } 5496 5497 position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 5498 5499 outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f), 5500 (int) (position.right + 0.5f), (int) (position.bottom + 0.5f)); 5501 } 5502 5503 /** 5504 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 5505 * 5506 * Note: Called from the default {@link AccessibilityDelegate}. 5507 */ 5508 void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 5509 Rect bounds = mAttachInfo.mTmpInvalRect; 5510 5511 getDrawingRect(bounds); 5512 info.setBoundsInParent(bounds); 5513 5514 getBoundsOnScreen(bounds); 5515 info.setBoundsInScreen(bounds); 5516 5517 ViewParent parent = getParentForAccessibility(); 5518 if (parent instanceof View) { 5519 info.setParent((View) parent); 5520 } 5521 5522 if (mID != View.NO_ID) { 5523 View rootView = getRootView(); 5524 if (rootView == null) { 5525 rootView = this; 5526 } 5527 View label = rootView.findLabelForView(this, mID); 5528 if (label != null) { 5529 info.setLabeledBy(label); 5530 } 5531 5532 if ((mAttachInfo.mAccessibilityFetchFlags 5533 & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0 5534 && Resources.resourceHasPackage(mID)) { 5535 try { 5536 String viewId = getResources().getResourceName(mID); 5537 info.setViewIdResourceName(viewId); 5538 } catch (Resources.NotFoundException nfe) { 5539 /* ignore */ 5540 } 5541 } 5542 } 5543 5544 if (mLabelForId != View.NO_ID) { 5545 View rootView = getRootView(); 5546 if (rootView == null) { 5547 rootView = this; 5548 } 5549 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId); 5550 if (labeled != null) { 5551 info.setLabelFor(labeled); 5552 } 5553 } 5554 5555 info.setVisibleToUser(isVisibleToUser()); 5556 5557 info.setPackageName(mContext.getPackageName()); 5558 info.setClassName(View.class.getName()); 5559 info.setContentDescription(getContentDescription()); 5560 5561 info.setEnabled(isEnabled()); 5562 info.setClickable(isClickable()); 5563 info.setFocusable(isFocusable()); 5564 info.setFocused(isFocused()); 5565 info.setAccessibilityFocused(isAccessibilityFocused()); 5566 info.setSelected(isSelected()); 5567 info.setLongClickable(isLongClickable()); 5568 info.setLiveRegion(getAccessibilityLiveRegion()); 5569 5570 // TODO: These make sense only if we are in an AdapterView but all 5571 // views can be selected. Maybe from accessibility perspective 5572 // we should report as selectable view in an AdapterView. 5573 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 5574 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 5575 5576 if (isFocusable()) { 5577 if (isFocused()) { 5578 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 5579 } else { 5580 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 5581 } 5582 } 5583 5584 if (!isAccessibilityFocused()) { 5585 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 5586 } else { 5587 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 5588 } 5589 5590 if (isClickable() && isEnabled()) { 5591 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 5592 } 5593 5594 if (isLongClickable() && isEnabled()) { 5595 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 5596 } 5597 5598 CharSequence text = getIterableTextForAccessibility(); 5599 if (text != null && text.length() > 0) { 5600 info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd()); 5601 5602 info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); 5603 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 5604 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 5605 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 5606 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 5607 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 5608 } 5609 } 5610 5611 private View findLabelForView(View view, int labeledId) { 5612 if (mMatchLabelForPredicate == null) { 5613 mMatchLabelForPredicate = new MatchLabelForPredicate(); 5614 } 5615 mMatchLabelForPredicate.mLabeledId = labeledId; 5616 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 5617 } 5618 5619 /** 5620 * Computes whether this view is visible to the user. Such a view is 5621 * attached, visible, all its predecessors are visible, it is not clipped 5622 * entirely by its predecessors, and has an alpha greater than zero. 5623 * 5624 * @return Whether the view is visible on the screen. 5625 * 5626 * @hide 5627 */ 5628 protected boolean isVisibleToUser() { 5629 return isVisibleToUser(null); 5630 } 5631 5632 /** 5633 * Computes whether the given portion of this view is visible to the user. 5634 * Such a view is attached, visible, all its predecessors are visible, 5635 * has an alpha greater than zero, and the specified portion is not 5636 * clipped entirely by its predecessors. 5637 * 5638 * @param boundInView the portion of the view to test; coordinates should be relative; may be 5639 * <code>null</code>, and the entire view will be tested in this case. 5640 * When <code>true</code> is returned by the function, the actual visible 5641 * region will be stored in this parameter; that is, if boundInView is fully 5642 * contained within the view, no modification will be made, otherwise regions 5643 * outside of the visible area of the view will be clipped. 5644 * 5645 * @return Whether the specified portion of the view is visible on the screen. 5646 * 5647 * @hide 5648 */ 5649 protected boolean isVisibleToUser(Rect boundInView) { 5650 if (mAttachInfo != null) { 5651 // Attached to invisible window means this view is not visible. 5652 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 5653 return false; 5654 } 5655 // An invisible predecessor or one with alpha zero means 5656 // that this view is not visible to the user. 5657 Object current = this; 5658 while (current instanceof View) { 5659 View view = (View) current; 5660 // We have attach info so this view is attached and there is no 5661 // need to check whether we reach to ViewRootImpl on the way up. 5662 if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 || 5663 view.getVisibility() != VISIBLE) { 5664 return false; 5665 } 5666 current = view.mParent; 5667 } 5668 // Check if the view is entirely covered by its predecessors. 5669 Rect visibleRect = mAttachInfo.mTmpInvalRect; 5670 Point offset = mAttachInfo.mPoint; 5671 if (!getGlobalVisibleRect(visibleRect, offset)) { 5672 return false; 5673 } 5674 // Check if the visible portion intersects the rectangle of interest. 5675 if (boundInView != null) { 5676 visibleRect.offset(-offset.x, -offset.y); 5677 return boundInView.intersect(visibleRect); 5678 } 5679 return true; 5680 } 5681 return false; 5682 } 5683 5684 /** 5685 * Returns the delegate for implementing accessibility support via 5686 * composition. For more details see {@link AccessibilityDelegate}. 5687 * 5688 * @return The delegate, or null if none set. 5689 * 5690 * @hide 5691 */ 5692 public AccessibilityDelegate getAccessibilityDelegate() { 5693 return mAccessibilityDelegate; 5694 } 5695 5696 /** 5697 * Sets a delegate for implementing accessibility support via composition as 5698 * opposed to inheritance. The delegate's primary use is for implementing 5699 * backwards compatible widgets. For more details see {@link AccessibilityDelegate}. 5700 * 5701 * @param delegate The delegate instance. 5702 * 5703 * @see AccessibilityDelegate 5704 */ 5705 public void setAccessibilityDelegate(AccessibilityDelegate delegate) { 5706 mAccessibilityDelegate = delegate; 5707 } 5708 5709 /** 5710 * Gets the provider for managing a virtual view hierarchy rooted at this View 5711 * and reported to {@link android.accessibilityservice.AccessibilityService}s 5712 * that explore the window content. 5713 * <p> 5714 * If this method returns an instance, this instance is responsible for managing 5715 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 5716 * View including the one representing the View itself. Similarly the returned 5717 * instance is responsible for performing accessibility actions on any virtual 5718 * view or the root view itself. 5719 * </p> 5720 * <p> 5721 * If an {@link AccessibilityDelegate} has been specified via calling 5722 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5723 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 5724 * is responsible for handling this call. 5725 * </p> 5726 * 5727 * @return The provider. 5728 * 5729 * @see AccessibilityNodeProvider 5730 */ 5731 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 5732 if (mAccessibilityDelegate != null) { 5733 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 5734 } else { 5735 return null; 5736 } 5737 } 5738 5739 /** 5740 * Gets the unique identifier of this view on the screen for accessibility purposes. 5741 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 5742 * 5743 * @return The view accessibility id. 5744 * 5745 * @hide 5746 */ 5747 public int getAccessibilityViewId() { 5748 if (mAccessibilityViewId == NO_ID) { 5749 mAccessibilityViewId = sNextAccessibilityViewId++; 5750 } 5751 return mAccessibilityViewId; 5752 } 5753 5754 /** 5755 * Gets the unique identifier of the window in which this View reseides. 5756 * 5757 * @return The window accessibility id. 5758 * 5759 * @hide 5760 */ 5761 public int getAccessibilityWindowId() { 5762 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId 5763 : AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 5764 } 5765 5766 /** 5767 * Gets the {@link View} description. It briefly describes the view and is 5768 * primarily used for accessibility support. Set this property to enable 5769 * better accessibility support for your application. This is especially 5770 * true for views that do not have textual representation (For example, 5771 * ImageButton). 5772 * 5773 * @return The content description. 5774 * 5775 * @attr ref android.R.styleable#View_contentDescription 5776 */ 5777 @ViewDebug.ExportedProperty(category = "accessibility") 5778 public CharSequence getContentDescription() { 5779 return mContentDescription; 5780 } 5781 5782 /** 5783 * Sets the {@link View} description. It briefly describes the view and is 5784 * primarily used for accessibility support. Set this property to enable 5785 * better accessibility support for your application. This is especially 5786 * true for views that do not have textual representation (For example, 5787 * ImageButton). 5788 * 5789 * @param contentDescription The content description. 5790 * 5791 * @attr ref android.R.styleable#View_contentDescription 5792 */ 5793 @RemotableViewMethod 5794 public void setContentDescription(CharSequence contentDescription) { 5795 if (mContentDescription == null) { 5796 if (contentDescription == null) { 5797 return; 5798 } 5799 } else if (mContentDescription.equals(contentDescription)) { 5800 return; 5801 } 5802 mContentDescription = contentDescription; 5803 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 5804 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 5805 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 5806 notifySubtreeAccessibilityStateChangedIfNeeded(); 5807 } else { 5808 notifyViewAccessibilityStateChangedIfNeeded( 5809 AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION); 5810 } 5811 } 5812 5813 /** 5814 * Gets the id of a view for which this view serves as a label for 5815 * accessibility purposes. 5816 * 5817 * @return The labeled view id. 5818 */ 5819 @ViewDebug.ExportedProperty(category = "accessibility") 5820 public int getLabelFor() { 5821 return mLabelForId; 5822 } 5823 5824 /** 5825 * Sets the id of a view for which this view serves as a label for 5826 * accessibility purposes. 5827 * 5828 * @param id The labeled view id. 5829 */ 5830 @RemotableViewMethod 5831 public void setLabelFor(int id) { 5832 mLabelForId = id; 5833 if (mLabelForId != View.NO_ID 5834 && mID == View.NO_ID) { 5835 mID = generateViewId(); 5836 } 5837 } 5838 5839 /** 5840 * Invoked whenever this view loses focus, either by losing window focus or by losing 5841 * focus within its window. This method can be used to clear any state tied to the 5842 * focus. For instance, if a button is held pressed with the trackball and the window 5843 * loses focus, this method can be used to cancel the press. 5844 * 5845 * Subclasses of View overriding this method should always call super.onFocusLost(). 5846 * 5847 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 5848 * @see #onWindowFocusChanged(boolean) 5849 * 5850 * @hide pending API council approval 5851 */ 5852 protected void onFocusLost() { 5853 resetPressedState(); 5854 } 5855 5856 private void resetPressedState() { 5857 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 5858 return; 5859 } 5860 5861 if (isPressed()) { 5862 setPressed(false); 5863 5864 if (!mHasPerformedLongPress) { 5865 removeLongPressCallback(); 5866 } 5867 } 5868 } 5869 5870 /** 5871 * Returns true if this view has focus 5872 * 5873 * @return True if this view has focus, false otherwise. 5874 */ 5875 @ViewDebug.ExportedProperty(category = "focus") 5876 public boolean isFocused() { 5877 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 5878 } 5879 5880 /** 5881 * Find the view in the hierarchy rooted at this view that currently has 5882 * focus. 5883 * 5884 * @return The view that currently has focus, or null if no focused view can 5885 * be found. 5886 */ 5887 public View findFocus() { 5888 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 5889 } 5890 5891 /** 5892 * Indicates whether this view is one of the set of scrollable containers in 5893 * its window. 5894 * 5895 * @return whether this view is one of the set of scrollable containers in 5896 * its window 5897 * 5898 * @attr ref android.R.styleable#View_isScrollContainer 5899 */ 5900 public boolean isScrollContainer() { 5901 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 5902 } 5903 5904 /** 5905 * Change whether this view is one of the set of scrollable containers in 5906 * its window. This will be used to determine whether the window can 5907 * resize or must pan when a soft input area is open -- scrollable 5908 * containers allow the window to use resize mode since the container 5909 * will appropriately shrink. 5910 * 5911 * @attr ref android.R.styleable#View_isScrollContainer 5912 */ 5913 public void setScrollContainer(boolean isScrollContainer) { 5914 if (isScrollContainer) { 5915 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 5916 mAttachInfo.mScrollContainers.add(this); 5917 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 5918 } 5919 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 5920 } else { 5921 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 5922 mAttachInfo.mScrollContainers.remove(this); 5923 } 5924 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 5925 } 5926 } 5927 5928 /** 5929 * Returns the quality of the drawing cache. 5930 * 5931 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5932 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5933 * 5934 * @see #setDrawingCacheQuality(int) 5935 * @see #setDrawingCacheEnabled(boolean) 5936 * @see #isDrawingCacheEnabled() 5937 * 5938 * @attr ref android.R.styleable#View_drawingCacheQuality 5939 */ 5940 @DrawingCacheQuality 5941 public int getDrawingCacheQuality() { 5942 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 5943 } 5944 5945 /** 5946 * Set the drawing cache quality of this view. This value is used only when the 5947 * drawing cache is enabled 5948 * 5949 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5950 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5951 * 5952 * @see #getDrawingCacheQuality() 5953 * @see #setDrawingCacheEnabled(boolean) 5954 * @see #isDrawingCacheEnabled() 5955 * 5956 * @attr ref android.R.styleable#View_drawingCacheQuality 5957 */ 5958 public void setDrawingCacheQuality(@DrawingCacheQuality int quality) { 5959 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 5960 } 5961 5962 /** 5963 * Returns whether the screen should remain on, corresponding to the current 5964 * value of {@link #KEEP_SCREEN_ON}. 5965 * 5966 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 5967 * 5968 * @see #setKeepScreenOn(boolean) 5969 * 5970 * @attr ref android.R.styleable#View_keepScreenOn 5971 */ 5972 public boolean getKeepScreenOn() { 5973 return (mViewFlags & KEEP_SCREEN_ON) != 0; 5974 } 5975 5976 /** 5977 * Controls whether the screen should remain on, modifying the 5978 * value of {@link #KEEP_SCREEN_ON}. 5979 * 5980 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 5981 * 5982 * @see #getKeepScreenOn() 5983 * 5984 * @attr ref android.R.styleable#View_keepScreenOn 5985 */ 5986 public void setKeepScreenOn(boolean keepScreenOn) { 5987 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 5988 } 5989 5990 /** 5991 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5992 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5993 * 5994 * @attr ref android.R.styleable#View_nextFocusLeft 5995 */ 5996 public int getNextFocusLeftId() { 5997 return mNextFocusLeftId; 5998 } 5999 6000 /** 6001 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 6002 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 6003 * decide automatically. 6004 * 6005 * @attr ref android.R.styleable#View_nextFocusLeft 6006 */ 6007 public void setNextFocusLeftId(int nextFocusLeftId) { 6008 mNextFocusLeftId = nextFocusLeftId; 6009 } 6010 6011 /** 6012 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 6013 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6014 * 6015 * @attr ref android.R.styleable#View_nextFocusRight 6016 */ 6017 public int getNextFocusRightId() { 6018 return mNextFocusRightId; 6019 } 6020 6021 /** 6022 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 6023 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 6024 * decide automatically. 6025 * 6026 * @attr ref android.R.styleable#View_nextFocusRight 6027 */ 6028 public void setNextFocusRightId(int nextFocusRightId) { 6029 mNextFocusRightId = nextFocusRightId; 6030 } 6031 6032 /** 6033 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 6034 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6035 * 6036 * @attr ref android.R.styleable#View_nextFocusUp 6037 */ 6038 public int getNextFocusUpId() { 6039 return mNextFocusUpId; 6040 } 6041 6042 /** 6043 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 6044 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 6045 * decide automatically. 6046 * 6047 * @attr ref android.R.styleable#View_nextFocusUp 6048 */ 6049 public void setNextFocusUpId(int nextFocusUpId) { 6050 mNextFocusUpId = nextFocusUpId; 6051 } 6052 6053 /** 6054 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 6055 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6056 * 6057 * @attr ref android.R.styleable#View_nextFocusDown 6058 */ 6059 public int getNextFocusDownId() { 6060 return mNextFocusDownId; 6061 } 6062 6063 /** 6064 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 6065 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 6066 * decide automatically. 6067 * 6068 * @attr ref android.R.styleable#View_nextFocusDown 6069 */ 6070 public void setNextFocusDownId(int nextFocusDownId) { 6071 mNextFocusDownId = nextFocusDownId; 6072 } 6073 6074 /** 6075 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 6076 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6077 * 6078 * @attr ref android.R.styleable#View_nextFocusForward 6079 */ 6080 public int getNextFocusForwardId() { 6081 return mNextFocusForwardId; 6082 } 6083 6084 /** 6085 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 6086 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 6087 * decide automatically. 6088 * 6089 * @attr ref android.R.styleable#View_nextFocusForward 6090 */ 6091 public void setNextFocusForwardId(int nextFocusForwardId) { 6092 mNextFocusForwardId = nextFocusForwardId; 6093 } 6094 6095 /** 6096 * Returns the visibility of this view and all of its ancestors 6097 * 6098 * @return True if this view and all of its ancestors are {@link #VISIBLE} 6099 */ 6100 public boolean isShown() { 6101 View current = this; 6102 //noinspection ConstantConditions 6103 do { 6104 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 6105 return false; 6106 } 6107 ViewParent parent = current.mParent; 6108 if (parent == null) { 6109 return false; // We are not attached to the view root 6110 } 6111 if (!(parent instanceof View)) { 6112 return true; 6113 } 6114 current = (View) parent; 6115 } while (current != null); 6116 6117 return false; 6118 } 6119 6120 /** 6121 * Called by the view hierarchy when the content insets for a window have 6122 * changed, to allow it to adjust its content to fit within those windows. 6123 * The content insets tell you the space that the status bar, input method, 6124 * and other system windows infringe on the application's window. 6125 * 6126 * <p>You do not normally need to deal with this function, since the default 6127 * window decoration given to applications takes care of applying it to the 6128 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 6129 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 6130 * and your content can be placed under those system elements. You can then 6131 * use this method within your view hierarchy if you have parts of your UI 6132 * which you would like to ensure are not being covered. 6133 * 6134 * <p>The default implementation of this method simply applies the content 6135 * insets to the view's padding, consuming that content (modifying the 6136 * insets to be 0), and returning true. This behavior is off by default, but can 6137 * be enabled through {@link #setFitsSystemWindows(boolean)}. 6138 * 6139 * <p>This function's traversal down the hierarchy is depth-first. The same content 6140 * insets object is propagated down the hierarchy, so any changes made to it will 6141 * be seen by all following views (including potentially ones above in 6142 * the hierarchy since this is a depth-first traversal). The first view 6143 * that returns true will abort the entire traversal. 6144 * 6145 * <p>The default implementation works well for a situation where it is 6146 * used with a container that covers the entire window, allowing it to 6147 * apply the appropriate insets to its content on all edges. If you need 6148 * a more complicated layout (such as two different views fitting system 6149 * windows, one on the top of the window, and one on the bottom), 6150 * you can override the method and handle the insets however you would like. 6151 * Note that the insets provided by the framework are always relative to the 6152 * far edges of the window, not accounting for the location of the called view 6153 * within that window. (In fact when this method is called you do not yet know 6154 * where the layout will place the view, as it is done before layout happens.) 6155 * 6156 * <p>Note: unlike many View methods, there is no dispatch phase to this 6157 * call. If you are overriding it in a ViewGroup and want to allow the 6158 * call to continue to your children, you must be sure to call the super 6159 * implementation. 6160 * 6161 * <p>Here is a sample layout that makes use of fitting system windows 6162 * to have controls for a video view placed inside of the window decorations 6163 * that it hides and shows. This can be used with code like the second 6164 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 6165 * 6166 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 6167 * 6168 * @param insets Current content insets of the window. Prior to 6169 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 6170 * the insets or else you and Android will be unhappy. 6171 * 6172 * @return {@code true} if this view applied the insets and it should not 6173 * continue propagating further down the hierarchy, {@code false} otherwise. 6174 * @see #getFitsSystemWindows() 6175 * @see #setFitsSystemWindows(boolean) 6176 * @see #setSystemUiVisibility(int) 6177 * 6178 * @deprecated As of API XX use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply 6179 * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use 6180 * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)} 6181 * to implement handling their own insets. 6182 */ 6183 protected boolean fitSystemWindows(Rect insets) { 6184 if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) { 6185 if (insets == null) { 6186 // Null insets by definition have already been consumed. 6187 // This call cannot apply insets since there are none to apply, 6188 // so return false. 6189 return false; 6190 } 6191 // If we're not in the process of dispatching the newer apply insets call, 6192 // that means we're not in the compatibility path. Dispatch into the newer 6193 // apply insets path and take things from there. 6194 try { 6195 mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS; 6196 return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed(); 6197 } finally { 6198 mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS; 6199 } 6200 } else { 6201 // We're being called from the newer apply insets path. 6202 // Perform the standard fallback behavior. 6203 return fitSystemWindowsInt(insets); 6204 } 6205 } 6206 6207 private boolean fitSystemWindowsInt(Rect insets) { 6208 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 6209 mUserPaddingStart = UNDEFINED_PADDING; 6210 mUserPaddingEnd = UNDEFINED_PADDING; 6211 Rect localInsets = sThreadLocal.get(); 6212 if (localInsets == null) { 6213 localInsets = new Rect(); 6214 sThreadLocal.set(localInsets); 6215 } 6216 boolean res = computeFitSystemWindows(insets, localInsets); 6217 mUserPaddingLeftInitial = localInsets.left; 6218 mUserPaddingRightInitial = localInsets.right; 6219 internalSetPadding(localInsets.left, localInsets.top, 6220 localInsets.right, localInsets.bottom); 6221 return res; 6222 } 6223 return false; 6224 } 6225 6226 /** 6227 * Called when the view should apply {@link WindowInsets} according to its internal policy. 6228 * 6229 * <p>This method should be overridden by views that wish to apply a policy different from or 6230 * in addition to the default behavior. Clients that wish to force a view subtree 6231 * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p> 6232 * 6233 * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set 6234 * it will be called during dispatch instead of this method. The listener may optionally 6235 * call this method from its own implementation if it wishes to apply the view's default 6236 * insets policy in addition to its own.</p> 6237 * 6238 * <p>Implementations of this method should either return the insets parameter unchanged 6239 * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed 6240 * that this view applied itself. This allows new inset types added in future platform 6241 * versions to pass through existing implementations unchanged without being erroneously 6242 * consumed.</p> 6243 * 6244 * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows} 6245 * property is set then the view will consume the system window insets and apply them 6246 * as padding for the view.</p> 6247 * 6248 * @param insets Insets to apply 6249 * @return The supplied insets with any applied insets consumed 6250 */ 6251 public WindowInsets onApplyWindowInsets(WindowInsets insets) { 6252 if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) { 6253 // We weren't called from within a direct call to fitSystemWindows, 6254 // call into it as a fallback in case we're in a class that overrides it 6255 // and has logic to perform. 6256 if (fitSystemWindows(insets.getSystemWindowInsets())) { 6257 return insets.consumeSystemWindowInsets(); 6258 } 6259 } else { 6260 // We were called from within a direct call to fitSystemWindows. 6261 if (fitSystemWindowsInt(insets.getSystemWindowInsets())) { 6262 return insets.consumeSystemWindowInsets(); 6263 } 6264 } 6265 return insets; 6266 } 6267 6268 /** 6269 * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying 6270 * window insets to this view. The listener's 6271 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 6272 * method will be called instead of the view's 6273 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 6274 * 6275 * @param listener Listener to set 6276 * 6277 * @see #onApplyWindowInsets(WindowInsets) 6278 */ 6279 public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) { 6280 getListenerInfo().mOnApplyWindowInsetsListener = listener; 6281 } 6282 6283 /** 6284 * Request to apply the given window insets to this view or another view in its subtree. 6285 * 6286 * <p>This method should be called by clients wishing to apply insets corresponding to areas 6287 * obscured by window decorations or overlays. This can include the status and navigation bars, 6288 * action bars, input methods and more. New inset categories may be added in the future. 6289 * The method returns the insets provided minus any that were applied by this view or its 6290 * children.</p> 6291 * 6292 * <p>Clients wishing to provide custom behavior should override the 6293 * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a 6294 * {@link OnApplyWindowInsetsListener} via the 6295 * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener} 6296 * method.</p> 6297 * 6298 * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method. 6299 * </p> 6300 * 6301 * @param insets Insets to apply 6302 * @return The provided insets minus the insets that were consumed 6303 */ 6304 public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) { 6305 try { 6306 mPrivateFlags3 |= PFLAG3_APPLYING_INSETS; 6307 if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) { 6308 return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets); 6309 } else { 6310 return onApplyWindowInsets(insets); 6311 } 6312 } finally { 6313 mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS; 6314 } 6315 } 6316 6317 /** 6318 * @hide Compute the insets that should be consumed by this view and the ones 6319 * that should propagate to those under it. 6320 */ 6321 protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) { 6322 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 6323 || mAttachInfo == null 6324 || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0 6325 && !mAttachInfo.mOverscanRequested)) { 6326 outLocalInsets.set(inoutInsets); 6327 inoutInsets.set(0, 0, 0, 0); 6328 return true; 6329 } else { 6330 // The application wants to take care of fitting system window for 6331 // the content... however we still need to take care of any overscan here. 6332 final Rect overscan = mAttachInfo.mOverscanInsets; 6333 outLocalInsets.set(overscan); 6334 inoutInsets.left -= overscan.left; 6335 inoutInsets.top -= overscan.top; 6336 inoutInsets.right -= overscan.right; 6337 inoutInsets.bottom -= overscan.bottom; 6338 return false; 6339 } 6340 } 6341 6342 /** 6343 * Sets whether or not this view should account for system screen decorations 6344 * such as the status bar and inset its content; that is, controlling whether 6345 * the default implementation of {@link #fitSystemWindows(Rect)} will be 6346 * executed. See that method for more details. 6347 * 6348 * <p>Note that if you are providing your own implementation of 6349 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 6350 * flag to true -- your implementation will be overriding the default 6351 * implementation that checks this flag. 6352 * 6353 * @param fitSystemWindows If true, then the default implementation of 6354 * {@link #fitSystemWindows(Rect)} will be executed. 6355 * 6356 * @attr ref android.R.styleable#View_fitsSystemWindows 6357 * @see #getFitsSystemWindows() 6358 * @see #fitSystemWindows(Rect) 6359 * @see #setSystemUiVisibility(int) 6360 */ 6361 public void setFitsSystemWindows(boolean fitSystemWindows) { 6362 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 6363 } 6364 6365 /** 6366 * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method 6367 * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)} 6368 * will be executed. 6369 * 6370 * @return {@code true} if the default implementation of 6371 * {@link #fitSystemWindows(Rect)} will be executed. 6372 * 6373 * @attr ref android.R.styleable#View_fitsSystemWindows 6374 * @see #setFitsSystemWindows(boolean) 6375 * @see #fitSystemWindows(Rect) 6376 * @see #setSystemUiVisibility(int) 6377 */ 6378 public boolean getFitsSystemWindows() { 6379 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 6380 } 6381 6382 /** @hide */ 6383 public boolean fitsSystemWindows() { 6384 return getFitsSystemWindows(); 6385 } 6386 6387 /** 6388 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 6389 * @deprecated Use {@link #requestApplyInsets()} for newer platform versions. 6390 */ 6391 public void requestFitSystemWindows() { 6392 if (mParent != null) { 6393 mParent.requestFitSystemWindows(); 6394 } 6395 } 6396 6397 /** 6398 * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed. 6399 */ 6400 public void requestApplyInsets() { 6401 requestFitSystemWindows(); 6402 } 6403 6404 /** 6405 * For use by PhoneWindow to make its own system window fitting optional. 6406 * @hide 6407 */ 6408 public void makeOptionalFitsSystemWindows() { 6409 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 6410 } 6411 6412 /** 6413 * Returns the visibility status for this view. 6414 * 6415 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6416 * @attr ref android.R.styleable#View_visibility 6417 */ 6418 @ViewDebug.ExportedProperty(mapping = { 6419 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 6420 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 6421 @ViewDebug.IntToString(from = GONE, to = "GONE") 6422 }) 6423 @Visibility 6424 public int getVisibility() { 6425 return mViewFlags & VISIBILITY_MASK; 6426 } 6427 6428 /** 6429 * Set the enabled state of this view. 6430 * 6431 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6432 * @attr ref android.R.styleable#View_visibility 6433 */ 6434 @RemotableViewMethod 6435 public void setVisibility(@Visibility int visibility) { 6436 setFlags(visibility, VISIBILITY_MASK); 6437 if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false); 6438 } 6439 6440 /** 6441 * Returns the enabled status for this view. The interpretation of the 6442 * enabled state varies by subclass. 6443 * 6444 * @return True if this view is enabled, false otherwise. 6445 */ 6446 @ViewDebug.ExportedProperty 6447 public boolean isEnabled() { 6448 return (mViewFlags & ENABLED_MASK) == ENABLED; 6449 } 6450 6451 /** 6452 * Set the enabled state of this view. The interpretation of the enabled 6453 * state varies by subclass. 6454 * 6455 * @param enabled True if this view is enabled, false otherwise. 6456 */ 6457 @RemotableViewMethod 6458 public void setEnabled(boolean enabled) { 6459 if (enabled == isEnabled()) return; 6460 6461 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 6462 6463 /* 6464 * The View most likely has to change its appearance, so refresh 6465 * the drawable state. 6466 */ 6467 refreshDrawableState(); 6468 6469 // Invalidate too, since the default behavior for views is to be 6470 // be drawn at 50% alpha rather than to change the drawable. 6471 invalidate(true); 6472 6473 if (!enabled) { 6474 cancelPendingInputEvents(); 6475 } 6476 } 6477 6478 /** 6479 * Set whether this view can receive the focus. 6480 * 6481 * Setting this to false will also ensure that this view is not focusable 6482 * in touch mode. 6483 * 6484 * @param focusable If true, this view can receive the focus. 6485 * 6486 * @see #setFocusableInTouchMode(boolean) 6487 * @attr ref android.R.styleable#View_focusable 6488 */ 6489 public void setFocusable(boolean focusable) { 6490 if (!focusable) { 6491 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 6492 } 6493 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 6494 } 6495 6496 /** 6497 * Set whether this view can receive focus while in touch mode. 6498 * 6499 * Setting this to true will also ensure that this view is focusable. 6500 * 6501 * @param focusableInTouchMode If true, this view can receive the focus while 6502 * in touch mode. 6503 * 6504 * @see #setFocusable(boolean) 6505 * @attr ref android.R.styleable#View_focusableInTouchMode 6506 */ 6507 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 6508 // Focusable in touch mode should always be set before the focusable flag 6509 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 6510 // which, in touch mode, will not successfully request focus on this view 6511 // because the focusable in touch mode flag is not set 6512 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 6513 if (focusableInTouchMode) { 6514 setFlags(FOCUSABLE, FOCUSABLE_MASK); 6515 } 6516 } 6517 6518 /** 6519 * Set whether this view should have sound effects enabled for events such as 6520 * clicking and touching. 6521 * 6522 * <p>You may wish to disable sound effects for a view if you already play sounds, 6523 * for instance, a dial key that plays dtmf tones. 6524 * 6525 * @param soundEffectsEnabled whether sound effects are enabled for this view. 6526 * @see #isSoundEffectsEnabled() 6527 * @see #playSoundEffect(int) 6528 * @attr ref android.R.styleable#View_soundEffectsEnabled 6529 */ 6530 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 6531 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 6532 } 6533 6534 /** 6535 * @return whether this view should have sound effects enabled for events such as 6536 * clicking and touching. 6537 * 6538 * @see #setSoundEffectsEnabled(boolean) 6539 * @see #playSoundEffect(int) 6540 * @attr ref android.R.styleable#View_soundEffectsEnabled 6541 */ 6542 @ViewDebug.ExportedProperty 6543 public boolean isSoundEffectsEnabled() { 6544 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 6545 } 6546 6547 /** 6548 * Set whether this view should have haptic feedback for events such as 6549 * long presses. 6550 * 6551 * <p>You may wish to disable haptic feedback if your view already controls 6552 * its own haptic feedback. 6553 * 6554 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 6555 * @see #isHapticFeedbackEnabled() 6556 * @see #performHapticFeedback(int) 6557 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6558 */ 6559 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 6560 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 6561 } 6562 6563 /** 6564 * @return whether this view should have haptic feedback enabled for events 6565 * long presses. 6566 * 6567 * @see #setHapticFeedbackEnabled(boolean) 6568 * @see #performHapticFeedback(int) 6569 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6570 */ 6571 @ViewDebug.ExportedProperty 6572 public boolean isHapticFeedbackEnabled() { 6573 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 6574 } 6575 6576 /** 6577 * Returns the layout direction for this view. 6578 * 6579 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 6580 * {@link #LAYOUT_DIRECTION_RTL}, 6581 * {@link #LAYOUT_DIRECTION_INHERIT} or 6582 * {@link #LAYOUT_DIRECTION_LOCALE}. 6583 * 6584 * @attr ref android.R.styleable#View_layoutDirection 6585 * 6586 * @hide 6587 */ 6588 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6589 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 6590 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 6591 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 6592 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 6593 }) 6594 @LayoutDir 6595 public int getRawLayoutDirection() { 6596 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 6597 } 6598 6599 /** 6600 * Set the layout direction for this view. This will propagate a reset of layout direction 6601 * resolution to the view's children and resolve layout direction for this view. 6602 * 6603 * @param layoutDirection the layout direction to set. Should be one of: 6604 * 6605 * {@link #LAYOUT_DIRECTION_LTR}, 6606 * {@link #LAYOUT_DIRECTION_RTL}, 6607 * {@link #LAYOUT_DIRECTION_INHERIT}, 6608 * {@link #LAYOUT_DIRECTION_LOCALE}. 6609 * 6610 * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution 6611 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 6612 * will return the default {@link #LAYOUT_DIRECTION_LTR}. 6613 * 6614 * @attr ref android.R.styleable#View_layoutDirection 6615 */ 6616 @RemotableViewMethod 6617 public void setLayoutDirection(@LayoutDir int layoutDirection) { 6618 if (getRawLayoutDirection() != layoutDirection) { 6619 // Reset the current layout direction and the resolved one 6620 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 6621 resetRtlProperties(); 6622 // Set the new layout direction (filtered) 6623 mPrivateFlags2 |= 6624 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 6625 // We need to resolve all RTL properties as they all depend on layout direction 6626 resolveRtlPropertiesIfNeeded(); 6627 requestLayout(); 6628 invalidate(true); 6629 } 6630 } 6631 6632 /** 6633 * Returns the resolved layout direction for this view. 6634 * 6635 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 6636 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 6637 * 6638 * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version 6639 * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}. 6640 * 6641 * @attr ref android.R.styleable#View_layoutDirection 6642 */ 6643 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6644 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 6645 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 6646 }) 6647 @ResolvedLayoutDir 6648 public int getLayoutDirection() { 6649 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 6650 if (targetSdkVersion < JELLY_BEAN_MR1) { 6651 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 6652 return LAYOUT_DIRECTION_RESOLVED_DEFAULT; 6653 } 6654 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == 6655 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 6656 } 6657 6658 /** 6659 * Indicates whether or not this view's layout is right-to-left. This is resolved from 6660 * layout attribute and/or the inherited value from the parent 6661 * 6662 * @return true if the layout is right-to-left. 6663 * 6664 * @hide 6665 */ 6666 @ViewDebug.ExportedProperty(category = "layout") 6667 public boolean isLayoutRtl() { 6668 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 6669 } 6670 6671 /** 6672 * Indicates whether the view is currently tracking transient state that the 6673 * app should not need to concern itself with saving and restoring, but that 6674 * the framework should take special note to preserve when possible. 6675 * 6676 * <p>A view with transient state cannot be trivially rebound from an external 6677 * data source, such as an adapter binding item views in a list. This may be 6678 * because the view is performing an animation, tracking user selection 6679 * of content, or similar.</p> 6680 * 6681 * @return true if the view has transient state 6682 */ 6683 @ViewDebug.ExportedProperty(category = "layout") 6684 public boolean hasTransientState() { 6685 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 6686 } 6687 6688 /** 6689 * Set whether this view is currently tracking transient state that the 6690 * framework should attempt to preserve when possible. This flag is reference counted, 6691 * so every call to setHasTransientState(true) should be paired with a later call 6692 * to setHasTransientState(false). 6693 * 6694 * <p>A view with transient state cannot be trivially rebound from an external 6695 * data source, such as an adapter binding item views in a list. This may be 6696 * because the view is performing an animation, tracking user selection 6697 * of content, or similar.</p> 6698 * 6699 * @param hasTransientState true if this view has transient state 6700 */ 6701 public void setHasTransientState(boolean hasTransientState) { 6702 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 6703 mTransientStateCount - 1; 6704 if (mTransientStateCount < 0) { 6705 mTransientStateCount = 0; 6706 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 6707 "unmatched pair of setHasTransientState calls"); 6708 } else if ((hasTransientState && mTransientStateCount == 1) || 6709 (!hasTransientState && mTransientStateCount == 0)) { 6710 // update flag if we've just incremented up from 0 or decremented down to 0 6711 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 6712 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 6713 if (mParent != null) { 6714 try { 6715 mParent.childHasTransientStateChanged(this, hasTransientState); 6716 } catch (AbstractMethodError e) { 6717 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 6718 " does not fully implement ViewParent", e); 6719 } 6720 } 6721 } 6722 } 6723 6724 /** 6725 * Returns true if this view is currently attached to a window. 6726 */ 6727 public boolean isAttachedToWindow() { 6728 return mAttachInfo != null; 6729 } 6730 6731 /** 6732 * Returns true if this view has been through at least one layout since it 6733 * was last attached to or detached from a window. 6734 */ 6735 public boolean isLaidOut() { 6736 return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT; 6737 } 6738 6739 /** 6740 * If this view doesn't do any drawing on its own, set this flag to 6741 * allow further optimizations. By default, this flag is not set on 6742 * View, but could be set on some View subclasses such as ViewGroup. 6743 * 6744 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 6745 * you should clear this flag. 6746 * 6747 * @param willNotDraw whether or not this View draw on its own 6748 */ 6749 public void setWillNotDraw(boolean willNotDraw) { 6750 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 6751 } 6752 6753 /** 6754 * Returns whether or not this View draws on its own. 6755 * 6756 * @return true if this view has nothing to draw, false otherwise 6757 */ 6758 @ViewDebug.ExportedProperty(category = "drawing") 6759 public boolean willNotDraw() { 6760 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 6761 } 6762 6763 /** 6764 * When a View's drawing cache is enabled, drawing is redirected to an 6765 * offscreen bitmap. Some views, like an ImageView, must be able to 6766 * bypass this mechanism if they already draw a single bitmap, to avoid 6767 * unnecessary usage of the memory. 6768 * 6769 * @param willNotCacheDrawing true if this view does not cache its 6770 * drawing, false otherwise 6771 */ 6772 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 6773 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 6774 } 6775 6776 /** 6777 * Returns whether or not this View can cache its drawing or not. 6778 * 6779 * @return true if this view does not cache its drawing, false otherwise 6780 */ 6781 @ViewDebug.ExportedProperty(category = "drawing") 6782 public boolean willNotCacheDrawing() { 6783 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 6784 } 6785 6786 /** 6787 * Indicates whether this view reacts to click events or not. 6788 * 6789 * @return true if the view is clickable, false otherwise 6790 * 6791 * @see #setClickable(boolean) 6792 * @attr ref android.R.styleable#View_clickable 6793 */ 6794 @ViewDebug.ExportedProperty 6795 public boolean isClickable() { 6796 return (mViewFlags & CLICKABLE) == CLICKABLE; 6797 } 6798 6799 /** 6800 * Enables or disables click events for this view. When a view 6801 * is clickable it will change its state to "pressed" on every click. 6802 * Subclasses should set the view clickable to visually react to 6803 * user's clicks. 6804 * 6805 * @param clickable true to make the view clickable, false otherwise 6806 * 6807 * @see #isClickable() 6808 * @attr ref android.R.styleable#View_clickable 6809 */ 6810 public void setClickable(boolean clickable) { 6811 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 6812 } 6813 6814 /** 6815 * Indicates whether this view reacts to long click events or not. 6816 * 6817 * @return true if the view is long clickable, false otherwise 6818 * 6819 * @see #setLongClickable(boolean) 6820 * @attr ref android.R.styleable#View_longClickable 6821 */ 6822 public boolean isLongClickable() { 6823 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 6824 } 6825 6826 /** 6827 * Enables or disables long click events for this view. When a view is long 6828 * clickable it reacts to the user holding down the button for a longer 6829 * duration than a tap. This event can either launch the listener or a 6830 * context menu. 6831 * 6832 * @param longClickable true to make the view long clickable, false otherwise 6833 * @see #isLongClickable() 6834 * @attr ref android.R.styleable#View_longClickable 6835 */ 6836 public void setLongClickable(boolean longClickable) { 6837 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 6838 } 6839 6840 /** 6841 * Sets the pressed state for this view and provides a touch coordinate for 6842 * animation hinting. 6843 * 6844 * @param pressed Pass true to set the View's internal state to "pressed", 6845 * or false to reverts the View's internal state from a 6846 * previously set "pressed" state. 6847 * @param x The x coordinate of the touch that caused the press 6848 * @param y The y coordinate of the touch that caused the press 6849 */ 6850 private void setPressed(boolean pressed, float x, float y) { 6851 if (pressed) { 6852 drawableHotspotChanged(x, y); 6853 } 6854 6855 setPressed(pressed); 6856 } 6857 6858 /** 6859 * Sets the pressed state for this view. 6860 * 6861 * @see #isClickable() 6862 * @see #setClickable(boolean) 6863 * 6864 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 6865 * the View's internal state from a previously set "pressed" state. 6866 */ 6867 public void setPressed(boolean pressed) { 6868 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 6869 6870 if (pressed) { 6871 mPrivateFlags |= PFLAG_PRESSED; 6872 } else { 6873 mPrivateFlags &= ~PFLAG_PRESSED; 6874 } 6875 6876 if (needsRefresh) { 6877 refreshDrawableState(); 6878 } 6879 dispatchSetPressed(pressed); 6880 } 6881 6882 /** 6883 * Dispatch setPressed to all of this View's children. 6884 * 6885 * @see #setPressed(boolean) 6886 * 6887 * @param pressed The new pressed state 6888 */ 6889 protected void dispatchSetPressed(boolean pressed) { 6890 } 6891 6892 /** 6893 * Indicates whether the view is currently in pressed state. Unless 6894 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 6895 * the pressed state. 6896 * 6897 * @see #setPressed(boolean) 6898 * @see #isClickable() 6899 * @see #setClickable(boolean) 6900 * 6901 * @return true if the view is currently pressed, false otherwise 6902 */ 6903 @ViewDebug.ExportedProperty 6904 public boolean isPressed() { 6905 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 6906 } 6907 6908 /** 6909 * Indicates whether this view will save its state (that is, 6910 * whether its {@link #onSaveInstanceState} method will be called). 6911 * 6912 * @return Returns true if the view state saving is enabled, else false. 6913 * 6914 * @see #setSaveEnabled(boolean) 6915 * @attr ref android.R.styleable#View_saveEnabled 6916 */ 6917 public boolean isSaveEnabled() { 6918 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 6919 } 6920 6921 /** 6922 * Controls whether the saving of this view's state is 6923 * enabled (that is, whether its {@link #onSaveInstanceState} method 6924 * will be called). Note that even if freezing is enabled, the 6925 * view still must have an id assigned to it (via {@link #setId(int)}) 6926 * for its state to be saved. This flag can only disable the 6927 * saving of this view; any child views may still have their state saved. 6928 * 6929 * @param enabled Set to false to <em>disable</em> state saving, or true 6930 * (the default) to allow it. 6931 * 6932 * @see #isSaveEnabled() 6933 * @see #setId(int) 6934 * @see #onSaveInstanceState() 6935 * @attr ref android.R.styleable#View_saveEnabled 6936 */ 6937 public void setSaveEnabled(boolean enabled) { 6938 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 6939 } 6940 6941 /** 6942 * Gets whether the framework should discard touches when the view's 6943 * window is obscured by another visible window. 6944 * Refer to the {@link View} security documentation for more details. 6945 * 6946 * @return True if touch filtering is enabled. 6947 * 6948 * @see #setFilterTouchesWhenObscured(boolean) 6949 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6950 */ 6951 @ViewDebug.ExportedProperty 6952 public boolean getFilterTouchesWhenObscured() { 6953 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 6954 } 6955 6956 /** 6957 * Sets whether the framework should discard touches when the view's 6958 * window is obscured by another visible window. 6959 * Refer to the {@link View} security documentation for more details. 6960 * 6961 * @param enabled True if touch filtering should be enabled. 6962 * 6963 * @see #getFilterTouchesWhenObscured 6964 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6965 */ 6966 public void setFilterTouchesWhenObscured(boolean enabled) { 6967 setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0, 6968 FILTER_TOUCHES_WHEN_OBSCURED); 6969 } 6970 6971 /** 6972 * Indicates whether the entire hierarchy under this view will save its 6973 * state when a state saving traversal occurs from its parent. The default 6974 * is true; if false, these views will not be saved unless 6975 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6976 * 6977 * @return Returns true if the view state saving from parent is enabled, else false. 6978 * 6979 * @see #setSaveFromParentEnabled(boolean) 6980 */ 6981 public boolean isSaveFromParentEnabled() { 6982 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 6983 } 6984 6985 /** 6986 * Controls whether the entire hierarchy under this view will save its 6987 * state when a state saving traversal occurs from its parent. The default 6988 * is true; if false, these views will not be saved unless 6989 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6990 * 6991 * @param enabled Set to false to <em>disable</em> state saving, or true 6992 * (the default) to allow it. 6993 * 6994 * @see #isSaveFromParentEnabled() 6995 * @see #setId(int) 6996 * @see #onSaveInstanceState() 6997 */ 6998 public void setSaveFromParentEnabled(boolean enabled) { 6999 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 7000 } 7001 7002 7003 /** 7004 * Returns whether this View is able to take focus. 7005 * 7006 * @return True if this view can take focus, or false otherwise. 7007 * @attr ref android.R.styleable#View_focusable 7008 */ 7009 @ViewDebug.ExportedProperty(category = "focus") 7010 public final boolean isFocusable() { 7011 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 7012 } 7013 7014 /** 7015 * When a view is focusable, it may not want to take focus when in touch mode. 7016 * For example, a button would like focus when the user is navigating via a D-pad 7017 * so that the user can click on it, but once the user starts touching the screen, 7018 * the button shouldn't take focus 7019 * @return Whether the view is focusable in touch mode. 7020 * @attr ref android.R.styleable#View_focusableInTouchMode 7021 */ 7022 @ViewDebug.ExportedProperty 7023 public final boolean isFocusableInTouchMode() { 7024 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 7025 } 7026 7027 /** 7028 * Find the nearest view in the specified direction that can take focus. 7029 * This does not actually give focus to that view. 7030 * 7031 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7032 * 7033 * @return The nearest focusable in the specified direction, or null if none 7034 * can be found. 7035 */ 7036 public View focusSearch(@FocusRealDirection int direction) { 7037 if (mParent != null) { 7038 return mParent.focusSearch(this, direction); 7039 } else { 7040 return null; 7041 } 7042 } 7043 7044 /** 7045 * This method is the last chance for the focused view and its ancestors to 7046 * respond to an arrow key. This is called when the focused view did not 7047 * consume the key internally, nor could the view system find a new view in 7048 * the requested direction to give focus to. 7049 * 7050 * @param focused The currently focused view. 7051 * @param direction The direction focus wants to move. One of FOCUS_UP, 7052 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 7053 * @return True if the this view consumed this unhandled move. 7054 */ 7055 public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) { 7056 return false; 7057 } 7058 7059 /** 7060 * If a user manually specified the next view id for a particular direction, 7061 * use the root to look up the view. 7062 * @param root The root view of the hierarchy containing this view. 7063 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 7064 * or FOCUS_BACKWARD. 7065 * @return The user specified next view, or null if there is none. 7066 */ 7067 View findUserSetNextFocus(View root, @FocusDirection int direction) { 7068 switch (direction) { 7069 case FOCUS_LEFT: 7070 if (mNextFocusLeftId == View.NO_ID) return null; 7071 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 7072 case FOCUS_RIGHT: 7073 if (mNextFocusRightId == View.NO_ID) return null; 7074 return findViewInsideOutShouldExist(root, mNextFocusRightId); 7075 case FOCUS_UP: 7076 if (mNextFocusUpId == View.NO_ID) return null; 7077 return findViewInsideOutShouldExist(root, mNextFocusUpId); 7078 case FOCUS_DOWN: 7079 if (mNextFocusDownId == View.NO_ID) return null; 7080 return findViewInsideOutShouldExist(root, mNextFocusDownId); 7081 case FOCUS_FORWARD: 7082 if (mNextFocusForwardId == View.NO_ID) return null; 7083 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 7084 case FOCUS_BACKWARD: { 7085 if (mID == View.NO_ID) return null; 7086 final int id = mID; 7087 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 7088 @Override 7089 public boolean apply(View t) { 7090 return t.mNextFocusForwardId == id; 7091 } 7092 }); 7093 } 7094 } 7095 return null; 7096 } 7097 7098 private View findViewInsideOutShouldExist(View root, int id) { 7099 if (mMatchIdPredicate == null) { 7100 mMatchIdPredicate = new MatchIdPredicate(); 7101 } 7102 mMatchIdPredicate.mId = id; 7103 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 7104 if (result == null) { 7105 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 7106 } 7107 return result; 7108 } 7109 7110 /** 7111 * Find and return all focusable views that are descendants of this view, 7112 * possibly including this view if it is focusable itself. 7113 * 7114 * @param direction The direction of the focus 7115 * @return A list of focusable views 7116 */ 7117 public ArrayList<View> getFocusables(@FocusDirection int direction) { 7118 ArrayList<View> result = new ArrayList<View>(24); 7119 addFocusables(result, direction); 7120 return result; 7121 } 7122 7123 /** 7124 * Add any focusable views that are descendants of this view (possibly 7125 * including this view if it is focusable itself) to views. If we are in touch mode, 7126 * only add views that are also focusable in touch mode. 7127 * 7128 * @param views Focusable views found so far 7129 * @param direction The direction of the focus 7130 */ 7131 public void addFocusables(ArrayList<View> views, @FocusDirection int direction) { 7132 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 7133 } 7134 7135 /** 7136 * Adds any focusable views that are descendants of this view (possibly 7137 * including this view if it is focusable itself) to views. This method 7138 * adds all focusable views regardless if we are in touch mode or 7139 * only views focusable in touch mode if we are in touch mode or 7140 * only views that can take accessibility focus if accessibility is enabeld 7141 * depending on the focusable mode paramater. 7142 * 7143 * @param views Focusable views found so far or null if all we are interested is 7144 * the number of focusables. 7145 * @param direction The direction of the focus. 7146 * @param focusableMode The type of focusables to be added. 7147 * 7148 * @see #FOCUSABLES_ALL 7149 * @see #FOCUSABLES_TOUCH_MODE 7150 */ 7151 public void addFocusables(ArrayList<View> views, @FocusDirection int direction, 7152 @FocusableMode int focusableMode) { 7153 if (views == null) { 7154 return; 7155 } 7156 if (!isFocusable()) { 7157 return; 7158 } 7159 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 7160 && isInTouchMode() && !isFocusableInTouchMode()) { 7161 return; 7162 } 7163 views.add(this); 7164 } 7165 7166 /** 7167 * Finds the Views that contain given text. The containment is case insensitive. 7168 * The search is performed by either the text that the View renders or the content 7169 * description that describes the view for accessibility purposes and the view does 7170 * not render or both. Clients can specify how the search is to be performed via 7171 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 7172 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 7173 * 7174 * @param outViews The output list of matching Views. 7175 * @param searched The text to match against. 7176 * 7177 * @see #FIND_VIEWS_WITH_TEXT 7178 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 7179 * @see #setContentDescription(CharSequence) 7180 */ 7181 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, 7182 @FindViewFlags int flags) { 7183 if (getAccessibilityNodeProvider() != null) { 7184 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 7185 outViews.add(this); 7186 } 7187 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 7188 && (searched != null && searched.length() > 0) 7189 && (mContentDescription != null && mContentDescription.length() > 0)) { 7190 String searchedLowerCase = searched.toString().toLowerCase(); 7191 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 7192 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 7193 outViews.add(this); 7194 } 7195 } 7196 } 7197 7198 /** 7199 * Find and return all touchable views that are descendants of this view, 7200 * possibly including this view if it is touchable itself. 7201 * 7202 * @return A list of touchable views 7203 */ 7204 public ArrayList<View> getTouchables() { 7205 ArrayList<View> result = new ArrayList<View>(); 7206 addTouchables(result); 7207 return result; 7208 } 7209 7210 /** 7211 * Add any touchable views that are descendants of this view (possibly 7212 * including this view if it is touchable itself) to views. 7213 * 7214 * @param views Touchable views found so far 7215 */ 7216 public void addTouchables(ArrayList<View> views) { 7217 final int viewFlags = mViewFlags; 7218 7219 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 7220 && (viewFlags & ENABLED_MASK) == ENABLED) { 7221 views.add(this); 7222 } 7223 } 7224 7225 /** 7226 * Returns whether this View is accessibility focused. 7227 * 7228 * @return True if this View is accessibility focused. 7229 */ 7230 public boolean isAccessibilityFocused() { 7231 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 7232 } 7233 7234 /** 7235 * Call this to try to give accessibility focus to this view. 7236 * 7237 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 7238 * returns false or the view is no visible or the view already has accessibility 7239 * focus. 7240 * 7241 * See also {@link #focusSearch(int)}, which is what you call to say that you 7242 * have focus, and you want your parent to look for the next one. 7243 * 7244 * @return Whether this view actually took accessibility focus. 7245 * 7246 * @hide 7247 */ 7248 public boolean requestAccessibilityFocus() { 7249 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 7250 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 7251 return false; 7252 } 7253 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7254 return false; 7255 } 7256 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 7257 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 7258 ViewRootImpl viewRootImpl = getViewRootImpl(); 7259 if (viewRootImpl != null) { 7260 viewRootImpl.setAccessibilityFocus(this, null); 7261 } 7262 invalidate(); 7263 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 7264 return true; 7265 } 7266 return false; 7267 } 7268 7269 /** 7270 * Call this to try to clear accessibility focus of this view. 7271 * 7272 * See also {@link #focusSearch(int)}, which is what you call to say that you 7273 * have focus, and you want your parent to look for the next one. 7274 * 7275 * @hide 7276 */ 7277 public void clearAccessibilityFocus() { 7278 clearAccessibilityFocusNoCallbacks(); 7279 // Clear the global reference of accessibility focus if this 7280 // view or any of its descendants had accessibility focus. 7281 ViewRootImpl viewRootImpl = getViewRootImpl(); 7282 if (viewRootImpl != null) { 7283 View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 7284 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 7285 viewRootImpl.setAccessibilityFocus(null, null); 7286 } 7287 } 7288 } 7289 7290 private void sendAccessibilityHoverEvent(int eventType) { 7291 // Since we are not delivering to a client accessibility events from not 7292 // important views (unless the clinet request that) we need to fire the 7293 // event from the deepest view exposed to the client. As a consequence if 7294 // the user crosses a not exposed view the client will see enter and exit 7295 // of the exposed predecessor followed by and enter and exit of that same 7296 // predecessor when entering and exiting the not exposed descendant. This 7297 // is fine since the client has a clear idea which view is hovered at the 7298 // price of a couple more events being sent. This is a simple and 7299 // working solution. 7300 View source = this; 7301 while (true) { 7302 if (source.includeForAccessibility()) { 7303 source.sendAccessibilityEvent(eventType); 7304 return; 7305 } 7306 ViewParent parent = source.getParent(); 7307 if (parent instanceof View) { 7308 source = (View) parent; 7309 } else { 7310 return; 7311 } 7312 } 7313 } 7314 7315 /** 7316 * Clears accessibility focus without calling any callback methods 7317 * normally invoked in {@link #clearAccessibilityFocus()}. This method 7318 * is used for clearing accessibility focus when giving this focus to 7319 * another view. 7320 */ 7321 void clearAccessibilityFocusNoCallbacks() { 7322 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 7323 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 7324 invalidate(); 7325 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 7326 } 7327 } 7328 7329 /** 7330 * Call this to try to give focus to a specific view or to one of its 7331 * descendants. 7332 * 7333 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7334 * false), or if it is focusable and it is not focusable in touch mode 7335 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7336 * 7337 * See also {@link #focusSearch(int)}, which is what you call to say that you 7338 * have focus, and you want your parent to look for the next one. 7339 * 7340 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 7341 * {@link #FOCUS_DOWN} and <code>null</code>. 7342 * 7343 * @return Whether this view or one of its descendants actually took focus. 7344 */ 7345 public final boolean requestFocus() { 7346 return requestFocus(View.FOCUS_DOWN); 7347 } 7348 7349 /** 7350 * Call this to try to give focus to a specific view or to one of its 7351 * descendants and give it a hint about what direction focus is heading. 7352 * 7353 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7354 * false), or if it is focusable and it is not focusable in touch mode 7355 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7356 * 7357 * See also {@link #focusSearch(int)}, which is what you call to say that you 7358 * have focus, and you want your parent to look for the next one. 7359 * 7360 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 7361 * <code>null</code> set for the previously focused rectangle. 7362 * 7363 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7364 * @return Whether this view or one of its descendants actually took focus. 7365 */ 7366 public final boolean requestFocus(int direction) { 7367 return requestFocus(direction, null); 7368 } 7369 7370 /** 7371 * Call this to try to give focus to a specific view or to one of its descendants 7372 * and give it hints about the direction and a specific rectangle that the focus 7373 * is coming from. The rectangle can help give larger views a finer grained hint 7374 * about where focus is coming from, and therefore, where to show selection, or 7375 * forward focus change internally. 7376 * 7377 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7378 * false), or if it is focusable and it is not focusable in touch mode 7379 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7380 * 7381 * A View will not take focus if it is not visible. 7382 * 7383 * A View will not take focus if one of its parents has 7384 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 7385 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 7386 * 7387 * See also {@link #focusSearch(int)}, which is what you call to say that you 7388 * have focus, and you want your parent to look for the next one. 7389 * 7390 * You may wish to override this method if your custom {@link View} has an internal 7391 * {@link View} that it wishes to forward the request to. 7392 * 7393 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7394 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 7395 * to give a finer grained hint about where focus is coming from. May be null 7396 * if there is no hint. 7397 * @return Whether this view or one of its descendants actually took focus. 7398 */ 7399 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 7400 return requestFocusNoSearch(direction, previouslyFocusedRect); 7401 } 7402 7403 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 7404 // need to be focusable 7405 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 7406 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7407 return false; 7408 } 7409 7410 // need to be focusable in touch mode if in touch mode 7411 if (isInTouchMode() && 7412 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 7413 return false; 7414 } 7415 7416 // need to not have any parents blocking us 7417 if (hasAncestorThatBlocksDescendantFocus()) { 7418 return false; 7419 } 7420 7421 handleFocusGainInternal(direction, previouslyFocusedRect); 7422 return true; 7423 } 7424 7425 /** 7426 * Call this to try to give focus to a specific view or to one of its descendants. This is a 7427 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 7428 * touch mode to request focus when they are touched. 7429 * 7430 * @return Whether this view or one of its descendants actually took focus. 7431 * 7432 * @see #isInTouchMode() 7433 * 7434 */ 7435 public final boolean requestFocusFromTouch() { 7436 // Leave touch mode if we need to 7437 if (isInTouchMode()) { 7438 ViewRootImpl viewRoot = getViewRootImpl(); 7439 if (viewRoot != null) { 7440 viewRoot.ensureTouchMode(false); 7441 } 7442 } 7443 return requestFocus(View.FOCUS_DOWN); 7444 } 7445 7446 /** 7447 * @return Whether any ancestor of this view blocks descendant focus. 7448 */ 7449 private boolean hasAncestorThatBlocksDescendantFocus() { 7450 final boolean focusableInTouchMode = isFocusableInTouchMode(); 7451 ViewParent ancestor = mParent; 7452 while (ancestor instanceof ViewGroup) { 7453 final ViewGroup vgAncestor = (ViewGroup) ancestor; 7454 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS 7455 || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) { 7456 return true; 7457 } else { 7458 ancestor = vgAncestor.getParent(); 7459 } 7460 } 7461 return false; 7462 } 7463 7464 /** 7465 * Gets the mode for determining whether this View is important for accessibility 7466 * which is if it fires accessibility events and if it is reported to 7467 * accessibility services that query the screen. 7468 * 7469 * @return The mode for determining whether a View is important for accessibility. 7470 * 7471 * @attr ref android.R.styleable#View_importantForAccessibility 7472 * 7473 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7474 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7475 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7476 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7477 */ 7478 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 7479 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 7480 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 7481 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"), 7482 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS, 7483 to = "noHideDescendants") 7484 }) 7485 public int getImportantForAccessibility() { 7486 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7487 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7488 } 7489 7490 /** 7491 * Sets the live region mode for this view. This indicates to accessibility 7492 * services whether they should automatically notify the user about changes 7493 * to the view's content description or text, or to the content descriptions 7494 * or text of the view's children (where applicable). 7495 * <p> 7496 * For example, in a login screen with a TextView that displays an "incorrect 7497 * password" notification, that view should be marked as a live region with 7498 * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7499 * <p> 7500 * To disable change notifications for this view, use 7501 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region 7502 * mode for most views. 7503 * <p> 7504 * To indicate that the user should be notified of changes, use 7505 * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7506 * <p> 7507 * If the view's changes should interrupt ongoing speech and notify the user 7508 * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}. 7509 * 7510 * @param mode The live region mode for this view, one of: 7511 * <ul> 7512 * <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE} 7513 * <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE} 7514 * <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE} 7515 * </ul> 7516 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7517 */ 7518 public void setAccessibilityLiveRegion(int mode) { 7519 if (mode != getAccessibilityLiveRegion()) { 7520 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7521 mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT) 7522 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7523 notifyViewAccessibilityStateChangedIfNeeded( 7524 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7525 } 7526 } 7527 7528 /** 7529 * Gets the live region mode for this View. 7530 * 7531 * @return The live region mode for the view. 7532 * 7533 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7534 * 7535 * @see #setAccessibilityLiveRegion(int) 7536 */ 7537 public int getAccessibilityLiveRegion() { 7538 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK) 7539 >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 7540 } 7541 7542 /** 7543 * Sets how to determine whether this view is important for accessibility 7544 * which is if it fires accessibility events and if it is reported to 7545 * accessibility services that query the screen. 7546 * 7547 * @param mode How to determine whether this view is important for accessibility. 7548 * 7549 * @attr ref android.R.styleable#View_importantForAccessibility 7550 * 7551 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7552 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7553 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7554 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7555 */ 7556 public void setImportantForAccessibility(int mode) { 7557 final int oldMode = getImportantForAccessibility(); 7558 if (mode != oldMode) { 7559 // If we're moving between AUTO and another state, we might not need 7560 // to send a subtree changed notification. We'll store the computed 7561 // importance, since we'll need to check it later to make sure. 7562 final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO 7563 || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO; 7564 final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility(); 7565 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7566 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 7567 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7568 if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) { 7569 notifySubtreeAccessibilityStateChangedIfNeeded(); 7570 } else { 7571 notifyViewAccessibilityStateChangedIfNeeded( 7572 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7573 } 7574 } 7575 } 7576 7577 /** 7578 * Computes whether this view should be exposed for accessibility. In 7579 * general, views that are interactive or provide information are exposed 7580 * while views that serve only as containers are hidden. 7581 * <p> 7582 * If an ancestor of this view has importance 7583 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method 7584 * returns <code>false</code>. 7585 * <p> 7586 * Otherwise, the value is computed according to the view's 7587 * {@link #getImportantForAccessibility()} value: 7588 * <ol> 7589 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or 7590 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false 7591 * </code> 7592 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code> 7593 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if 7594 * view satisfies any of the following: 7595 * <ul> 7596 * <li>Is actionable, e.g. {@link #isClickable()}, 7597 * {@link #isLongClickable()}, or {@link #isFocusable()} 7598 * <li>Has an {@link AccessibilityDelegate} 7599 * <li>Has an interaction listener, e.g. {@link OnTouchListener}, 7600 * {@link OnKeyListener}, etc. 7601 * <li>Is an accessibility live region, e.g. 7602 * {@link #getAccessibilityLiveRegion()} is not 7603 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. 7604 * </ul> 7605 * </ol> 7606 * 7607 * @return Whether the view is exposed for accessibility. 7608 * @see #setImportantForAccessibility(int) 7609 * @see #getImportantForAccessibility() 7610 */ 7611 public boolean isImportantForAccessibility() { 7612 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7613 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7614 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO 7615 || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 7616 return false; 7617 } 7618 7619 // Check parent mode to ensure we're not hidden. 7620 ViewParent parent = mParent; 7621 while (parent instanceof View) { 7622 if (((View) parent).getImportantForAccessibility() 7623 == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 7624 return false; 7625 } 7626 parent = parent.getParent(); 7627 } 7628 7629 return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility() 7630 || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null 7631 || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE; 7632 } 7633 7634 /** 7635 * Gets the parent for accessibility purposes. Note that the parent for 7636 * accessibility is not necessary the immediate parent. It is the first 7637 * predecessor that is important for accessibility. 7638 * 7639 * @return The parent for accessibility purposes. 7640 */ 7641 public ViewParent getParentForAccessibility() { 7642 if (mParent instanceof View) { 7643 View parentView = (View) mParent; 7644 if (parentView.includeForAccessibility()) { 7645 return mParent; 7646 } else { 7647 return mParent.getParentForAccessibility(); 7648 } 7649 } 7650 return null; 7651 } 7652 7653 /** 7654 * Adds the children of a given View for accessibility. Since some Views are 7655 * not important for accessibility the children for accessibility are not 7656 * necessarily direct children of the view, rather they are the first level of 7657 * descendants important for accessibility. 7658 * 7659 * @param children The list of children for accessibility. 7660 */ 7661 public void addChildrenForAccessibility(ArrayList<View> children) { 7662 7663 } 7664 7665 /** 7666 * Whether to regard this view for accessibility. A view is regarded for 7667 * accessibility if it is important for accessibility or the querying 7668 * accessibility service has explicitly requested that view not 7669 * important for accessibility are regarded. 7670 * 7671 * @return Whether to regard the view for accessibility. 7672 * 7673 * @hide 7674 */ 7675 public boolean includeForAccessibility() { 7676 if (mAttachInfo != null) { 7677 return (mAttachInfo.mAccessibilityFetchFlags 7678 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0 7679 || isImportantForAccessibility(); 7680 } 7681 return false; 7682 } 7683 7684 /** 7685 * Returns whether the View is considered actionable from 7686 * accessibility perspective. Such view are important for 7687 * accessibility. 7688 * 7689 * @return True if the view is actionable for accessibility. 7690 * 7691 * @hide 7692 */ 7693 public boolean isActionableForAccessibility() { 7694 return (isClickable() || isLongClickable() || isFocusable()); 7695 } 7696 7697 /** 7698 * Returns whether the View has registered callbacks which makes it 7699 * important for accessibility. 7700 * 7701 * @return True if the view is actionable for accessibility. 7702 */ 7703 private boolean hasListenersForAccessibility() { 7704 ListenerInfo info = getListenerInfo(); 7705 return mTouchDelegate != null || info.mOnKeyListener != null 7706 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 7707 || info.mOnHoverListener != null || info.mOnDragListener != null; 7708 } 7709 7710 /** 7711 * Notifies that the accessibility state of this view changed. The change 7712 * is local to this view and does not represent structural changes such 7713 * as children and parent. For example, the view became focusable. The 7714 * notification is at at most once every 7715 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7716 * to avoid unnecessary load to the system. Also once a view has a pending 7717 * notification this method is a NOP until the notification has been sent. 7718 * 7719 * @hide 7720 */ 7721 public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) { 7722 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7723 return; 7724 } 7725 if (mSendViewStateChangedAccessibilityEvent == null) { 7726 mSendViewStateChangedAccessibilityEvent = 7727 new SendViewStateChangedAccessibilityEvent(); 7728 } 7729 mSendViewStateChangedAccessibilityEvent.runOrPost(changeType); 7730 } 7731 7732 /** 7733 * Notifies that the accessibility state of this view changed. The change 7734 * is *not* local to this view and does represent structural changes such 7735 * as children and parent. For example, the view size changed. The 7736 * notification is at at most once every 7737 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7738 * to avoid unnecessary load to the system. Also once a view has a pending 7739 * notification this method is a NOP until the notification has been sent. 7740 * 7741 * @hide 7742 */ 7743 public void notifySubtreeAccessibilityStateChangedIfNeeded() { 7744 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7745 return; 7746 } 7747 if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) { 7748 mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 7749 if (mParent != null) { 7750 try { 7751 mParent.notifySubtreeAccessibilityStateChanged( 7752 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE); 7753 } catch (AbstractMethodError e) { 7754 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 7755 " does not fully implement ViewParent", e); 7756 } 7757 } 7758 } 7759 } 7760 7761 /** 7762 * Reset the flag indicating the accessibility state of the subtree rooted 7763 * at this view changed. 7764 */ 7765 void resetSubtreeAccessibilityStateChanged() { 7766 mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 7767 } 7768 7769 /** 7770 * Performs the specified accessibility action on the view. For 7771 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 7772 * <p> 7773 * If an {@link AccessibilityDelegate} has been specified via calling 7774 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 7775 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 7776 * is responsible for handling this call. 7777 * </p> 7778 * 7779 * @param action The action to perform. 7780 * @param arguments Optional action arguments. 7781 * @return Whether the action was performed. 7782 */ 7783 public boolean performAccessibilityAction(int action, Bundle arguments) { 7784 if (mAccessibilityDelegate != null) { 7785 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 7786 } else { 7787 return performAccessibilityActionInternal(action, arguments); 7788 } 7789 } 7790 7791 /** 7792 * @see #performAccessibilityAction(int, Bundle) 7793 * 7794 * Note: Called from the default {@link AccessibilityDelegate}. 7795 */ 7796 boolean performAccessibilityActionInternal(int action, Bundle arguments) { 7797 switch (action) { 7798 case AccessibilityNodeInfo.ACTION_CLICK: { 7799 if (isClickable()) { 7800 performClick(); 7801 return true; 7802 } 7803 } break; 7804 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 7805 if (isLongClickable()) { 7806 performLongClick(); 7807 return true; 7808 } 7809 } break; 7810 case AccessibilityNodeInfo.ACTION_FOCUS: { 7811 if (!hasFocus()) { 7812 // Get out of touch mode since accessibility 7813 // wants to move focus around. 7814 getViewRootImpl().ensureTouchMode(false); 7815 return requestFocus(); 7816 } 7817 } break; 7818 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 7819 if (hasFocus()) { 7820 clearFocus(); 7821 return !isFocused(); 7822 } 7823 } break; 7824 case AccessibilityNodeInfo.ACTION_SELECT: { 7825 if (!isSelected()) { 7826 setSelected(true); 7827 return isSelected(); 7828 } 7829 } break; 7830 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 7831 if (isSelected()) { 7832 setSelected(false); 7833 return !isSelected(); 7834 } 7835 } break; 7836 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 7837 if (!isAccessibilityFocused()) { 7838 return requestAccessibilityFocus(); 7839 } 7840 } break; 7841 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 7842 if (isAccessibilityFocused()) { 7843 clearAccessibilityFocus(); 7844 return true; 7845 } 7846 } break; 7847 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 7848 if (arguments != null) { 7849 final int granularity = arguments.getInt( 7850 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 7851 final boolean extendSelection = arguments.getBoolean( 7852 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 7853 return traverseAtGranularity(granularity, true, extendSelection); 7854 } 7855 } break; 7856 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 7857 if (arguments != null) { 7858 final int granularity = arguments.getInt( 7859 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 7860 final boolean extendSelection = arguments.getBoolean( 7861 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 7862 return traverseAtGranularity(granularity, false, extendSelection); 7863 } 7864 } break; 7865 case AccessibilityNodeInfo.ACTION_SET_SELECTION: { 7866 CharSequence text = getIterableTextForAccessibility(); 7867 if (text == null) { 7868 return false; 7869 } 7870 final int start = (arguments != null) ? arguments.getInt( 7871 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1; 7872 final int end = (arguments != null) ? arguments.getInt( 7873 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1; 7874 // Only cursor position can be specified (selection length == 0) 7875 if ((getAccessibilitySelectionStart() != start 7876 || getAccessibilitySelectionEnd() != end) 7877 && (start == end)) { 7878 setAccessibilitySelection(start, end); 7879 notifyViewAccessibilityStateChangedIfNeeded( 7880 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7881 return true; 7882 } 7883 } break; 7884 } 7885 return false; 7886 } 7887 7888 private boolean traverseAtGranularity(int granularity, boolean forward, 7889 boolean extendSelection) { 7890 CharSequence text = getIterableTextForAccessibility(); 7891 if (text == null || text.length() == 0) { 7892 return false; 7893 } 7894 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 7895 if (iterator == null) { 7896 return false; 7897 } 7898 int current = getAccessibilitySelectionEnd(); 7899 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 7900 current = forward ? 0 : text.length(); 7901 } 7902 final int[] range = forward ? iterator.following(current) : iterator.preceding(current); 7903 if (range == null) { 7904 return false; 7905 } 7906 final int segmentStart = range[0]; 7907 final int segmentEnd = range[1]; 7908 int selectionStart; 7909 int selectionEnd; 7910 if (extendSelection && isAccessibilitySelectionExtendable()) { 7911 selectionStart = getAccessibilitySelectionStart(); 7912 if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 7913 selectionStart = forward ? segmentStart : segmentEnd; 7914 } 7915 selectionEnd = forward ? segmentEnd : segmentStart; 7916 } else { 7917 selectionStart = selectionEnd= forward ? segmentEnd : segmentStart; 7918 } 7919 setAccessibilitySelection(selectionStart, selectionEnd); 7920 final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY 7921 : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY; 7922 sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd); 7923 return true; 7924 } 7925 7926 /** 7927 * Gets the text reported for accessibility purposes. 7928 * 7929 * @return The accessibility text. 7930 * 7931 * @hide 7932 */ 7933 public CharSequence getIterableTextForAccessibility() { 7934 return getContentDescription(); 7935 } 7936 7937 /** 7938 * Gets whether accessibility selection can be extended. 7939 * 7940 * @return If selection is extensible. 7941 * 7942 * @hide 7943 */ 7944 public boolean isAccessibilitySelectionExtendable() { 7945 return false; 7946 } 7947 7948 /** 7949 * @hide 7950 */ 7951 public int getAccessibilitySelectionStart() { 7952 return mAccessibilityCursorPosition; 7953 } 7954 7955 /** 7956 * @hide 7957 */ 7958 public int getAccessibilitySelectionEnd() { 7959 return getAccessibilitySelectionStart(); 7960 } 7961 7962 /** 7963 * @hide 7964 */ 7965 public void setAccessibilitySelection(int start, int end) { 7966 if (start == end && end == mAccessibilityCursorPosition) { 7967 return; 7968 } 7969 if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) { 7970 mAccessibilityCursorPosition = start; 7971 } else { 7972 mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 7973 } 7974 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 7975 } 7976 7977 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 7978 int fromIndex, int toIndex) { 7979 if (mParent == null) { 7980 return; 7981 } 7982 AccessibilityEvent event = AccessibilityEvent.obtain( 7983 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 7984 onInitializeAccessibilityEvent(event); 7985 onPopulateAccessibilityEvent(event); 7986 event.setFromIndex(fromIndex); 7987 event.setToIndex(toIndex); 7988 event.setAction(action); 7989 event.setMovementGranularity(granularity); 7990 mParent.requestSendAccessibilityEvent(this, event); 7991 } 7992 7993 /** 7994 * @hide 7995 */ 7996 public TextSegmentIterator getIteratorForGranularity(int granularity) { 7997 switch (granularity) { 7998 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 7999 CharSequence text = getIterableTextForAccessibility(); 8000 if (text != null && text.length() > 0) { 8001 CharacterTextSegmentIterator iterator = 8002 CharacterTextSegmentIterator.getInstance( 8003 mContext.getResources().getConfiguration().locale); 8004 iterator.initialize(text.toString()); 8005 return iterator; 8006 } 8007 } break; 8008 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 8009 CharSequence text = getIterableTextForAccessibility(); 8010 if (text != null && text.length() > 0) { 8011 WordTextSegmentIterator iterator = 8012 WordTextSegmentIterator.getInstance( 8013 mContext.getResources().getConfiguration().locale); 8014 iterator.initialize(text.toString()); 8015 return iterator; 8016 } 8017 } break; 8018 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 8019 CharSequence text = getIterableTextForAccessibility(); 8020 if (text != null && text.length() > 0) { 8021 ParagraphTextSegmentIterator iterator = 8022 ParagraphTextSegmentIterator.getInstance(); 8023 iterator.initialize(text.toString()); 8024 return iterator; 8025 } 8026 } break; 8027 } 8028 return null; 8029 } 8030 8031 /** 8032 * @hide 8033 */ 8034 public void dispatchStartTemporaryDetach() { 8035 onStartTemporaryDetach(); 8036 } 8037 8038 /** 8039 * This is called when a container is going to temporarily detach a child, with 8040 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 8041 * It will either be followed by {@link #onFinishTemporaryDetach()} or 8042 * {@link #onDetachedFromWindow()} when the container is done. 8043 */ 8044 public void onStartTemporaryDetach() { 8045 removeUnsetPressCallback(); 8046 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 8047 } 8048 8049 /** 8050 * @hide 8051 */ 8052 public void dispatchFinishTemporaryDetach() { 8053 onFinishTemporaryDetach(); 8054 } 8055 8056 /** 8057 * Called after {@link #onStartTemporaryDetach} when the container is done 8058 * changing the view. 8059 */ 8060 public void onFinishTemporaryDetach() { 8061 } 8062 8063 /** 8064 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 8065 * for this view's window. Returns null if the view is not currently attached 8066 * to the window. Normally you will not need to use this directly, but 8067 * just use the standard high-level event callbacks like 8068 * {@link #onKeyDown(int, KeyEvent)}. 8069 */ 8070 public KeyEvent.DispatcherState getKeyDispatcherState() { 8071 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 8072 } 8073 8074 /** 8075 * Dispatch a key event before it is processed by any input method 8076 * associated with the view hierarchy. This can be used to intercept 8077 * key events in special situations before the IME consumes them; a 8078 * typical example would be handling the BACK key to update the application's 8079 * UI instead of allowing the IME to see it and close itself. 8080 * 8081 * @param event The key event to be dispatched. 8082 * @return True if the event was handled, false otherwise. 8083 */ 8084 public boolean dispatchKeyEventPreIme(KeyEvent event) { 8085 return onKeyPreIme(event.getKeyCode(), event); 8086 } 8087 8088 /** 8089 * Dispatch a key event to the next view on the focus path. This path runs 8090 * from the top of the view tree down to the currently focused view. If this 8091 * view has focus, it will dispatch to itself. Otherwise it will dispatch 8092 * the next node down the focus path. This method also fires any key 8093 * listeners. 8094 * 8095 * @param event The key event to be dispatched. 8096 * @return True if the event was handled, false otherwise. 8097 */ 8098 public boolean dispatchKeyEvent(KeyEvent event) { 8099 if (mInputEventConsistencyVerifier != null) { 8100 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 8101 } 8102 8103 // Give any attached key listener a first crack at the event. 8104 //noinspection SimplifiableIfStatement 8105 ListenerInfo li = mListenerInfo; 8106 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 8107 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 8108 return true; 8109 } 8110 8111 if (event.dispatch(this, mAttachInfo != null 8112 ? mAttachInfo.mKeyDispatchState : null, this)) { 8113 return true; 8114 } 8115 8116 if (mInputEventConsistencyVerifier != null) { 8117 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8118 } 8119 return false; 8120 } 8121 8122 /** 8123 * Dispatches a key shortcut event. 8124 * 8125 * @param event The key event to be dispatched. 8126 * @return True if the event was handled by the view, false otherwise. 8127 */ 8128 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 8129 return onKeyShortcut(event.getKeyCode(), event); 8130 } 8131 8132 /** 8133 * Pass the touch screen motion event down to the target view, or this 8134 * view if it is the target. 8135 * 8136 * @param event The motion event to be dispatched. 8137 * @return True if the event was handled by the view, false otherwise. 8138 */ 8139 public boolean dispatchTouchEvent(MotionEvent event) { 8140 boolean result = false; 8141 8142 if (mInputEventConsistencyVerifier != null) { 8143 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 8144 } 8145 8146 final int actionMasked = event.getActionMasked(); 8147 if (actionMasked == MotionEvent.ACTION_DOWN) { 8148 // Defensive cleanup for new gesture 8149 stopNestedScroll(); 8150 } 8151 8152 if (onFilterTouchEventForSecurity(event)) { 8153 //noinspection SimplifiableIfStatement 8154 ListenerInfo li = mListenerInfo; 8155 if (li != null && li.mOnTouchListener != null 8156 && (mViewFlags & ENABLED_MASK) == ENABLED 8157 && li.mOnTouchListener.onTouch(this, event)) { 8158 result = true; 8159 } 8160 8161 if (!result && onTouchEvent(event)) { 8162 result = true; 8163 } 8164 } 8165 8166 if (!result && mInputEventConsistencyVerifier != null) { 8167 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8168 } 8169 8170 // Clean up after nested scrolls if this is the end of a gesture; 8171 // also cancel it if we tried an ACTION_DOWN but we didn't want the rest 8172 // of the gesture. 8173 if (actionMasked == MotionEvent.ACTION_UP || 8174 actionMasked == MotionEvent.ACTION_CANCEL || 8175 (actionMasked == MotionEvent.ACTION_DOWN && !result)) { 8176 stopNestedScroll(); 8177 } 8178 8179 return result; 8180 } 8181 8182 /** 8183 * Filter the touch event to apply security policies. 8184 * 8185 * @param event The motion event to be filtered. 8186 * @return True if the event should be dispatched, false if the event should be dropped. 8187 * 8188 * @see #getFilterTouchesWhenObscured 8189 */ 8190 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 8191 //noinspection RedundantIfStatement 8192 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 8193 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 8194 // Window is obscured, drop this touch. 8195 return false; 8196 } 8197 return true; 8198 } 8199 8200 /** 8201 * Pass a trackball motion event down to the focused view. 8202 * 8203 * @param event The motion event to be dispatched. 8204 * @return True if the event was handled by the view, false otherwise. 8205 */ 8206 public boolean dispatchTrackballEvent(MotionEvent event) { 8207 if (mInputEventConsistencyVerifier != null) { 8208 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 8209 } 8210 8211 return onTrackballEvent(event); 8212 } 8213 8214 /** 8215 * Dispatch a generic motion event. 8216 * <p> 8217 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 8218 * are delivered to the view under the pointer. All other generic motion events are 8219 * delivered to the focused view. Hover events are handled specially and are delivered 8220 * to {@link #onHoverEvent(MotionEvent)}. 8221 * </p> 8222 * 8223 * @param event The motion event to be dispatched. 8224 * @return True if the event was handled by the view, false otherwise. 8225 */ 8226 public boolean dispatchGenericMotionEvent(MotionEvent event) { 8227 if (mInputEventConsistencyVerifier != null) { 8228 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 8229 } 8230 8231 final int source = event.getSource(); 8232 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 8233 final int action = event.getAction(); 8234 if (action == MotionEvent.ACTION_HOVER_ENTER 8235 || action == MotionEvent.ACTION_HOVER_MOVE 8236 || action == MotionEvent.ACTION_HOVER_EXIT) { 8237 if (dispatchHoverEvent(event)) { 8238 return true; 8239 } 8240 } else if (dispatchGenericPointerEvent(event)) { 8241 return true; 8242 } 8243 } else if (dispatchGenericFocusedEvent(event)) { 8244 return true; 8245 } 8246 8247 if (dispatchGenericMotionEventInternal(event)) { 8248 return true; 8249 } 8250 8251 if (mInputEventConsistencyVerifier != null) { 8252 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8253 } 8254 return false; 8255 } 8256 8257 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 8258 //noinspection SimplifiableIfStatement 8259 ListenerInfo li = mListenerInfo; 8260 if (li != null && li.mOnGenericMotionListener != null 8261 && (mViewFlags & ENABLED_MASK) == ENABLED 8262 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 8263 return true; 8264 } 8265 8266 if (onGenericMotionEvent(event)) { 8267 return true; 8268 } 8269 8270 if (mInputEventConsistencyVerifier != null) { 8271 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8272 } 8273 return false; 8274 } 8275 8276 /** 8277 * Dispatch a hover event. 8278 * <p> 8279 * Do not call this method directly. 8280 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8281 * </p> 8282 * 8283 * @param event The motion event to be dispatched. 8284 * @return True if the event was handled by the view, false otherwise. 8285 */ 8286 protected boolean dispatchHoverEvent(MotionEvent event) { 8287 ListenerInfo li = mListenerInfo; 8288 //noinspection SimplifiableIfStatement 8289 if (li != null && li.mOnHoverListener != null 8290 && (mViewFlags & ENABLED_MASK) == ENABLED 8291 && li.mOnHoverListener.onHover(this, event)) { 8292 return true; 8293 } 8294 8295 return onHoverEvent(event); 8296 } 8297 8298 /** 8299 * Returns true if the view has a child to which it has recently sent 8300 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 8301 * it does not have a hovered child, then it must be the innermost hovered view. 8302 * @hide 8303 */ 8304 protected boolean hasHoveredChild() { 8305 return false; 8306 } 8307 8308 /** 8309 * Dispatch a generic motion event to the view under the first pointer. 8310 * <p> 8311 * Do not call this method directly. 8312 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8313 * </p> 8314 * 8315 * @param event The motion event to be dispatched. 8316 * @return True if the event was handled by the view, false otherwise. 8317 */ 8318 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 8319 return false; 8320 } 8321 8322 /** 8323 * Dispatch a generic motion event to the currently focused view. 8324 * <p> 8325 * Do not call this method directly. 8326 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8327 * </p> 8328 * 8329 * @param event The motion event to be dispatched. 8330 * @return True if the event was handled by the view, false otherwise. 8331 */ 8332 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 8333 return false; 8334 } 8335 8336 /** 8337 * Dispatch a pointer event. 8338 * <p> 8339 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 8340 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 8341 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 8342 * and should not be expected to handle other pointing device features. 8343 * </p> 8344 * 8345 * @param event The motion event to be dispatched. 8346 * @return True if the event was handled by the view, false otherwise. 8347 * @hide 8348 */ 8349 public final boolean dispatchPointerEvent(MotionEvent event) { 8350 if (event.isTouchEvent()) { 8351 return dispatchTouchEvent(event); 8352 } else { 8353 return dispatchGenericMotionEvent(event); 8354 } 8355 } 8356 8357 /** 8358 * Called when the window containing this view gains or loses window focus. 8359 * ViewGroups should override to route to their children. 8360 * 8361 * @param hasFocus True if the window containing this view now has focus, 8362 * false otherwise. 8363 */ 8364 public void dispatchWindowFocusChanged(boolean hasFocus) { 8365 onWindowFocusChanged(hasFocus); 8366 } 8367 8368 /** 8369 * Called when the window containing this view gains or loses focus. Note 8370 * that this is separate from view focus: to receive key events, both 8371 * your view and its window must have focus. If a window is displayed 8372 * on top of yours that takes input focus, then your own window will lose 8373 * focus but the view focus will remain unchanged. 8374 * 8375 * @param hasWindowFocus True if the window containing this view now has 8376 * focus, false otherwise. 8377 */ 8378 public void onWindowFocusChanged(boolean hasWindowFocus) { 8379 InputMethodManager imm = InputMethodManager.peekInstance(); 8380 if (!hasWindowFocus) { 8381 if (isPressed()) { 8382 setPressed(false); 8383 } 8384 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 8385 imm.focusOut(this); 8386 } 8387 removeLongPressCallback(); 8388 removeTapCallback(); 8389 onFocusLost(); 8390 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 8391 imm.focusIn(this); 8392 } 8393 refreshDrawableState(); 8394 } 8395 8396 /** 8397 * Returns true if this view is in a window that currently has window focus. 8398 * Note that this is not the same as the view itself having focus. 8399 * 8400 * @return True if this view is in a window that currently has window focus. 8401 */ 8402 public boolean hasWindowFocus() { 8403 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 8404 } 8405 8406 /** 8407 * Dispatch a view visibility change down the view hierarchy. 8408 * ViewGroups should override to route to their children. 8409 * @param changedView The view whose visibility changed. Could be 'this' or 8410 * an ancestor view. 8411 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 8412 * {@link #INVISIBLE} or {@link #GONE}. 8413 */ 8414 protected void dispatchVisibilityChanged(@NonNull View changedView, 8415 @Visibility int visibility) { 8416 onVisibilityChanged(changedView, visibility); 8417 } 8418 8419 /** 8420 * Called when the visibility of the view or an ancestor of the view is changed. 8421 * @param changedView The view whose visibility changed. Could be 'this' or 8422 * an ancestor view. 8423 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 8424 * {@link #INVISIBLE} or {@link #GONE}. 8425 */ 8426 protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) { 8427 if (visibility == VISIBLE) { 8428 if (mAttachInfo != null) { 8429 initialAwakenScrollBars(); 8430 } else { 8431 mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 8432 } 8433 } 8434 } 8435 8436 /** 8437 * Dispatch a hint about whether this view is displayed. For instance, when 8438 * a View moves out of the screen, it might receives a display hint indicating 8439 * the view is not displayed. Applications should not <em>rely</em> on this hint 8440 * as there is no guarantee that they will receive one. 8441 * 8442 * @param hint A hint about whether or not this view is displayed: 8443 * {@link #VISIBLE} or {@link #INVISIBLE}. 8444 */ 8445 public void dispatchDisplayHint(@Visibility int hint) { 8446 onDisplayHint(hint); 8447 } 8448 8449 /** 8450 * Gives this view a hint about whether is displayed or not. For instance, when 8451 * a View moves out of the screen, it might receives a display hint indicating 8452 * the view is not displayed. Applications should not <em>rely</em> on this hint 8453 * as there is no guarantee that they will receive one. 8454 * 8455 * @param hint A hint about whether or not this view is displayed: 8456 * {@link #VISIBLE} or {@link #INVISIBLE}. 8457 */ 8458 protected void onDisplayHint(@Visibility int hint) { 8459 } 8460 8461 /** 8462 * Dispatch a window visibility change down the view hierarchy. 8463 * ViewGroups should override to route to their children. 8464 * 8465 * @param visibility The new visibility of the window. 8466 * 8467 * @see #onWindowVisibilityChanged(int) 8468 */ 8469 public void dispatchWindowVisibilityChanged(@Visibility int visibility) { 8470 onWindowVisibilityChanged(visibility); 8471 } 8472 8473 /** 8474 * Called when the window containing has change its visibility 8475 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 8476 * that this tells you whether or not your window is being made visible 8477 * to the window manager; this does <em>not</em> tell you whether or not 8478 * your window is obscured by other windows on the screen, even if it 8479 * is itself visible. 8480 * 8481 * @param visibility The new visibility of the window. 8482 */ 8483 protected void onWindowVisibilityChanged(@Visibility int visibility) { 8484 if (visibility == VISIBLE) { 8485 initialAwakenScrollBars(); 8486 } 8487 } 8488 8489 /** 8490 * Returns the current visibility of the window this view is attached to 8491 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 8492 * 8493 * @return Returns the current visibility of the view's window. 8494 */ 8495 @Visibility 8496 public int getWindowVisibility() { 8497 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 8498 } 8499 8500 /** 8501 * Retrieve the overall visible display size in which the window this view is 8502 * attached to has been positioned in. This takes into account screen 8503 * decorations above the window, for both cases where the window itself 8504 * is being position inside of them or the window is being placed under 8505 * then and covered insets are used for the window to position its content 8506 * inside. In effect, this tells you the available area where content can 8507 * be placed and remain visible to users. 8508 * 8509 * <p>This function requires an IPC back to the window manager to retrieve 8510 * the requested information, so should not be used in performance critical 8511 * code like drawing. 8512 * 8513 * @param outRect Filled in with the visible display frame. If the view 8514 * is not attached to a window, this is simply the raw display size. 8515 */ 8516 public void getWindowVisibleDisplayFrame(Rect outRect) { 8517 if (mAttachInfo != null) { 8518 try { 8519 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 8520 } catch (RemoteException e) { 8521 return; 8522 } 8523 // XXX This is really broken, and probably all needs to be done 8524 // in the window manager, and we need to know more about whether 8525 // we want the area behind or in front of the IME. 8526 final Rect insets = mAttachInfo.mVisibleInsets; 8527 outRect.left += insets.left; 8528 outRect.top += insets.top; 8529 outRect.right -= insets.right; 8530 outRect.bottom -= insets.bottom; 8531 return; 8532 } 8533 // The view is not attached to a display so we don't have a context. 8534 // Make a best guess about the display size. 8535 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 8536 d.getRectSize(outRect); 8537 } 8538 8539 /** 8540 * Dispatch a notification about a resource configuration change down 8541 * the view hierarchy. 8542 * ViewGroups should override to route to their children. 8543 * 8544 * @param newConfig The new resource configuration. 8545 * 8546 * @see #onConfigurationChanged(android.content.res.Configuration) 8547 */ 8548 public void dispatchConfigurationChanged(Configuration newConfig) { 8549 onConfigurationChanged(newConfig); 8550 } 8551 8552 /** 8553 * Called when the current configuration of the resources being used 8554 * by the application have changed. You can use this to decide when 8555 * to reload resources that can changed based on orientation and other 8556 * configuration characterstics. You only need to use this if you are 8557 * not relying on the normal {@link android.app.Activity} mechanism of 8558 * recreating the activity instance upon a configuration change. 8559 * 8560 * @param newConfig The new resource configuration. 8561 */ 8562 protected void onConfigurationChanged(Configuration newConfig) { 8563 } 8564 8565 /** 8566 * Private function to aggregate all per-view attributes in to the view 8567 * root. 8568 */ 8569 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8570 performCollectViewAttributes(attachInfo, visibility); 8571 } 8572 8573 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8574 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 8575 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 8576 attachInfo.mKeepScreenOn = true; 8577 } 8578 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 8579 ListenerInfo li = mListenerInfo; 8580 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 8581 attachInfo.mHasSystemUiListeners = true; 8582 } 8583 } 8584 } 8585 8586 void needGlobalAttributesUpdate(boolean force) { 8587 final AttachInfo ai = mAttachInfo; 8588 if (ai != null && !ai.mRecomputeGlobalAttributes) { 8589 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 8590 || ai.mHasSystemUiListeners) { 8591 ai.mRecomputeGlobalAttributes = true; 8592 } 8593 } 8594 } 8595 8596 /** 8597 * Returns whether the device is currently in touch mode. Touch mode is entered 8598 * once the user begins interacting with the device by touch, and affects various 8599 * things like whether focus is always visible to the user. 8600 * 8601 * @return Whether the device is in touch mode. 8602 */ 8603 @ViewDebug.ExportedProperty 8604 public boolean isInTouchMode() { 8605 if (mAttachInfo != null) { 8606 return mAttachInfo.mInTouchMode; 8607 } else { 8608 return ViewRootImpl.isInTouchMode(); 8609 } 8610 } 8611 8612 /** 8613 * Returns the context the view is running in, through which it can 8614 * access the current theme, resources, etc. 8615 * 8616 * @return The view's Context. 8617 */ 8618 @ViewDebug.CapturedViewProperty 8619 public final Context getContext() { 8620 return mContext; 8621 } 8622 8623 /** 8624 * Handle a key event before it is processed by any input method 8625 * associated with the view hierarchy. This can be used to intercept 8626 * key events in special situations before the IME consumes them; a 8627 * typical example would be handling the BACK key to update the application's 8628 * UI instead of allowing the IME to see it and close itself. 8629 * 8630 * @param keyCode The value in event.getKeyCode(). 8631 * @param event Description of the key event. 8632 * @return If you handled the event, return true. If you want to allow the 8633 * event to be handled by the next receiver, return false. 8634 */ 8635 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 8636 return false; 8637 } 8638 8639 /** 8640 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 8641 * KeyEvent.Callback.onKeyDown()}: perform press of the view 8642 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 8643 * is released, if the view is enabled and clickable. 8644 * 8645 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8646 * although some may elect to do so in some situations. Do not rely on this to 8647 * catch software key presses. 8648 * 8649 * @param keyCode A key code that represents the button pressed, from 8650 * {@link android.view.KeyEvent}. 8651 * @param event The KeyEvent object that defines the button action. 8652 */ 8653 public boolean onKeyDown(int keyCode, KeyEvent event) { 8654 boolean result = false; 8655 8656 if (KeyEvent.isConfirmKey(keyCode)) { 8657 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8658 return true; 8659 } 8660 // Long clickable items don't necessarily have to be clickable 8661 if (((mViewFlags & CLICKABLE) == CLICKABLE || 8662 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 8663 (event.getRepeatCount() == 0)) { 8664 setPressed(true); 8665 checkForLongClick(0); 8666 return true; 8667 } 8668 } 8669 return result; 8670 } 8671 8672 /** 8673 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 8674 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 8675 * the event). 8676 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8677 * although some may elect to do so in some situations. Do not rely on this to 8678 * catch software key presses. 8679 */ 8680 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 8681 return false; 8682 } 8683 8684 /** 8685 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 8686 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 8687 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 8688 * {@link KeyEvent#KEYCODE_ENTER} is released. 8689 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8690 * although some may elect to do so in some situations. Do not rely on this to 8691 * catch software key presses. 8692 * 8693 * @param keyCode A key code that represents the button pressed, from 8694 * {@link android.view.KeyEvent}. 8695 * @param event The KeyEvent object that defines the button action. 8696 */ 8697 public boolean onKeyUp(int keyCode, KeyEvent event) { 8698 if (KeyEvent.isConfirmKey(keyCode)) { 8699 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8700 return true; 8701 } 8702 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 8703 setPressed(false); 8704 8705 if (!mHasPerformedLongPress) { 8706 // This is a tap, so remove the longpress check 8707 removeLongPressCallback(); 8708 return performClick(); 8709 } 8710 } 8711 } 8712 return false; 8713 } 8714 8715 /** 8716 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 8717 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 8718 * the event). 8719 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8720 * although some may elect to do so in some situations. Do not rely on this to 8721 * catch software key presses. 8722 * 8723 * @param keyCode A key code that represents the button pressed, from 8724 * {@link android.view.KeyEvent}. 8725 * @param repeatCount The number of times the action was made. 8726 * @param event The KeyEvent object that defines the button action. 8727 */ 8728 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 8729 return false; 8730 } 8731 8732 /** 8733 * Called on the focused view when a key shortcut event is not handled. 8734 * Override this method to implement local key shortcuts for the View. 8735 * Key shortcuts can also be implemented by setting the 8736 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 8737 * 8738 * @param keyCode The value in event.getKeyCode(). 8739 * @param event Description of the key event. 8740 * @return If you handled the event, return true. If you want to allow the 8741 * event to be handled by the next receiver, return false. 8742 */ 8743 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 8744 return false; 8745 } 8746 8747 /** 8748 * Check whether the called view is a text editor, in which case it 8749 * would make sense to automatically display a soft input window for 8750 * it. Subclasses should override this if they implement 8751 * {@link #onCreateInputConnection(EditorInfo)} to return true if 8752 * a call on that method would return a non-null InputConnection, and 8753 * they are really a first-class editor that the user would normally 8754 * start typing on when the go into a window containing your view. 8755 * 8756 * <p>The default implementation always returns false. This does 8757 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 8758 * will not be called or the user can not otherwise perform edits on your 8759 * view; it is just a hint to the system that this is not the primary 8760 * purpose of this view. 8761 * 8762 * @return Returns true if this view is a text editor, else false. 8763 */ 8764 public boolean onCheckIsTextEditor() { 8765 return false; 8766 } 8767 8768 /** 8769 * Create a new InputConnection for an InputMethod to interact 8770 * with the view. The default implementation returns null, since it doesn't 8771 * support input methods. You can override this to implement such support. 8772 * This is only needed for views that take focus and text input. 8773 * 8774 * <p>When implementing this, you probably also want to implement 8775 * {@link #onCheckIsTextEditor()} to indicate you will return a 8776 * non-null InputConnection.</p> 8777 * 8778 * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo} 8779 * object correctly and in its entirety, so that the connected IME can rely 8780 * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart} 8781 * and {@link android.view.inputmethod.EditorInfo#initialSelEnd} members 8782 * must be filled in with the correct cursor position for IMEs to work correctly 8783 * with your application.</p> 8784 * 8785 * @param outAttrs Fill in with attribute information about the connection. 8786 */ 8787 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 8788 return null; 8789 } 8790 8791 /** 8792 * Called by the {@link android.view.inputmethod.InputMethodManager} 8793 * when a view who is not the current 8794 * input connection target is trying to make a call on the manager. The 8795 * default implementation returns false; you can override this to return 8796 * true for certain views if you are performing InputConnection proxying 8797 * to them. 8798 * @param view The View that is making the InputMethodManager call. 8799 * @return Return true to allow the call, false to reject. 8800 */ 8801 public boolean checkInputConnectionProxy(View view) { 8802 return false; 8803 } 8804 8805 /** 8806 * Show the context menu for this view. It is not safe to hold on to the 8807 * menu after returning from this method. 8808 * 8809 * You should normally not overload this method. Overload 8810 * {@link #onCreateContextMenu(ContextMenu)} or define an 8811 * {@link OnCreateContextMenuListener} to add items to the context menu. 8812 * 8813 * @param menu The context menu to populate 8814 */ 8815 public void createContextMenu(ContextMenu menu) { 8816 ContextMenuInfo menuInfo = getContextMenuInfo(); 8817 8818 // Sets the current menu info so all items added to menu will have 8819 // my extra info set. 8820 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 8821 8822 onCreateContextMenu(menu); 8823 ListenerInfo li = mListenerInfo; 8824 if (li != null && li.mOnCreateContextMenuListener != null) { 8825 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 8826 } 8827 8828 // Clear the extra information so subsequent items that aren't mine don't 8829 // have my extra info. 8830 ((MenuBuilder)menu).setCurrentMenuInfo(null); 8831 8832 if (mParent != null) { 8833 mParent.createContextMenu(menu); 8834 } 8835 } 8836 8837 /** 8838 * Views should implement this if they have extra information to associate 8839 * with the context menu. The return result is supplied as a parameter to 8840 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 8841 * callback. 8842 * 8843 * @return Extra information about the item for which the context menu 8844 * should be shown. This information will vary across different 8845 * subclasses of View. 8846 */ 8847 protected ContextMenuInfo getContextMenuInfo() { 8848 return null; 8849 } 8850 8851 /** 8852 * Views should implement this if the view itself is going to add items to 8853 * the context menu. 8854 * 8855 * @param menu the context menu to populate 8856 */ 8857 protected void onCreateContextMenu(ContextMenu menu) { 8858 } 8859 8860 /** 8861 * Implement this method to handle trackball motion events. The 8862 * <em>relative</em> movement of the trackball since the last event 8863 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 8864 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 8865 * that a movement of 1 corresponds to the user pressing one DPAD key (so 8866 * they will often be fractional values, representing the more fine-grained 8867 * movement information available from a trackball). 8868 * 8869 * @param event The motion event. 8870 * @return True if the event was handled, false otherwise. 8871 */ 8872 public boolean onTrackballEvent(MotionEvent event) { 8873 return false; 8874 } 8875 8876 /** 8877 * Implement this method to handle generic motion events. 8878 * <p> 8879 * Generic motion events describe joystick movements, mouse hovers, track pad 8880 * touches, scroll wheel movements and other input events. The 8881 * {@link MotionEvent#getSource() source} of the motion event specifies 8882 * the class of input that was received. Implementations of this method 8883 * must examine the bits in the source before processing the event. 8884 * The following code example shows how this is done. 8885 * </p><p> 8886 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 8887 * are delivered to the view under the pointer. All other generic motion events are 8888 * delivered to the focused view. 8889 * </p> 8890 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 8891 * if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) { 8892 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 8893 * // process the joystick movement... 8894 * return true; 8895 * } 8896 * } 8897 * if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { 8898 * switch (event.getAction()) { 8899 * case MotionEvent.ACTION_HOVER_MOVE: 8900 * // process the mouse hover movement... 8901 * return true; 8902 * case MotionEvent.ACTION_SCROLL: 8903 * // process the scroll wheel movement... 8904 * return true; 8905 * } 8906 * } 8907 * return super.onGenericMotionEvent(event); 8908 * }</pre> 8909 * 8910 * @param event The generic motion event being processed. 8911 * @return True if the event was handled, false otherwise. 8912 */ 8913 public boolean onGenericMotionEvent(MotionEvent event) { 8914 return false; 8915 } 8916 8917 /** 8918 * Implement this method to handle hover events. 8919 * <p> 8920 * This method is called whenever a pointer is hovering into, over, or out of the 8921 * bounds of a view and the view is not currently being touched. 8922 * Hover events are represented as pointer events with action 8923 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 8924 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 8925 * </p> 8926 * <ul> 8927 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 8928 * when the pointer enters the bounds of the view.</li> 8929 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 8930 * when the pointer has already entered the bounds of the view and has moved.</li> 8931 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 8932 * when the pointer has exited the bounds of the view or when the pointer is 8933 * about to go down due to a button click, tap, or similar user action that 8934 * causes the view to be touched.</li> 8935 * </ul> 8936 * <p> 8937 * The view should implement this method to return true to indicate that it is 8938 * handling the hover event, such as by changing its drawable state. 8939 * </p><p> 8940 * The default implementation calls {@link #setHovered} to update the hovered state 8941 * of the view when a hover enter or hover exit event is received, if the view 8942 * is enabled and is clickable. The default implementation also sends hover 8943 * accessibility events. 8944 * </p> 8945 * 8946 * @param event The motion event that describes the hover. 8947 * @return True if the view handled the hover event. 8948 * 8949 * @see #isHovered 8950 * @see #setHovered 8951 * @see #onHoverChanged 8952 */ 8953 public boolean onHoverEvent(MotionEvent event) { 8954 // The root view may receive hover (or touch) events that are outside the bounds of 8955 // the window. This code ensures that we only send accessibility events for 8956 // hovers that are actually within the bounds of the root view. 8957 final int action = event.getActionMasked(); 8958 if (!mSendingHoverAccessibilityEvents) { 8959 if ((action == MotionEvent.ACTION_HOVER_ENTER 8960 || action == MotionEvent.ACTION_HOVER_MOVE) 8961 && !hasHoveredChild() 8962 && pointInView(event.getX(), event.getY())) { 8963 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 8964 mSendingHoverAccessibilityEvents = true; 8965 } 8966 } else { 8967 if (action == MotionEvent.ACTION_HOVER_EXIT 8968 || (action == MotionEvent.ACTION_MOVE 8969 && !pointInView(event.getX(), event.getY()))) { 8970 mSendingHoverAccessibilityEvents = false; 8971 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 8972 } 8973 } 8974 8975 if (isHoverable()) { 8976 switch (action) { 8977 case MotionEvent.ACTION_HOVER_ENTER: 8978 setHovered(true); 8979 break; 8980 case MotionEvent.ACTION_HOVER_EXIT: 8981 setHovered(false); 8982 break; 8983 } 8984 8985 // Dispatch the event to onGenericMotionEvent before returning true. 8986 // This is to provide compatibility with existing applications that 8987 // handled HOVER_MOVE events in onGenericMotionEvent and that would 8988 // break because of the new default handling for hoverable views 8989 // in onHoverEvent. 8990 // Note that onGenericMotionEvent will be called by default when 8991 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 8992 dispatchGenericMotionEventInternal(event); 8993 // The event was already handled by calling setHovered(), so always 8994 // return true. 8995 return true; 8996 } 8997 8998 return false; 8999 } 9000 9001 /** 9002 * Returns true if the view should handle {@link #onHoverEvent} 9003 * by calling {@link #setHovered} to change its hovered state. 9004 * 9005 * @return True if the view is hoverable. 9006 */ 9007 private boolean isHoverable() { 9008 final int viewFlags = mViewFlags; 9009 if ((viewFlags & ENABLED_MASK) == DISABLED) { 9010 return false; 9011 } 9012 9013 return (viewFlags & CLICKABLE) == CLICKABLE 9014 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 9015 } 9016 9017 /** 9018 * Returns true if the view is currently hovered. 9019 * 9020 * @return True if the view is currently hovered. 9021 * 9022 * @see #setHovered 9023 * @see #onHoverChanged 9024 */ 9025 @ViewDebug.ExportedProperty 9026 public boolean isHovered() { 9027 return (mPrivateFlags & PFLAG_HOVERED) != 0; 9028 } 9029 9030 /** 9031 * Sets whether the view is currently hovered. 9032 * <p> 9033 * Calling this method also changes the drawable state of the view. This 9034 * enables the view to react to hover by using different drawable resources 9035 * to change its appearance. 9036 * </p><p> 9037 * The {@link #onHoverChanged} method is called when the hovered state changes. 9038 * </p> 9039 * 9040 * @param hovered True if the view is hovered. 9041 * 9042 * @see #isHovered 9043 * @see #onHoverChanged 9044 */ 9045 public void setHovered(boolean hovered) { 9046 if (hovered) { 9047 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 9048 mPrivateFlags |= PFLAG_HOVERED; 9049 refreshDrawableState(); 9050 onHoverChanged(true); 9051 } 9052 } else { 9053 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 9054 mPrivateFlags &= ~PFLAG_HOVERED; 9055 refreshDrawableState(); 9056 onHoverChanged(false); 9057 } 9058 } 9059 } 9060 9061 /** 9062 * Implement this method to handle hover state changes. 9063 * <p> 9064 * This method is called whenever the hover state changes as a result of a 9065 * call to {@link #setHovered}. 9066 * </p> 9067 * 9068 * @param hovered The current hover state, as returned by {@link #isHovered}. 9069 * 9070 * @see #isHovered 9071 * @see #setHovered 9072 */ 9073 public void onHoverChanged(boolean hovered) { 9074 } 9075 9076 /** 9077 * Implement this method to handle touch screen motion events. 9078 * <p> 9079 * If this method is used to detect click actions, it is recommended that 9080 * the actions be performed by implementing and calling 9081 * {@link #performClick()}. This will ensure consistent system behavior, 9082 * including: 9083 * <ul> 9084 * <li>obeying click sound preferences 9085 * <li>dispatching OnClickListener calls 9086 * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when 9087 * accessibility features are enabled 9088 * </ul> 9089 * 9090 * @param event The motion event. 9091 * @return True if the event was handled, false otherwise. 9092 */ 9093 public boolean onTouchEvent(MotionEvent event) { 9094 final float x = event.getX(); 9095 final float y = event.getY(); 9096 final int viewFlags = mViewFlags; 9097 9098 if ((viewFlags & ENABLED_MASK) == DISABLED) { 9099 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 9100 setPressed(false); 9101 } 9102 // A disabled view that is clickable still consumes the touch 9103 // events, it just doesn't respond to them. 9104 return (((viewFlags & CLICKABLE) == CLICKABLE || 9105 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 9106 } 9107 9108 if (mTouchDelegate != null) { 9109 if (mTouchDelegate.onTouchEvent(event)) { 9110 return true; 9111 } 9112 } 9113 9114 if (((viewFlags & CLICKABLE) == CLICKABLE || 9115 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 9116 switch (event.getAction()) { 9117 case MotionEvent.ACTION_UP: 9118 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 9119 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 9120 // take focus if we don't have it already and we should in 9121 // touch mode. 9122 boolean focusTaken = false; 9123 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 9124 focusTaken = requestFocus(); 9125 } 9126 9127 if (prepressed) { 9128 // The button is being released before we actually 9129 // showed it as pressed. Make it show the pressed 9130 // state now (before scheduling the click) to ensure 9131 // the user sees it. 9132 setPressed(true, x, y); 9133 } 9134 9135 if (!mHasPerformedLongPress) { 9136 // This is a tap, so remove the longpress check 9137 removeLongPressCallback(); 9138 9139 // Only perform take click actions if we were in the pressed state 9140 if (!focusTaken) { 9141 // Use a Runnable and post this rather than calling 9142 // performClick directly. This lets other visual state 9143 // of the view update before click actions start. 9144 if (mPerformClick == null) { 9145 mPerformClick = new PerformClick(); 9146 } 9147 if (!post(mPerformClick)) { 9148 performClick(); 9149 } 9150 } 9151 } 9152 9153 if (mUnsetPressedState == null) { 9154 mUnsetPressedState = new UnsetPressedState(); 9155 } 9156 9157 if (prepressed) { 9158 postDelayed(mUnsetPressedState, 9159 ViewConfiguration.getPressedStateDuration()); 9160 } else if (!post(mUnsetPressedState)) { 9161 // If the post failed, unpress right now 9162 mUnsetPressedState.run(); 9163 } 9164 9165 removeTapCallback(); 9166 } 9167 break; 9168 9169 case MotionEvent.ACTION_DOWN: 9170 mHasPerformedLongPress = false; 9171 9172 if (performButtonActionOnTouchDown(event)) { 9173 break; 9174 } 9175 9176 // Walk up the hierarchy to determine if we're inside a scrolling container. 9177 boolean isInScrollingContainer = isInScrollingContainer(); 9178 9179 // For views inside a scrolling container, delay the pressed feedback for 9180 // a short period in case this is a scroll. 9181 if (isInScrollingContainer) { 9182 mPrivateFlags |= PFLAG_PREPRESSED; 9183 if (mPendingCheckForTap == null) { 9184 mPendingCheckForTap = new CheckForTap(); 9185 } 9186 mPendingCheckForTap.x = event.getX(); 9187 mPendingCheckForTap.y = event.getY(); 9188 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 9189 } else { 9190 // Not inside a scrolling container, so show the feedback right away 9191 setPressed(true, x, y); 9192 checkForLongClick(0); 9193 } 9194 break; 9195 9196 case MotionEvent.ACTION_CANCEL: 9197 setPressed(false); 9198 removeTapCallback(); 9199 removeLongPressCallback(); 9200 break; 9201 9202 case MotionEvent.ACTION_MOVE: 9203 drawableHotspotChanged(x, y); 9204 9205 // Be lenient about moving outside of buttons 9206 if (!pointInView(x, y, mTouchSlop)) { 9207 // Outside button 9208 removeTapCallback(); 9209 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 9210 // Remove any future long press/tap checks 9211 removeLongPressCallback(); 9212 9213 setPressed(false); 9214 } 9215 } 9216 break; 9217 } 9218 9219 return true; 9220 } 9221 9222 return false; 9223 } 9224 9225 /** 9226 * @hide 9227 */ 9228 public boolean isInScrollingContainer() { 9229 ViewParent p = getParent(); 9230 while (p != null && p instanceof ViewGroup) { 9231 if (((ViewGroup) p).shouldDelayChildPressedState()) { 9232 return true; 9233 } 9234 p = p.getParent(); 9235 } 9236 return false; 9237 } 9238 9239 /** 9240 * Remove the longpress detection timer. 9241 */ 9242 private void removeLongPressCallback() { 9243 if (mPendingCheckForLongPress != null) { 9244 removeCallbacks(mPendingCheckForLongPress); 9245 } 9246 } 9247 9248 /** 9249 * Remove the pending click action 9250 */ 9251 private void removePerformClickCallback() { 9252 if (mPerformClick != null) { 9253 removeCallbacks(mPerformClick); 9254 } 9255 } 9256 9257 /** 9258 * Remove the prepress detection timer. 9259 */ 9260 private void removeUnsetPressCallback() { 9261 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 9262 setPressed(false); 9263 removeCallbacks(mUnsetPressedState); 9264 } 9265 } 9266 9267 /** 9268 * Remove the tap detection timer. 9269 */ 9270 private void removeTapCallback() { 9271 if (mPendingCheckForTap != null) { 9272 mPrivateFlags &= ~PFLAG_PREPRESSED; 9273 removeCallbacks(mPendingCheckForTap); 9274 } 9275 } 9276 9277 /** 9278 * Cancels a pending long press. Your subclass can use this if you 9279 * want the context menu to come up if the user presses and holds 9280 * at the same place, but you don't want it to come up if they press 9281 * and then move around enough to cause scrolling. 9282 */ 9283 public void cancelLongPress() { 9284 removeLongPressCallback(); 9285 9286 /* 9287 * The prepressed state handled by the tap callback is a display 9288 * construct, but the tap callback will post a long press callback 9289 * less its own timeout. Remove it here. 9290 */ 9291 removeTapCallback(); 9292 } 9293 9294 /** 9295 * Remove the pending callback for sending a 9296 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 9297 */ 9298 private void removeSendViewScrolledAccessibilityEventCallback() { 9299 if (mSendViewScrolledAccessibilityEvent != null) { 9300 removeCallbacks(mSendViewScrolledAccessibilityEvent); 9301 mSendViewScrolledAccessibilityEvent.mIsPending = false; 9302 } 9303 } 9304 9305 /** 9306 * Sets the TouchDelegate for this View. 9307 */ 9308 public void setTouchDelegate(TouchDelegate delegate) { 9309 mTouchDelegate = delegate; 9310 } 9311 9312 /** 9313 * Gets the TouchDelegate for this View. 9314 */ 9315 public TouchDelegate getTouchDelegate() { 9316 return mTouchDelegate; 9317 } 9318 9319 /** 9320 * Request unbuffered dispatch of the given stream of MotionEvents to this View. 9321 * 9322 * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input 9323 * system not batch {@link MotionEvent}s but instead deliver them as soon as they're 9324 * available. This method should only be called for touch events. 9325 * 9326 * <p class="note">This api is not intended for most applications. Buffered dispatch 9327 * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent 9328 * streams will not improve your input latency. Side effects include: increased latency, 9329 * jittery scrolls and inability to take advantage of system resampling. Talk to your input 9330 * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for 9331 * you.</p> 9332 */ 9333 public final void requestUnbufferedDispatch(MotionEvent event) { 9334 final int action = event.getAction(); 9335 if (mAttachInfo == null 9336 || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE 9337 || !event.isTouchEvent()) { 9338 return; 9339 } 9340 mAttachInfo.mUnbufferedDispatchRequested = true; 9341 } 9342 9343 /** 9344 * Set flags controlling behavior of this view. 9345 * 9346 * @param flags Constant indicating the value which should be set 9347 * @param mask Constant indicating the bit range that should be changed 9348 */ 9349 void setFlags(int flags, int mask) { 9350 final boolean accessibilityEnabled = 9351 AccessibilityManager.getInstance(mContext).isEnabled(); 9352 final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility(); 9353 9354 int old = mViewFlags; 9355 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 9356 9357 int changed = mViewFlags ^ old; 9358 if (changed == 0) { 9359 return; 9360 } 9361 int privateFlags = mPrivateFlags; 9362 9363 /* Check if the FOCUSABLE bit has changed */ 9364 if (((changed & FOCUSABLE_MASK) != 0) && 9365 ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) { 9366 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 9367 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 9368 /* Give up focus if we are no longer focusable */ 9369 clearFocus(); 9370 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 9371 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 9372 /* 9373 * Tell the view system that we are now available to take focus 9374 * if no one else already has it. 9375 */ 9376 if (mParent != null) mParent.focusableViewAvailable(this); 9377 } 9378 } 9379 9380 final int newVisibility = flags & VISIBILITY_MASK; 9381 if (newVisibility == VISIBLE) { 9382 if ((changed & VISIBILITY_MASK) != 0) { 9383 /* 9384 * If this view is becoming visible, invalidate it in case it changed while 9385 * it was not visible. Marking it drawn ensures that the invalidation will 9386 * go through. 9387 */ 9388 mPrivateFlags |= PFLAG_DRAWN; 9389 invalidate(true); 9390 9391 needGlobalAttributesUpdate(true); 9392 9393 // a view becoming visible is worth notifying the parent 9394 // about in case nothing has focus. even if this specific view 9395 // isn't focusable, it may contain something that is, so let 9396 // the root view try to give this focus if nothing else does. 9397 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 9398 mParent.focusableViewAvailable(this); 9399 } 9400 } 9401 } 9402 9403 /* Check if the GONE bit has changed */ 9404 if ((changed & GONE) != 0) { 9405 needGlobalAttributesUpdate(false); 9406 requestLayout(); 9407 9408 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 9409 if (hasFocus()) clearFocus(); 9410 clearAccessibilityFocus(); 9411 destroyDrawingCache(); 9412 if (mParent instanceof View) { 9413 // GONE views noop invalidation, so invalidate the parent 9414 ((View) mParent).invalidate(true); 9415 } 9416 // Mark the view drawn to ensure that it gets invalidated properly the next 9417 // time it is visible and gets invalidated 9418 mPrivateFlags |= PFLAG_DRAWN; 9419 } 9420 if (mAttachInfo != null) { 9421 mAttachInfo.mViewVisibilityChanged = true; 9422 } 9423 } 9424 9425 /* Check if the VISIBLE bit has changed */ 9426 if ((changed & INVISIBLE) != 0) { 9427 needGlobalAttributesUpdate(false); 9428 /* 9429 * If this view is becoming invisible, set the DRAWN flag so that 9430 * the next invalidate() will not be skipped. 9431 */ 9432 mPrivateFlags |= PFLAG_DRAWN; 9433 9434 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) { 9435 // root view becoming invisible shouldn't clear focus and accessibility focus 9436 if (getRootView() != this) { 9437 if (hasFocus()) clearFocus(); 9438 clearAccessibilityFocus(); 9439 } 9440 } 9441 if (mAttachInfo != null) { 9442 mAttachInfo.mViewVisibilityChanged = true; 9443 } 9444 } 9445 9446 if ((changed & VISIBILITY_MASK) != 0) { 9447 // If the view is invisible, cleanup its display list to free up resources 9448 if (newVisibility != VISIBLE && mAttachInfo != null) { 9449 cleanupDraw(); 9450 } 9451 9452 if (mParent instanceof ViewGroup) { 9453 ((ViewGroup) mParent).onChildVisibilityChanged(this, 9454 (changed & VISIBILITY_MASK), newVisibility); 9455 ((View) mParent).invalidate(true); 9456 } else if (mParent != null) { 9457 mParent.invalidateChild(this, null); 9458 } 9459 dispatchVisibilityChanged(this, newVisibility); 9460 9461 notifySubtreeAccessibilityStateChangedIfNeeded(); 9462 } 9463 9464 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 9465 destroyDrawingCache(); 9466 } 9467 9468 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 9469 destroyDrawingCache(); 9470 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9471 invalidateParentCaches(); 9472 } 9473 9474 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 9475 destroyDrawingCache(); 9476 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9477 } 9478 9479 if ((changed & DRAW_MASK) != 0) { 9480 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 9481 if (mBackground != null) { 9482 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9483 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 9484 } else { 9485 mPrivateFlags |= PFLAG_SKIP_DRAW; 9486 } 9487 } else { 9488 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9489 } 9490 requestLayout(); 9491 invalidate(true); 9492 } 9493 9494 if ((changed & KEEP_SCREEN_ON) != 0) { 9495 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 9496 mParent.recomputeViewAttributes(this); 9497 } 9498 } 9499 9500 if (accessibilityEnabled) { 9501 if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0 9502 || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) { 9503 if (oldIncludeForAccessibility != includeForAccessibility()) { 9504 notifySubtreeAccessibilityStateChangedIfNeeded(); 9505 } else { 9506 notifyViewAccessibilityStateChangedIfNeeded( 9507 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9508 } 9509 } else if ((changed & ENABLED_MASK) != 0) { 9510 notifyViewAccessibilityStateChangedIfNeeded( 9511 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9512 } 9513 } 9514 } 9515 9516 /** 9517 * Change the view's z order in the tree, so it's on top of other sibling 9518 * views. This ordering change may affect layout, if the parent container 9519 * uses an order-dependent layout scheme (e.g., LinearLayout). Prior 9520 * to {@link android.os.Build.VERSION_CODES#KITKAT} this 9521 * method should be followed by calls to {@link #requestLayout()} and 9522 * {@link View#invalidate()} on the view's parent to force the parent to redraw 9523 * with the new child ordering. 9524 * 9525 * @see ViewGroup#bringChildToFront(View) 9526 */ 9527 public void bringToFront() { 9528 if (mParent != null) { 9529 mParent.bringChildToFront(this); 9530 } 9531 } 9532 9533 /** 9534 * This is called in response to an internal scroll in this view (i.e., the 9535 * view scrolled its own contents). This is typically as a result of 9536 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 9537 * called. 9538 * 9539 * @param l Current horizontal scroll origin. 9540 * @param t Current vertical scroll origin. 9541 * @param oldl Previous horizontal scroll origin. 9542 * @param oldt Previous vertical scroll origin. 9543 */ 9544 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 9545 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 9546 postSendViewScrolledAccessibilityEventCallback(); 9547 } 9548 9549 mBackgroundSizeChanged = true; 9550 9551 final AttachInfo ai = mAttachInfo; 9552 if (ai != null) { 9553 ai.mViewScrollChanged = true; 9554 } 9555 } 9556 9557 /** 9558 * Interface definition for a callback to be invoked when the layout bounds of a view 9559 * changes due to layout processing. 9560 */ 9561 public interface OnLayoutChangeListener { 9562 /** 9563 * Called when the layout bounds of a view changes due to layout processing. 9564 * 9565 * @param v The view whose bounds have changed. 9566 * @param left The new value of the view's left property. 9567 * @param top The new value of the view's top property. 9568 * @param right The new value of the view's right property. 9569 * @param bottom The new value of the view's bottom property. 9570 * @param oldLeft The previous value of the view's left property. 9571 * @param oldTop The previous value of the view's top property. 9572 * @param oldRight The previous value of the view's right property. 9573 * @param oldBottom The previous value of the view's bottom property. 9574 */ 9575 void onLayoutChange(View v, int left, int top, int right, int bottom, 9576 int oldLeft, int oldTop, int oldRight, int oldBottom); 9577 } 9578 9579 /** 9580 * This is called during layout when the size of this view has changed. If 9581 * you were just added to the view hierarchy, you're called with the old 9582 * values of 0. 9583 * 9584 * @param w Current width of this view. 9585 * @param h Current height of this view. 9586 * @param oldw Old width of this view. 9587 * @param oldh Old height of this view. 9588 */ 9589 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 9590 } 9591 9592 /** 9593 * Called by draw to draw the child views. This may be overridden 9594 * by derived classes to gain control just before its children are drawn 9595 * (but after its own view has been drawn). 9596 * @param canvas the canvas on which to draw the view 9597 */ 9598 protected void dispatchDraw(Canvas canvas) { 9599 9600 } 9601 9602 /** 9603 * Gets the parent of this view. Note that the parent is a 9604 * ViewParent and not necessarily a View. 9605 * 9606 * @return Parent of this view. 9607 */ 9608 public final ViewParent getParent() { 9609 return mParent; 9610 } 9611 9612 /** 9613 * Set the horizontal scrolled position of your view. This will cause a call to 9614 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9615 * invalidated. 9616 * @param value the x position to scroll to 9617 */ 9618 public void setScrollX(int value) { 9619 scrollTo(value, mScrollY); 9620 } 9621 9622 /** 9623 * Set the vertical scrolled position of your view. This will cause a call to 9624 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9625 * invalidated. 9626 * @param value the y position to scroll to 9627 */ 9628 public void setScrollY(int value) { 9629 scrollTo(mScrollX, value); 9630 } 9631 9632 /** 9633 * Return the scrolled left position of this view. This is the left edge of 9634 * the displayed part of your view. You do not need to draw any pixels 9635 * farther left, since those are outside of the frame of your view on 9636 * screen. 9637 * 9638 * @return The left edge of the displayed part of your view, in pixels. 9639 */ 9640 public final int getScrollX() { 9641 return mScrollX; 9642 } 9643 9644 /** 9645 * Return the scrolled top position of this view. This is the top edge of 9646 * the displayed part of your view. You do not need to draw any pixels above 9647 * it, since those are outside of the frame of your view on screen. 9648 * 9649 * @return The top edge of the displayed part of your view, in pixels. 9650 */ 9651 public final int getScrollY() { 9652 return mScrollY; 9653 } 9654 9655 /** 9656 * Return the width of the your view. 9657 * 9658 * @return The width of your view, in pixels. 9659 */ 9660 @ViewDebug.ExportedProperty(category = "layout") 9661 public final int getWidth() { 9662 return mRight - mLeft; 9663 } 9664 9665 /** 9666 * Return the height of your view. 9667 * 9668 * @return The height of your view, in pixels. 9669 */ 9670 @ViewDebug.ExportedProperty(category = "layout") 9671 public final int getHeight() { 9672 return mBottom - mTop; 9673 } 9674 9675 /** 9676 * Return the visible drawing bounds of your view. Fills in the output 9677 * rectangle with the values from getScrollX(), getScrollY(), 9678 * getWidth(), and getHeight(). These bounds do not account for any 9679 * transformation properties currently set on the view, such as 9680 * {@link #setScaleX(float)} or {@link #setRotation(float)}. 9681 * 9682 * @param outRect The (scrolled) drawing bounds of the view. 9683 */ 9684 public void getDrawingRect(Rect outRect) { 9685 outRect.left = mScrollX; 9686 outRect.top = mScrollY; 9687 outRect.right = mScrollX + (mRight - mLeft); 9688 outRect.bottom = mScrollY + (mBottom - mTop); 9689 } 9690 9691 /** 9692 * Like {@link #getMeasuredWidthAndState()}, but only returns the 9693 * raw width component (that is the result is masked by 9694 * {@link #MEASURED_SIZE_MASK}). 9695 * 9696 * @return The raw measured width of this view. 9697 */ 9698 public final int getMeasuredWidth() { 9699 return mMeasuredWidth & MEASURED_SIZE_MASK; 9700 } 9701 9702 /** 9703 * Return the full width measurement information for this view as computed 9704 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 9705 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 9706 * This should be used during measurement and layout calculations only. Use 9707 * {@link #getWidth()} to see how wide a view is after layout. 9708 * 9709 * @return The measured width of this view as a bit mask. 9710 */ 9711 public final int getMeasuredWidthAndState() { 9712 return mMeasuredWidth; 9713 } 9714 9715 /** 9716 * Like {@link #getMeasuredHeightAndState()}, but only returns the 9717 * raw width component (that is the result is masked by 9718 * {@link #MEASURED_SIZE_MASK}). 9719 * 9720 * @return The raw measured height of this view. 9721 */ 9722 public final int getMeasuredHeight() { 9723 return mMeasuredHeight & MEASURED_SIZE_MASK; 9724 } 9725 9726 /** 9727 * Return the full height measurement information for this view as computed 9728 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 9729 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 9730 * This should be used during measurement and layout calculations only. Use 9731 * {@link #getHeight()} to see how wide a view is after layout. 9732 * 9733 * @return The measured width of this view as a bit mask. 9734 */ 9735 public final int getMeasuredHeightAndState() { 9736 return mMeasuredHeight; 9737 } 9738 9739 /** 9740 * Return only the state bits of {@link #getMeasuredWidthAndState()} 9741 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 9742 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 9743 * and the height component is at the shifted bits 9744 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 9745 */ 9746 public final int getMeasuredState() { 9747 return (mMeasuredWidth&MEASURED_STATE_MASK) 9748 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 9749 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 9750 } 9751 9752 /** 9753 * The transform matrix of this view, which is calculated based on the current 9754 * rotation, scale, and pivot properties. 9755 * 9756 * @see #getRotation() 9757 * @see #getScaleX() 9758 * @see #getScaleY() 9759 * @see #getPivotX() 9760 * @see #getPivotY() 9761 * @return The current transform matrix for the view 9762 */ 9763 public Matrix getMatrix() { 9764 ensureTransformationInfo(); 9765 final Matrix matrix = mTransformationInfo.mMatrix; 9766 mRenderNode.getMatrix(matrix); 9767 return matrix; 9768 } 9769 9770 /** 9771 * Returns true if the transform matrix is the identity matrix. 9772 * Recomputes the matrix if necessary. 9773 * 9774 * @return True if the transform matrix is the identity matrix, false otherwise. 9775 */ 9776 final boolean hasIdentityMatrix() { 9777 return mRenderNode.hasIdentityMatrix(); 9778 } 9779 9780 void ensureTransformationInfo() { 9781 if (mTransformationInfo == null) { 9782 mTransformationInfo = new TransformationInfo(); 9783 } 9784 } 9785 9786 /** 9787 * Utility method to retrieve the inverse of the current mMatrix property. 9788 * We cache the matrix to avoid recalculating it when transform properties 9789 * have not changed. 9790 * 9791 * @return The inverse of the current matrix of this view. 9792 * @hide 9793 */ 9794 public final Matrix getInverseMatrix() { 9795 ensureTransformationInfo(); 9796 if (mTransformationInfo.mInverseMatrix == null) { 9797 mTransformationInfo.mInverseMatrix = new Matrix(); 9798 } 9799 final Matrix matrix = mTransformationInfo.mInverseMatrix; 9800 mRenderNode.getInverseMatrix(matrix); 9801 return matrix; 9802 } 9803 9804 /** 9805 * Gets the distance along the Z axis from the camera to this view. 9806 * 9807 * @see #setCameraDistance(float) 9808 * 9809 * @return The distance along the Z axis. 9810 */ 9811 public float getCameraDistance() { 9812 final float dpi = mResources.getDisplayMetrics().densityDpi; 9813 return -(mRenderNode.getCameraDistance() * dpi); 9814 } 9815 9816 /** 9817 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 9818 * views are drawn) from the camera to this view. The camera's distance 9819 * affects 3D transformations, for instance rotations around the X and Y 9820 * axis. If the rotationX or rotationY properties are changed and this view is 9821 * large (more than half the size of the screen), it is recommended to always 9822 * use a camera distance that's greater than the height (X axis rotation) or 9823 * the width (Y axis rotation) of this view.</p> 9824 * 9825 * <p>The distance of the camera from the view plane can have an affect on the 9826 * perspective distortion of the view when it is rotated around the x or y axis. 9827 * For example, a large distance will result in a large viewing angle, and there 9828 * will not be much perspective distortion of the view as it rotates. A short 9829 * distance may cause much more perspective distortion upon rotation, and can 9830 * also result in some drawing artifacts if the rotated view ends up partially 9831 * behind the camera (which is why the recommendation is to use a distance at 9832 * least as far as the size of the view, if the view is to be rotated.)</p> 9833 * 9834 * <p>The distance is expressed in "depth pixels." The default distance depends 9835 * on the screen density. For instance, on a medium density display, the 9836 * default distance is 1280. On a high density display, the default distance 9837 * is 1920.</p> 9838 * 9839 * <p>If you want to specify a distance that leads to visually consistent 9840 * results across various densities, use the following formula:</p> 9841 * <pre> 9842 * float scale = context.getResources().getDisplayMetrics().density; 9843 * view.setCameraDistance(distance * scale); 9844 * </pre> 9845 * 9846 * <p>The density scale factor of a high density display is 1.5, 9847 * and 1920 = 1280 * 1.5.</p> 9848 * 9849 * @param distance The distance in "depth pixels", if negative the opposite 9850 * value is used 9851 * 9852 * @see #setRotationX(float) 9853 * @see #setRotationY(float) 9854 */ 9855 public void setCameraDistance(float distance) { 9856 final float dpi = mResources.getDisplayMetrics().densityDpi; 9857 9858 invalidateViewProperty(true, false); 9859 mRenderNode.setCameraDistance(-Math.abs(distance) / dpi); 9860 invalidateViewProperty(false, false); 9861 9862 invalidateParentIfNeededAndWasQuickRejected(); 9863 } 9864 9865 /** 9866 * The degrees that the view is rotated around the pivot point. 9867 * 9868 * @see #setRotation(float) 9869 * @see #getPivotX() 9870 * @see #getPivotY() 9871 * 9872 * @return The degrees of rotation. 9873 */ 9874 @ViewDebug.ExportedProperty(category = "drawing") 9875 public float getRotation() { 9876 return mRenderNode.getRotation(); 9877 } 9878 9879 /** 9880 * Sets the degrees that the view is rotated around the pivot point. Increasing values 9881 * result in clockwise rotation. 9882 * 9883 * @param rotation The degrees of rotation. 9884 * 9885 * @see #getRotation() 9886 * @see #getPivotX() 9887 * @see #getPivotY() 9888 * @see #setRotationX(float) 9889 * @see #setRotationY(float) 9890 * 9891 * @attr ref android.R.styleable#View_rotation 9892 */ 9893 public void setRotation(float rotation) { 9894 if (rotation != getRotation()) { 9895 // Double-invalidation is necessary to capture view's old and new areas 9896 invalidateViewProperty(true, false); 9897 mRenderNode.setRotation(rotation); 9898 invalidateViewProperty(false, true); 9899 9900 invalidateParentIfNeededAndWasQuickRejected(); 9901 notifySubtreeAccessibilityStateChangedIfNeeded(); 9902 } 9903 } 9904 9905 /** 9906 * The degrees that the view is rotated around the vertical axis through the pivot point. 9907 * 9908 * @see #getPivotX() 9909 * @see #getPivotY() 9910 * @see #setRotationY(float) 9911 * 9912 * @return The degrees of Y rotation. 9913 */ 9914 @ViewDebug.ExportedProperty(category = "drawing") 9915 public float getRotationY() { 9916 return mRenderNode.getRotationY(); 9917 } 9918 9919 /** 9920 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 9921 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 9922 * down the y axis. 9923 * 9924 * When rotating large views, it is recommended to adjust the camera distance 9925 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 9926 * 9927 * @param rotationY The degrees of Y rotation. 9928 * 9929 * @see #getRotationY() 9930 * @see #getPivotX() 9931 * @see #getPivotY() 9932 * @see #setRotation(float) 9933 * @see #setRotationX(float) 9934 * @see #setCameraDistance(float) 9935 * 9936 * @attr ref android.R.styleable#View_rotationY 9937 */ 9938 public void setRotationY(float rotationY) { 9939 if (rotationY != getRotationY()) { 9940 invalidateViewProperty(true, false); 9941 mRenderNode.setRotationY(rotationY); 9942 invalidateViewProperty(false, true); 9943 9944 invalidateParentIfNeededAndWasQuickRejected(); 9945 notifySubtreeAccessibilityStateChangedIfNeeded(); 9946 } 9947 } 9948 9949 /** 9950 * The degrees that the view is rotated around the horizontal axis through the pivot point. 9951 * 9952 * @see #getPivotX() 9953 * @see #getPivotY() 9954 * @see #setRotationX(float) 9955 * 9956 * @return The degrees of X rotation. 9957 */ 9958 @ViewDebug.ExportedProperty(category = "drawing") 9959 public float getRotationX() { 9960 return mRenderNode.getRotationX(); 9961 } 9962 9963 /** 9964 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 9965 * Increasing values result in clockwise rotation from the viewpoint of looking down the 9966 * x axis. 9967 * 9968 * When rotating large views, it is recommended to adjust the camera distance 9969 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 9970 * 9971 * @param rotationX The degrees of X rotation. 9972 * 9973 * @see #getRotationX() 9974 * @see #getPivotX() 9975 * @see #getPivotY() 9976 * @see #setRotation(float) 9977 * @see #setRotationY(float) 9978 * @see #setCameraDistance(float) 9979 * 9980 * @attr ref android.R.styleable#View_rotationX 9981 */ 9982 public void setRotationX(float rotationX) { 9983 if (rotationX != getRotationX()) { 9984 invalidateViewProperty(true, false); 9985 mRenderNode.setRotationX(rotationX); 9986 invalidateViewProperty(false, true); 9987 9988 invalidateParentIfNeededAndWasQuickRejected(); 9989 notifySubtreeAccessibilityStateChangedIfNeeded(); 9990 } 9991 } 9992 9993 /** 9994 * The amount that the view is scaled in x around the pivot point, as a proportion of 9995 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 9996 * 9997 * <p>By default, this is 1.0f. 9998 * 9999 * @see #getPivotX() 10000 * @see #getPivotY() 10001 * @return The scaling factor. 10002 */ 10003 @ViewDebug.ExportedProperty(category = "drawing") 10004 public float getScaleX() { 10005 return mRenderNode.getScaleX(); 10006 } 10007 10008 /** 10009 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 10010 * the view's unscaled width. A value of 1 means that no scaling is applied. 10011 * 10012 * @param scaleX The scaling factor. 10013 * @see #getPivotX() 10014 * @see #getPivotY() 10015 * 10016 * @attr ref android.R.styleable#View_scaleX 10017 */ 10018 public void setScaleX(float scaleX) { 10019 if (scaleX != getScaleX()) { 10020 invalidateViewProperty(true, false); 10021 mRenderNode.setScaleX(scaleX); 10022 invalidateViewProperty(false, true); 10023 10024 invalidateParentIfNeededAndWasQuickRejected(); 10025 notifySubtreeAccessibilityStateChangedIfNeeded(); 10026 } 10027 } 10028 10029 /** 10030 * The amount that the view is scaled in y around the pivot point, as a proportion of 10031 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 10032 * 10033 * <p>By default, this is 1.0f. 10034 * 10035 * @see #getPivotX() 10036 * @see #getPivotY() 10037 * @return The scaling factor. 10038 */ 10039 @ViewDebug.ExportedProperty(category = "drawing") 10040 public float getScaleY() { 10041 return mRenderNode.getScaleY(); 10042 } 10043 10044 /** 10045 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 10046 * the view's unscaled width. A value of 1 means that no scaling is applied. 10047 * 10048 * @param scaleY The scaling factor. 10049 * @see #getPivotX() 10050 * @see #getPivotY() 10051 * 10052 * @attr ref android.R.styleable#View_scaleY 10053 */ 10054 public void setScaleY(float scaleY) { 10055 if (scaleY != getScaleY()) { 10056 invalidateViewProperty(true, false); 10057 mRenderNode.setScaleY(scaleY); 10058 invalidateViewProperty(false, true); 10059 10060 invalidateParentIfNeededAndWasQuickRejected(); 10061 notifySubtreeAccessibilityStateChangedIfNeeded(); 10062 } 10063 } 10064 10065 /** 10066 * The x location of the point around which the view is {@link #setRotation(float) rotated} 10067 * and {@link #setScaleX(float) scaled}. 10068 * 10069 * @see #getRotation() 10070 * @see #getScaleX() 10071 * @see #getScaleY() 10072 * @see #getPivotY() 10073 * @return The x location of the pivot point. 10074 * 10075 * @attr ref android.R.styleable#View_transformPivotX 10076 */ 10077 @ViewDebug.ExportedProperty(category = "drawing") 10078 public float getPivotX() { 10079 return mRenderNode.getPivotX(); 10080 } 10081 10082 /** 10083 * Sets the x location of the point around which the view is 10084 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 10085 * By default, the pivot point is centered on the object. 10086 * Setting this property disables this behavior and causes the view to use only the 10087 * explicitly set pivotX and pivotY values. 10088 * 10089 * @param pivotX The x location of the pivot point. 10090 * @see #getRotation() 10091 * @see #getScaleX() 10092 * @see #getScaleY() 10093 * @see #getPivotY() 10094 * 10095 * @attr ref android.R.styleable#View_transformPivotX 10096 */ 10097 public void setPivotX(float pivotX) { 10098 if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) { 10099 invalidateViewProperty(true, false); 10100 mRenderNode.setPivotX(pivotX); 10101 invalidateViewProperty(false, true); 10102 10103 invalidateParentIfNeededAndWasQuickRejected(); 10104 } 10105 } 10106 10107 /** 10108 * The y location of the point around which the view is {@link #setRotation(float) rotated} 10109 * and {@link #setScaleY(float) scaled}. 10110 * 10111 * @see #getRotation() 10112 * @see #getScaleX() 10113 * @see #getScaleY() 10114 * @see #getPivotY() 10115 * @return The y location of the pivot point. 10116 * 10117 * @attr ref android.R.styleable#View_transformPivotY 10118 */ 10119 @ViewDebug.ExportedProperty(category = "drawing") 10120 public float getPivotY() { 10121 return mRenderNode.getPivotY(); 10122 } 10123 10124 /** 10125 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 10126 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 10127 * Setting this property disables this behavior and causes the view to use only the 10128 * explicitly set pivotX and pivotY values. 10129 * 10130 * @param pivotY The y location of the pivot point. 10131 * @see #getRotation() 10132 * @see #getScaleX() 10133 * @see #getScaleY() 10134 * @see #getPivotY() 10135 * 10136 * @attr ref android.R.styleable#View_transformPivotY 10137 */ 10138 public void setPivotY(float pivotY) { 10139 if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) { 10140 invalidateViewProperty(true, false); 10141 mRenderNode.setPivotY(pivotY); 10142 invalidateViewProperty(false, true); 10143 10144 invalidateParentIfNeededAndWasQuickRejected(); 10145 } 10146 } 10147 10148 /** 10149 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 10150 * completely transparent and 1 means the view is completely opaque. 10151 * 10152 * <p>By default this is 1.0f. 10153 * @return The opacity of the view. 10154 */ 10155 @ViewDebug.ExportedProperty(category = "drawing") 10156 public float getAlpha() { 10157 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 10158 } 10159 10160 /** 10161 * Returns whether this View has content which overlaps. 10162 * 10163 * <p>This function, intended to be overridden by specific View types, is an optimization when 10164 * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to 10165 * an offscreen buffer and then composited into place, which can be expensive. If the view has 10166 * no overlapping rendering, the view can draw each primitive with the appropriate alpha value 10167 * directly. An example of overlapping rendering is a TextView with a background image, such as 10168 * a Button. An example of non-overlapping rendering is a TextView with no background, or an 10169 * ImageView with only the foreground image. The default implementation returns true; subclasses 10170 * should override if they have cases which can be optimized.</p> 10171 * 10172 * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas} 10173 * necessitates that a View return true if it uses the methods internally without passing the 10174 * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p> 10175 * 10176 * @return true if the content in this view might overlap, false otherwise. 10177 */ 10178 public boolean hasOverlappingRendering() { 10179 return true; 10180 } 10181 10182 /** 10183 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 10184 * completely transparent and 1 means the view is completely opaque.</p> 10185 * 10186 * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant 10187 * performance implications, especially for large views. It is best to use the alpha property 10188 * sparingly and transiently, as in the case of fading animations.</p> 10189 * 10190 * <p>For a view with a frequently changing alpha, such as during a fading animation, it is 10191 * strongly recommended for performance reasons to either override 10192 * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a 10193 * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p> 10194 * 10195 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 10196 * responsible for applying the opacity itself.</p> 10197 * 10198 * <p>Note that if the view is backed by a 10199 * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a 10200 * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than 10201 * 1.0 will supercede the alpha of the layer paint.</p> 10202 * 10203 * @param alpha The opacity of the view. 10204 * 10205 * @see #hasOverlappingRendering() 10206 * @see #setLayerType(int, android.graphics.Paint) 10207 * 10208 * @attr ref android.R.styleable#View_alpha 10209 */ 10210 public void setAlpha(float alpha) { 10211 ensureTransformationInfo(); 10212 if (mTransformationInfo.mAlpha != alpha) { 10213 mTransformationInfo.mAlpha = alpha; 10214 if (onSetAlpha((int) (alpha * 255))) { 10215 mPrivateFlags |= PFLAG_ALPHA_SET; 10216 // subclass is handling alpha - don't optimize rendering cache invalidation 10217 invalidateParentCaches(); 10218 invalidate(true); 10219 } else { 10220 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10221 invalidateViewProperty(true, false); 10222 mRenderNode.setAlpha(getFinalAlpha()); 10223 notifyViewAccessibilityStateChangedIfNeeded( 10224 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 10225 } 10226 } 10227 } 10228 10229 /** 10230 * Faster version of setAlpha() which performs the same steps except there are 10231 * no calls to invalidate(). The caller of this function should perform proper invalidation 10232 * on the parent and this object. The return value indicates whether the subclass handles 10233 * alpha (the return value for onSetAlpha()). 10234 * 10235 * @param alpha The new value for the alpha property 10236 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 10237 * the new value for the alpha property is different from the old value 10238 */ 10239 boolean setAlphaNoInvalidation(float alpha) { 10240 ensureTransformationInfo(); 10241 if (mTransformationInfo.mAlpha != alpha) { 10242 mTransformationInfo.mAlpha = alpha; 10243 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 10244 if (subclassHandlesAlpha) { 10245 mPrivateFlags |= PFLAG_ALPHA_SET; 10246 return true; 10247 } else { 10248 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10249 mRenderNode.setAlpha(getFinalAlpha()); 10250 } 10251 } 10252 return false; 10253 } 10254 10255 /** 10256 * This property is hidden and intended only for use by the Fade transition, which 10257 * animates it to produce a visual translucency that does not side-effect (or get 10258 * affected by) the real alpha property. This value is composited with the other 10259 * alpha value (and the AlphaAnimation value, when that is present) to produce 10260 * a final visual translucency result, which is what is passed into the DisplayList. 10261 * 10262 * @hide 10263 */ 10264 public void setTransitionAlpha(float alpha) { 10265 ensureTransformationInfo(); 10266 if (mTransformationInfo.mTransitionAlpha != alpha) { 10267 mTransformationInfo.mTransitionAlpha = alpha; 10268 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10269 invalidateViewProperty(true, false); 10270 mRenderNode.setAlpha(getFinalAlpha()); 10271 } 10272 } 10273 10274 /** 10275 * Calculates the visual alpha of this view, which is a combination of the actual 10276 * alpha value and the transitionAlpha value (if set). 10277 */ 10278 private float getFinalAlpha() { 10279 if (mTransformationInfo != null) { 10280 return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha; 10281 } 10282 return 1; 10283 } 10284 10285 /** 10286 * This property is hidden and intended only for use by the Fade transition, which 10287 * animates it to produce a visual translucency that does not side-effect (or get 10288 * affected by) the real alpha property. This value is composited with the other 10289 * alpha value (and the AlphaAnimation value, when that is present) to produce 10290 * a final visual translucency result, which is what is passed into the DisplayList. 10291 * 10292 * @hide 10293 */ 10294 @ViewDebug.ExportedProperty(category = "drawing") 10295 public float getTransitionAlpha() { 10296 return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1; 10297 } 10298 10299 /** 10300 * Top position of this view relative to its parent. 10301 * 10302 * @return The top of this view, in pixels. 10303 */ 10304 @ViewDebug.CapturedViewProperty 10305 public final int getTop() { 10306 return mTop; 10307 } 10308 10309 /** 10310 * Sets the top position of this view relative to its parent. This method is meant to be called 10311 * by the layout system and should not generally be called otherwise, because the property 10312 * may be changed at any time by the layout. 10313 * 10314 * @param top The top of this view, in pixels. 10315 */ 10316 public final void setTop(int top) { 10317 if (top != mTop) { 10318 final boolean matrixIsIdentity = hasIdentityMatrix(); 10319 if (matrixIsIdentity) { 10320 if (mAttachInfo != null) { 10321 int minTop; 10322 int yLoc; 10323 if (top < mTop) { 10324 minTop = top; 10325 yLoc = top - mTop; 10326 } else { 10327 minTop = mTop; 10328 yLoc = 0; 10329 } 10330 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 10331 } 10332 } else { 10333 // Double-invalidation is necessary to capture view's old and new areas 10334 invalidate(true); 10335 } 10336 10337 int width = mRight - mLeft; 10338 int oldHeight = mBottom - mTop; 10339 10340 mTop = top; 10341 mRenderNode.setTop(mTop); 10342 10343 sizeChange(width, mBottom - mTop, width, oldHeight); 10344 10345 if (!matrixIsIdentity) { 10346 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10347 invalidate(true); 10348 } 10349 mBackgroundSizeChanged = true; 10350 invalidateParentIfNeeded(); 10351 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10352 // View was rejected last time it was drawn by its parent; this may have changed 10353 invalidateParentIfNeeded(); 10354 } 10355 } 10356 } 10357 10358 /** 10359 * Bottom position of this view relative to its parent. 10360 * 10361 * @return The bottom of this view, in pixels. 10362 */ 10363 @ViewDebug.CapturedViewProperty 10364 public final int getBottom() { 10365 return mBottom; 10366 } 10367 10368 /** 10369 * True if this view has changed since the last time being drawn. 10370 * 10371 * @return The dirty state of this view. 10372 */ 10373 public boolean isDirty() { 10374 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 10375 } 10376 10377 /** 10378 * Sets the bottom position of this view relative to its parent. This method is meant to be 10379 * called by the layout system and should not generally be called otherwise, because the 10380 * property may be changed at any time by the layout. 10381 * 10382 * @param bottom The bottom of this view, in pixels. 10383 */ 10384 public final void setBottom(int bottom) { 10385 if (bottom != mBottom) { 10386 final boolean matrixIsIdentity = hasIdentityMatrix(); 10387 if (matrixIsIdentity) { 10388 if (mAttachInfo != null) { 10389 int maxBottom; 10390 if (bottom < mBottom) { 10391 maxBottom = mBottom; 10392 } else { 10393 maxBottom = bottom; 10394 } 10395 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 10396 } 10397 } else { 10398 // Double-invalidation is necessary to capture view's old and new areas 10399 invalidate(true); 10400 } 10401 10402 int width = mRight - mLeft; 10403 int oldHeight = mBottom - mTop; 10404 10405 mBottom = bottom; 10406 mRenderNode.setBottom(mBottom); 10407 10408 sizeChange(width, mBottom - mTop, width, oldHeight); 10409 10410 if (!matrixIsIdentity) { 10411 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10412 invalidate(true); 10413 } 10414 mBackgroundSizeChanged = true; 10415 invalidateParentIfNeeded(); 10416 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10417 // View was rejected last time it was drawn by its parent; this may have changed 10418 invalidateParentIfNeeded(); 10419 } 10420 } 10421 } 10422 10423 /** 10424 * Left position of this view relative to its parent. 10425 * 10426 * @return The left edge of this view, in pixels. 10427 */ 10428 @ViewDebug.CapturedViewProperty 10429 public final int getLeft() { 10430 return mLeft; 10431 } 10432 10433 /** 10434 * Sets the left position of this view relative to its parent. This method is meant to be called 10435 * by the layout system and should not generally be called otherwise, because the property 10436 * may be changed at any time by the layout. 10437 * 10438 * @param left The left of this view, in pixels. 10439 */ 10440 public final void setLeft(int left) { 10441 if (left != mLeft) { 10442 final boolean matrixIsIdentity = hasIdentityMatrix(); 10443 if (matrixIsIdentity) { 10444 if (mAttachInfo != null) { 10445 int minLeft; 10446 int xLoc; 10447 if (left < mLeft) { 10448 minLeft = left; 10449 xLoc = left - mLeft; 10450 } else { 10451 minLeft = mLeft; 10452 xLoc = 0; 10453 } 10454 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 10455 } 10456 } else { 10457 // Double-invalidation is necessary to capture view's old and new areas 10458 invalidate(true); 10459 } 10460 10461 int oldWidth = mRight - mLeft; 10462 int height = mBottom - mTop; 10463 10464 mLeft = left; 10465 mRenderNode.setLeft(left); 10466 10467 sizeChange(mRight - mLeft, height, oldWidth, height); 10468 10469 if (!matrixIsIdentity) { 10470 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10471 invalidate(true); 10472 } 10473 mBackgroundSizeChanged = true; 10474 invalidateParentIfNeeded(); 10475 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10476 // View was rejected last time it was drawn by its parent; this may have changed 10477 invalidateParentIfNeeded(); 10478 } 10479 } 10480 } 10481 10482 /** 10483 * Right position of this view relative to its parent. 10484 * 10485 * @return The right edge of this view, in pixels. 10486 */ 10487 @ViewDebug.CapturedViewProperty 10488 public final int getRight() { 10489 return mRight; 10490 } 10491 10492 /** 10493 * Sets the right position of this view relative to its parent. This method is meant to be called 10494 * by the layout system and should not generally be called otherwise, because the property 10495 * may be changed at any time by the layout. 10496 * 10497 * @param right The right of this view, in pixels. 10498 */ 10499 public final void setRight(int right) { 10500 if (right != mRight) { 10501 final boolean matrixIsIdentity = hasIdentityMatrix(); 10502 if (matrixIsIdentity) { 10503 if (mAttachInfo != null) { 10504 int maxRight; 10505 if (right < mRight) { 10506 maxRight = mRight; 10507 } else { 10508 maxRight = right; 10509 } 10510 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 10511 } 10512 } else { 10513 // Double-invalidation is necessary to capture view's old and new areas 10514 invalidate(true); 10515 } 10516 10517 int oldWidth = mRight - mLeft; 10518 int height = mBottom - mTop; 10519 10520 mRight = right; 10521 mRenderNode.setRight(mRight); 10522 10523 sizeChange(mRight - mLeft, height, oldWidth, height); 10524 10525 if (!matrixIsIdentity) { 10526 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10527 invalidate(true); 10528 } 10529 mBackgroundSizeChanged = true; 10530 invalidateParentIfNeeded(); 10531 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10532 // View was rejected last time it was drawn by its parent; this may have changed 10533 invalidateParentIfNeeded(); 10534 } 10535 } 10536 } 10537 10538 /** 10539 * The visual x position of this view, in pixels. This is equivalent to the 10540 * {@link #setTranslationX(float) translationX} property plus the current 10541 * {@link #getLeft() left} property. 10542 * 10543 * @return The visual x position of this view, in pixels. 10544 */ 10545 @ViewDebug.ExportedProperty(category = "drawing") 10546 public float getX() { 10547 return mLeft + getTranslationX(); 10548 } 10549 10550 /** 10551 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 10552 * {@link #setTranslationX(float) translationX} property to be the difference between 10553 * the x value passed in and the current {@link #getLeft() left} property. 10554 * 10555 * @param x The visual x position of this view, in pixels. 10556 */ 10557 public void setX(float x) { 10558 setTranslationX(x - mLeft); 10559 } 10560 10561 /** 10562 * The visual y position of this view, in pixels. This is equivalent to the 10563 * {@link #setTranslationY(float) translationY} property plus the current 10564 * {@link #getTop() top} property. 10565 * 10566 * @return The visual y position of this view, in pixels. 10567 */ 10568 @ViewDebug.ExportedProperty(category = "drawing") 10569 public float getY() { 10570 return mTop + getTranslationY(); 10571 } 10572 10573 /** 10574 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 10575 * {@link #setTranslationY(float) translationY} property to be the difference between 10576 * the y value passed in and the current {@link #getTop() top} property. 10577 * 10578 * @param y The visual y position of this view, in pixels. 10579 */ 10580 public void setY(float y) { 10581 setTranslationY(y - mTop); 10582 } 10583 10584 /** 10585 * The visual z position of this view, in pixels. This is equivalent to the 10586 * {@link #setTranslationZ(float) translationZ} property plus the current 10587 * {@link #getElevation() elevation} property. 10588 * 10589 * @return The visual z position of this view, in pixels. 10590 */ 10591 @ViewDebug.ExportedProperty(category = "drawing") 10592 public float getZ() { 10593 return getElevation() + getTranslationZ(); 10594 } 10595 10596 /** 10597 * Sets the visual z position of this view, in pixels. This is equivalent to setting the 10598 * {@link #setTranslationZ(float) translationZ} property to be the difference between 10599 * the x value passed in and the current {@link #getElevation() elevation} property. 10600 * 10601 * @param z The visual z position of this view, in pixels. 10602 */ 10603 public void setZ(float z) { 10604 setTranslationZ(z - getElevation()); 10605 } 10606 10607 /** 10608 * The base elevation of this view relative to its parent, in pixels. 10609 * 10610 * @return The base depth position of the view, in pixels. 10611 */ 10612 @ViewDebug.ExportedProperty(category = "drawing") 10613 public float getElevation() { 10614 return mRenderNode.getElevation(); 10615 } 10616 10617 /** 10618 * Sets the base elevation of this view, in pixels. 10619 * 10620 * @attr ref android.R.styleable#View_elevation 10621 */ 10622 public void setElevation(float elevation) { 10623 if (elevation != getElevation()) { 10624 invalidateViewProperty(true, false); 10625 mRenderNode.setElevation(elevation); 10626 invalidateViewProperty(false, true); 10627 10628 invalidateParentIfNeededAndWasQuickRejected(); 10629 } 10630 } 10631 10632 /** 10633 * The horizontal location of this view relative to its {@link #getLeft() left} position. 10634 * This position is post-layout, in addition to wherever the object's 10635 * layout placed it. 10636 * 10637 * @return The horizontal position of this view relative to its left position, in pixels. 10638 */ 10639 @ViewDebug.ExportedProperty(category = "drawing") 10640 public float getTranslationX() { 10641 return mRenderNode.getTranslationX(); 10642 } 10643 10644 /** 10645 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 10646 * This effectively positions the object post-layout, in addition to wherever the object's 10647 * layout placed it. 10648 * 10649 * @param translationX The horizontal position of this view relative to its left position, 10650 * in pixels. 10651 * 10652 * @attr ref android.R.styleable#View_translationX 10653 */ 10654 public void setTranslationX(float translationX) { 10655 if (translationX != getTranslationX()) { 10656 invalidateViewProperty(true, false); 10657 mRenderNode.setTranslationX(translationX); 10658 invalidateViewProperty(false, true); 10659 10660 invalidateParentIfNeededAndWasQuickRejected(); 10661 notifySubtreeAccessibilityStateChangedIfNeeded(); 10662 } 10663 } 10664 10665 /** 10666 * The vertical location of this view relative to its {@link #getTop() top} position. 10667 * This position is post-layout, in addition to wherever the object's 10668 * layout placed it. 10669 * 10670 * @return The vertical position of this view relative to its top position, 10671 * in pixels. 10672 */ 10673 @ViewDebug.ExportedProperty(category = "drawing") 10674 public float getTranslationY() { 10675 return mRenderNode.getTranslationY(); 10676 } 10677 10678 /** 10679 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 10680 * This effectively positions the object post-layout, in addition to wherever the object's 10681 * layout placed it. 10682 * 10683 * @param translationY The vertical position of this view relative to its top position, 10684 * in pixels. 10685 * 10686 * @attr ref android.R.styleable#View_translationY 10687 */ 10688 public void setTranslationY(float translationY) { 10689 if (translationY != getTranslationY()) { 10690 invalidateViewProperty(true, false); 10691 mRenderNode.setTranslationY(translationY); 10692 invalidateViewProperty(false, true); 10693 10694 invalidateParentIfNeededAndWasQuickRejected(); 10695 } 10696 } 10697 10698 /** 10699 * The depth location of this view relative to its {@link #getElevation() elevation}. 10700 * 10701 * @return The depth of this view relative to its elevation. 10702 */ 10703 @ViewDebug.ExportedProperty(category = "drawing") 10704 public float getTranslationZ() { 10705 return mRenderNode.getTranslationZ(); 10706 } 10707 10708 /** 10709 * Sets the depth location of this view relative to its {@link #getElevation() elevation}. 10710 * 10711 * @attr ref android.R.styleable#View_translationZ 10712 */ 10713 public void setTranslationZ(float translationZ) { 10714 if (translationZ != getTranslationZ()) { 10715 invalidateViewProperty(true, false); 10716 mRenderNode.setTranslationZ(translationZ); 10717 invalidateViewProperty(false, true); 10718 10719 invalidateParentIfNeededAndWasQuickRejected(); 10720 } 10721 } 10722 10723 /** 10724 * Returns the current StateListAnimator if exists. 10725 * 10726 * @return StateListAnimator or null if it does not exists 10727 * @see #setStateListAnimator(android.animation.StateListAnimator) 10728 */ 10729 public StateListAnimator getStateListAnimator() { 10730 return mStateListAnimator; 10731 } 10732 10733 /** 10734 * Attaches the provided StateListAnimator to this View. 10735 * <p> 10736 * Any previously attached StateListAnimator will be detached. 10737 * 10738 * @param stateListAnimator The StateListAnimator to update the view 10739 * @see {@link android.animation.StateListAnimator} 10740 */ 10741 public void setStateListAnimator(StateListAnimator stateListAnimator) { 10742 if (mStateListAnimator == stateListAnimator) { 10743 return; 10744 } 10745 if (mStateListAnimator != null) { 10746 mStateListAnimator.setTarget(null); 10747 } 10748 mStateListAnimator = stateListAnimator; 10749 if (stateListAnimator != null) { 10750 stateListAnimator.setTarget(this); 10751 if (isAttachedToWindow()) { 10752 stateListAnimator.setState(getDrawableState()); 10753 } 10754 } 10755 } 10756 10757 /** 10758 * Deprecated, pending removal 10759 * 10760 * @hide 10761 */ 10762 @Deprecated 10763 public void setOutline(@Nullable Outline outline) {} 10764 10765 /** 10766 * Returns whether the Outline should be used to clip the contents of the View. 10767 * <p> 10768 * Note that this flag will only be respected if the View's Outline returns true from 10769 * {@link Outline#canClip()}. 10770 * 10771 * @see #setOutlineProvider(ViewOutlineProvider) 10772 * @see #setClipToOutline(boolean) 10773 */ 10774 public final boolean getClipToOutline() { 10775 return mRenderNode.getClipToOutline(); 10776 } 10777 10778 /** 10779 * Sets whether the View's Outline should be used to clip the contents of the View. 10780 * <p> 10781 * Note that this flag will only be respected if the View's Outline returns true from 10782 * {@link Outline#canClip()}. 10783 * 10784 * @see #setOutlineProvider(ViewOutlineProvider) 10785 * @see #getClipToOutline() 10786 */ 10787 public void setClipToOutline(boolean clipToOutline) { 10788 damageInParent(); 10789 if (getClipToOutline() != clipToOutline) { 10790 mRenderNode.setClipToOutline(clipToOutline); 10791 } 10792 } 10793 10794 /** 10795 * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines 10796 * the shape of the shadow it casts, and enables outline clipping. 10797 * <p> 10798 * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline 10799 * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the 10800 * outline provider with this method allows this behavior to be overridden. 10801 * <p> 10802 * If the ViewOutlineProvider is null, if querying it for an outline returns false, 10803 * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast. 10804 * <p> 10805 * Only outlines that return true from {@link Outline#canClip()} may be used for clipping. 10806 * 10807 * @see #setClipToOutline(boolean) 10808 * @see #getClipToOutline() 10809 * @see #getOutlineProvider() 10810 */ 10811 public void setOutlineProvider(ViewOutlineProvider provider) { 10812 mOutlineProvider = provider; 10813 invalidateOutline(); 10814 } 10815 10816 /** 10817 * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline 10818 * that defines the shape of the shadow it casts, and enables outline clipping. 10819 * 10820 * @see #setOutlineProvider(ViewOutlineProvider) 10821 */ 10822 public ViewOutlineProvider getOutlineProvider() { 10823 return mOutlineProvider; 10824 } 10825 10826 /** 10827 * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider} 10828 * 10829 * @see #setOutlineProvider(ViewOutlineProvider) 10830 */ 10831 public void invalidateOutline() { 10832 // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow() 10833 if (mAttachInfo == null) return; 10834 10835 if (mOutlineProvider == null) { 10836 // no provider, remove outline 10837 mRenderNode.setOutline(null); 10838 } else { 10839 final Outline outline = mAttachInfo.mTmpOutline; 10840 outline.setEmpty(); 10841 outline.setAlpha(1.0f); 10842 10843 mOutlineProvider.getOutline(this, outline); 10844 mRenderNode.setOutline(outline); 10845 } 10846 10847 notifySubtreeAccessibilityStateChangedIfNeeded(); 10848 invalidateViewProperty(false, false); 10849 } 10850 10851 /** @hide */ 10852 public void setRevealClip(boolean shouldClip, float x, float y, float radius) { 10853 mRenderNode.setRevealClip(shouldClip, x, y, radius); 10854 invalidateViewProperty(false, false); 10855 } 10856 10857 /** 10858 * Hit rectangle in parent's coordinates 10859 * 10860 * @param outRect The hit rectangle of the view. 10861 */ 10862 public void getHitRect(Rect outRect) { 10863 if (hasIdentityMatrix() || mAttachInfo == null) { 10864 outRect.set(mLeft, mTop, mRight, mBottom); 10865 } else { 10866 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 10867 tmpRect.set(0, 0, getWidth(), getHeight()); 10868 getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect) 10869 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 10870 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 10871 } 10872 } 10873 10874 /** 10875 * Determines whether the given point, in local coordinates is inside the view. 10876 */ 10877 /*package*/ final boolean pointInView(float localX, float localY) { 10878 return localX >= 0 && localX < (mRight - mLeft) 10879 && localY >= 0 && localY < (mBottom - mTop); 10880 } 10881 10882 /** 10883 * Utility method to determine whether the given point, in local coordinates, 10884 * is inside the view, where the area of the view is expanded by the slop factor. 10885 * This method is called while processing touch-move events to determine if the event 10886 * is still within the view. 10887 * 10888 * @hide 10889 */ 10890 public boolean pointInView(float localX, float localY, float slop) { 10891 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 10892 localY < ((mBottom - mTop) + slop); 10893 } 10894 10895 /** 10896 * When a view has focus and the user navigates away from it, the next view is searched for 10897 * starting from the rectangle filled in by this method. 10898 * 10899 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 10900 * of the view. However, if your view maintains some idea of internal selection, 10901 * such as a cursor, or a selected row or column, you should override this method and 10902 * fill in a more specific rectangle. 10903 * 10904 * @param r The rectangle to fill in, in this view's coordinates. 10905 */ 10906 public void getFocusedRect(Rect r) { 10907 getDrawingRect(r); 10908 } 10909 10910 /** 10911 * If some part of this view is not clipped by any of its parents, then 10912 * return that area in r in global (root) coordinates. To convert r to local 10913 * coordinates (without taking possible View rotations into account), offset 10914 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 10915 * If the view is completely clipped or translated out, return false. 10916 * 10917 * @param r If true is returned, r holds the global coordinates of the 10918 * visible portion of this view. 10919 * @param globalOffset If true is returned, globalOffset holds the dx,dy 10920 * between this view and its root. globalOffet may be null. 10921 * @return true if r is non-empty (i.e. part of the view is visible at the 10922 * root level. 10923 */ 10924 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 10925 int width = mRight - mLeft; 10926 int height = mBottom - mTop; 10927 if (width > 0 && height > 0) { 10928 r.set(0, 0, width, height); 10929 if (globalOffset != null) { 10930 globalOffset.set(-mScrollX, -mScrollY); 10931 } 10932 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 10933 } 10934 return false; 10935 } 10936 10937 public final boolean getGlobalVisibleRect(Rect r) { 10938 return getGlobalVisibleRect(r, null); 10939 } 10940 10941 public final boolean getLocalVisibleRect(Rect r) { 10942 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 10943 if (getGlobalVisibleRect(r, offset)) { 10944 r.offset(-offset.x, -offset.y); // make r local 10945 return true; 10946 } 10947 return false; 10948 } 10949 10950 /** 10951 * Offset this view's vertical location by the specified number of pixels. 10952 * 10953 * @param offset the number of pixels to offset the view by 10954 */ 10955 public void offsetTopAndBottom(int offset) { 10956 if (offset != 0) { 10957 final boolean matrixIsIdentity = hasIdentityMatrix(); 10958 if (matrixIsIdentity) { 10959 if (isHardwareAccelerated()) { 10960 invalidateViewProperty(false, false); 10961 } else { 10962 final ViewParent p = mParent; 10963 if (p != null && mAttachInfo != null) { 10964 final Rect r = mAttachInfo.mTmpInvalRect; 10965 int minTop; 10966 int maxBottom; 10967 int yLoc; 10968 if (offset < 0) { 10969 minTop = mTop + offset; 10970 maxBottom = mBottom; 10971 yLoc = offset; 10972 } else { 10973 minTop = mTop; 10974 maxBottom = mBottom + offset; 10975 yLoc = 0; 10976 } 10977 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 10978 p.invalidateChild(this, r); 10979 } 10980 } 10981 } else { 10982 invalidateViewProperty(false, false); 10983 } 10984 10985 mTop += offset; 10986 mBottom += offset; 10987 mRenderNode.offsetTopAndBottom(offset); 10988 if (isHardwareAccelerated()) { 10989 invalidateViewProperty(false, false); 10990 } else { 10991 if (!matrixIsIdentity) { 10992 invalidateViewProperty(false, true); 10993 } 10994 invalidateParentIfNeeded(); 10995 } 10996 notifySubtreeAccessibilityStateChangedIfNeeded(); 10997 } 10998 } 10999 11000 /** 11001 * Offset this view's horizontal location by the specified amount of pixels. 11002 * 11003 * @param offset the number of pixels to offset the view by 11004 */ 11005 public void offsetLeftAndRight(int offset) { 11006 if (offset != 0) { 11007 final boolean matrixIsIdentity = hasIdentityMatrix(); 11008 if (matrixIsIdentity) { 11009 if (isHardwareAccelerated()) { 11010 invalidateViewProperty(false, false); 11011 } else { 11012 final ViewParent p = mParent; 11013 if (p != null && mAttachInfo != null) { 11014 final Rect r = mAttachInfo.mTmpInvalRect; 11015 int minLeft; 11016 int maxRight; 11017 if (offset < 0) { 11018 minLeft = mLeft + offset; 11019 maxRight = mRight; 11020 } else { 11021 minLeft = mLeft; 11022 maxRight = mRight + offset; 11023 } 11024 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 11025 p.invalidateChild(this, r); 11026 } 11027 } 11028 } else { 11029 invalidateViewProperty(false, false); 11030 } 11031 11032 mLeft += offset; 11033 mRight += offset; 11034 mRenderNode.offsetLeftAndRight(offset); 11035 if (isHardwareAccelerated()) { 11036 invalidateViewProperty(false, false); 11037 } else { 11038 if (!matrixIsIdentity) { 11039 invalidateViewProperty(false, true); 11040 } 11041 invalidateParentIfNeeded(); 11042 } 11043 notifySubtreeAccessibilityStateChangedIfNeeded(); 11044 } 11045 } 11046 11047 /** 11048 * Get the LayoutParams associated with this view. All views should have 11049 * layout parameters. These supply parameters to the <i>parent</i> of this 11050 * view specifying how it should be arranged. There are many subclasses of 11051 * ViewGroup.LayoutParams, and these correspond to the different subclasses 11052 * of ViewGroup that are responsible for arranging their children. 11053 * 11054 * This method may return null if this View is not attached to a parent 11055 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 11056 * was not invoked successfully. When a View is attached to a parent 11057 * ViewGroup, this method must not return null. 11058 * 11059 * @return The LayoutParams associated with this view, or null if no 11060 * parameters have been set yet 11061 */ 11062 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 11063 public ViewGroup.LayoutParams getLayoutParams() { 11064 return mLayoutParams; 11065 } 11066 11067 /** 11068 * Set the layout parameters associated with this view. These supply 11069 * parameters to the <i>parent</i> of this view specifying how it should be 11070 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 11071 * correspond to the different subclasses of ViewGroup that are responsible 11072 * for arranging their children. 11073 * 11074 * @param params The layout parameters for this view, cannot be null 11075 */ 11076 public void setLayoutParams(ViewGroup.LayoutParams params) { 11077 if (params == null) { 11078 throw new NullPointerException("Layout parameters cannot be null"); 11079 } 11080 mLayoutParams = params; 11081 resolveLayoutParams(); 11082 if (mParent instanceof ViewGroup) { 11083 ((ViewGroup) mParent).onSetLayoutParams(this, params); 11084 } 11085 requestLayout(); 11086 } 11087 11088 /** 11089 * Resolve the layout parameters depending on the resolved layout direction 11090 * 11091 * @hide 11092 */ 11093 public void resolveLayoutParams() { 11094 if (mLayoutParams != null) { 11095 mLayoutParams.resolveLayoutDirection(getLayoutDirection()); 11096 } 11097 } 11098 11099 /** 11100 * Set the scrolled position of your view. This will cause a call to 11101 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11102 * invalidated. 11103 * @param x the x position to scroll to 11104 * @param y the y position to scroll to 11105 */ 11106 public void scrollTo(int x, int y) { 11107 if (mScrollX != x || mScrollY != y) { 11108 int oldX = mScrollX; 11109 int oldY = mScrollY; 11110 mScrollX = x; 11111 mScrollY = y; 11112 invalidateParentCaches(); 11113 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 11114 if (!awakenScrollBars()) { 11115 postInvalidateOnAnimation(); 11116 } 11117 } 11118 } 11119 11120 /** 11121 * Move the scrolled position of your view. This will cause a call to 11122 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11123 * invalidated. 11124 * @param x the amount of pixels to scroll by horizontally 11125 * @param y the amount of pixels to scroll by vertically 11126 */ 11127 public void scrollBy(int x, int y) { 11128 scrollTo(mScrollX + x, mScrollY + y); 11129 } 11130 11131 /** 11132 * <p>Trigger the scrollbars to draw. When invoked this method starts an 11133 * animation to fade the scrollbars out after a default delay. If a subclass 11134 * provides animated scrolling, the start delay should equal the duration 11135 * of the scrolling animation.</p> 11136 * 11137 * <p>The animation starts only if at least one of the scrollbars is 11138 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 11139 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11140 * this method returns true, and false otherwise. If the animation is 11141 * started, this method calls {@link #invalidate()}; in that case the 11142 * caller should not call {@link #invalidate()}.</p> 11143 * 11144 * <p>This method should be invoked every time a subclass directly updates 11145 * the scroll parameters.</p> 11146 * 11147 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 11148 * and {@link #scrollTo(int, int)}.</p> 11149 * 11150 * @return true if the animation is played, false otherwise 11151 * 11152 * @see #awakenScrollBars(int) 11153 * @see #scrollBy(int, int) 11154 * @see #scrollTo(int, int) 11155 * @see #isHorizontalScrollBarEnabled() 11156 * @see #isVerticalScrollBarEnabled() 11157 * @see #setHorizontalScrollBarEnabled(boolean) 11158 * @see #setVerticalScrollBarEnabled(boolean) 11159 */ 11160 protected boolean awakenScrollBars() { 11161 return mScrollCache != null && 11162 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 11163 } 11164 11165 /** 11166 * Trigger the scrollbars to draw. 11167 * This method differs from awakenScrollBars() only in its default duration. 11168 * initialAwakenScrollBars() will show the scroll bars for longer than 11169 * usual to give the user more of a chance to notice them. 11170 * 11171 * @return true if the animation is played, false otherwise. 11172 */ 11173 private boolean initialAwakenScrollBars() { 11174 return mScrollCache != null && 11175 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 11176 } 11177 11178 /** 11179 * <p> 11180 * Trigger the scrollbars to draw. When invoked this method starts an 11181 * animation to fade the scrollbars out after a fixed delay. If a subclass 11182 * provides animated scrolling, the start delay should equal the duration of 11183 * the scrolling animation. 11184 * </p> 11185 * 11186 * <p> 11187 * The animation starts only if at least one of the scrollbars is enabled, 11188 * as specified by {@link #isHorizontalScrollBarEnabled()} and 11189 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11190 * this method returns true, and false otherwise. If the animation is 11191 * started, this method calls {@link #invalidate()}; in that case the caller 11192 * should not call {@link #invalidate()}. 11193 * </p> 11194 * 11195 * <p> 11196 * This method should be invoked everytime a subclass directly updates the 11197 * scroll parameters. 11198 * </p> 11199 * 11200 * @param startDelay the delay, in milliseconds, after which the animation 11201 * should start; when the delay is 0, the animation starts 11202 * immediately 11203 * @return true if the animation is played, false otherwise 11204 * 11205 * @see #scrollBy(int, int) 11206 * @see #scrollTo(int, int) 11207 * @see #isHorizontalScrollBarEnabled() 11208 * @see #isVerticalScrollBarEnabled() 11209 * @see #setHorizontalScrollBarEnabled(boolean) 11210 * @see #setVerticalScrollBarEnabled(boolean) 11211 */ 11212 protected boolean awakenScrollBars(int startDelay) { 11213 return awakenScrollBars(startDelay, true); 11214 } 11215 11216 /** 11217 * <p> 11218 * Trigger the scrollbars to draw. When invoked this method starts an 11219 * animation to fade the scrollbars out after a fixed delay. If a subclass 11220 * provides animated scrolling, the start delay should equal the duration of 11221 * the scrolling animation. 11222 * </p> 11223 * 11224 * <p> 11225 * The animation starts only if at least one of the scrollbars is enabled, 11226 * as specified by {@link #isHorizontalScrollBarEnabled()} and 11227 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11228 * this method returns true, and false otherwise. If the animation is 11229 * started, this method calls {@link #invalidate()} if the invalidate parameter 11230 * is set to true; in that case the caller 11231 * should not call {@link #invalidate()}. 11232 * </p> 11233 * 11234 * <p> 11235 * This method should be invoked everytime a subclass directly updates the 11236 * scroll parameters. 11237 * </p> 11238 * 11239 * @param startDelay the delay, in milliseconds, after which the animation 11240 * should start; when the delay is 0, the animation starts 11241 * immediately 11242 * 11243 * @param invalidate Wheter this method should call invalidate 11244 * 11245 * @return true if the animation is played, false otherwise 11246 * 11247 * @see #scrollBy(int, int) 11248 * @see #scrollTo(int, int) 11249 * @see #isHorizontalScrollBarEnabled() 11250 * @see #isVerticalScrollBarEnabled() 11251 * @see #setHorizontalScrollBarEnabled(boolean) 11252 * @see #setVerticalScrollBarEnabled(boolean) 11253 */ 11254 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 11255 final ScrollabilityCache scrollCache = mScrollCache; 11256 11257 if (scrollCache == null || !scrollCache.fadeScrollBars) { 11258 return false; 11259 } 11260 11261 if (scrollCache.scrollBar == null) { 11262 scrollCache.scrollBar = new ScrollBarDrawable(); 11263 } 11264 11265 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 11266 11267 if (invalidate) { 11268 // Invalidate to show the scrollbars 11269 postInvalidateOnAnimation(); 11270 } 11271 11272 if (scrollCache.state == ScrollabilityCache.OFF) { 11273 // FIXME: this is copied from WindowManagerService. 11274 // We should get this value from the system when it 11275 // is possible to do so. 11276 final int KEY_REPEAT_FIRST_DELAY = 750; 11277 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 11278 } 11279 11280 // Tell mScrollCache when we should start fading. This may 11281 // extend the fade start time if one was already scheduled 11282 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 11283 scrollCache.fadeStartTime = fadeStartTime; 11284 scrollCache.state = ScrollabilityCache.ON; 11285 11286 // Schedule our fader to run, unscheduling any old ones first 11287 if (mAttachInfo != null) { 11288 mAttachInfo.mHandler.removeCallbacks(scrollCache); 11289 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 11290 } 11291 11292 return true; 11293 } 11294 11295 return false; 11296 } 11297 11298 /** 11299 * Do not invalidate views which are not visible and which are not running an animation. They 11300 * will not get drawn and they should not set dirty flags as if they will be drawn 11301 */ 11302 private boolean skipInvalidate() { 11303 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 11304 (!(mParent instanceof ViewGroup) || 11305 !((ViewGroup) mParent).isViewTransitioning(this)); 11306 } 11307 11308 /** 11309 * Mark the area defined by dirty as needing to be drawn. If the view is 11310 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 11311 * point in the future. 11312 * <p> 11313 * This must be called from a UI thread. To call from a non-UI thread, call 11314 * {@link #postInvalidate()}. 11315 * <p> 11316 * <b>WARNING:</b> In API 19 and below, this method may be destructive to 11317 * {@code dirty}. 11318 * 11319 * @param dirty the rectangle representing the bounds of the dirty region 11320 */ 11321 public void invalidate(Rect dirty) { 11322 final int scrollX = mScrollX; 11323 final int scrollY = mScrollY; 11324 invalidateInternal(dirty.left - scrollX, dirty.top - scrollY, 11325 dirty.right - scrollX, dirty.bottom - scrollY, true, false); 11326 } 11327 11328 /** 11329 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The 11330 * coordinates of the dirty rect are relative to the view. If the view is 11331 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 11332 * point in the future. 11333 * <p> 11334 * This must be called from a UI thread. To call from a non-UI thread, call 11335 * {@link #postInvalidate()}. 11336 * 11337 * @param l the left position of the dirty region 11338 * @param t the top position of the dirty region 11339 * @param r the right position of the dirty region 11340 * @param b the bottom position of the dirty region 11341 */ 11342 public void invalidate(int l, int t, int r, int b) { 11343 final int scrollX = mScrollX; 11344 final int scrollY = mScrollY; 11345 invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false); 11346 } 11347 11348 /** 11349 * Invalidate the whole view. If the view is visible, 11350 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 11351 * the future. 11352 * <p> 11353 * This must be called from a UI thread. To call from a non-UI thread, call 11354 * {@link #postInvalidate()}. 11355 */ 11356 public void invalidate() { 11357 invalidate(true); 11358 } 11359 11360 /** 11361 * This is where the invalidate() work actually happens. A full invalidate() 11362 * causes the drawing cache to be invalidated, but this function can be 11363 * called with invalidateCache set to false to skip that invalidation step 11364 * for cases that do not need it (for example, a component that remains at 11365 * the same dimensions with the same content). 11366 * 11367 * @param invalidateCache Whether the drawing cache for this view should be 11368 * invalidated as well. This is usually true for a full 11369 * invalidate, but may be set to false if the View's contents or 11370 * dimensions have not changed. 11371 */ 11372 void invalidate(boolean invalidateCache) { 11373 invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true); 11374 } 11375 11376 void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache, 11377 boolean fullInvalidate) { 11378 if (mGhostView != null) { 11379 mGhostView.invalidate(invalidateCache); 11380 return; 11381 } 11382 11383 if (skipInvalidate()) { 11384 return; 11385 } 11386 11387 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) 11388 || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) 11389 || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED 11390 || (fullInvalidate && isOpaque() != mLastIsOpaque)) { 11391 if (fullInvalidate) { 11392 mLastIsOpaque = isOpaque(); 11393 mPrivateFlags &= ~PFLAG_DRAWN; 11394 } 11395 11396 mPrivateFlags |= PFLAG_DIRTY; 11397 11398 if (invalidateCache) { 11399 mPrivateFlags |= PFLAG_INVALIDATED; 11400 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 11401 } 11402 11403 // Propagate the damage rectangle to the parent view. 11404 final AttachInfo ai = mAttachInfo; 11405 final ViewParent p = mParent; 11406 if (p != null && ai != null && l < r && t < b) { 11407 final Rect damage = ai.mTmpInvalRect; 11408 damage.set(l, t, r, b); 11409 p.invalidateChild(this, damage); 11410 } 11411 11412 // Damage the entire projection receiver, if necessary. 11413 if (mBackground != null && mBackground.isProjected()) { 11414 final View receiver = getProjectionReceiver(); 11415 if (receiver != null) { 11416 receiver.damageInParent(); 11417 } 11418 } 11419 11420 // Damage the entire IsolatedZVolume receiving this view's shadow. 11421 if (isHardwareAccelerated() && getZ() != 0) { 11422 damageShadowReceiver(); 11423 } 11424 } 11425 } 11426 11427 /** 11428 * @return this view's projection receiver, or {@code null} if none exists 11429 */ 11430 private View getProjectionReceiver() { 11431 ViewParent p = getParent(); 11432 while (p != null && p instanceof View) { 11433 final View v = (View) p; 11434 if (v.isProjectionReceiver()) { 11435 return v; 11436 } 11437 p = p.getParent(); 11438 } 11439 11440 return null; 11441 } 11442 11443 /** 11444 * @return whether the view is a projection receiver 11445 */ 11446 private boolean isProjectionReceiver() { 11447 return mBackground != null; 11448 } 11449 11450 /** 11451 * Damage area of the screen that can be covered by this View's shadow. 11452 * 11453 * This method will guarantee that any changes to shadows cast by a View 11454 * are damaged on the screen for future redraw. 11455 */ 11456 private void damageShadowReceiver() { 11457 final AttachInfo ai = mAttachInfo; 11458 if (ai != null) { 11459 ViewParent p = getParent(); 11460 if (p != null && p instanceof ViewGroup) { 11461 final ViewGroup vg = (ViewGroup) p; 11462 vg.damageInParent(); 11463 } 11464 } 11465 } 11466 11467 /** 11468 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 11469 * set any flags or handle all of the cases handled by the default invalidation methods. 11470 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 11471 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 11472 * walk up the hierarchy, transforming the dirty rect as necessary. 11473 * 11474 * The method also handles normal invalidation logic if display list properties are not 11475 * being used in this view. The invalidateParent and forceRedraw flags are used by that 11476 * backup approach, to handle these cases used in the various property-setting methods. 11477 * 11478 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 11479 * are not being used in this view 11480 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 11481 * list properties are not being used in this view 11482 */ 11483 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 11484 if (!isHardwareAccelerated() 11485 || !mRenderNode.isValid() 11486 || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) { 11487 if (invalidateParent) { 11488 invalidateParentCaches(); 11489 } 11490 if (forceRedraw) { 11491 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 11492 } 11493 invalidate(false); 11494 } else { 11495 damageInParent(); 11496 } 11497 if (isHardwareAccelerated() && invalidateParent && getZ() != 0) { 11498 damageShadowReceiver(); 11499 } 11500 } 11501 11502 /** 11503 * Tells the parent view to damage this view's bounds. 11504 * 11505 * @hide 11506 */ 11507 protected void damageInParent() { 11508 final AttachInfo ai = mAttachInfo; 11509 final ViewParent p = mParent; 11510 if (p != null && ai != null) { 11511 final Rect r = ai.mTmpInvalRect; 11512 r.set(0, 0, mRight - mLeft, mBottom - mTop); 11513 if (mParent instanceof ViewGroup) { 11514 ((ViewGroup) mParent).damageChild(this, r); 11515 } else { 11516 mParent.invalidateChild(this, r); 11517 } 11518 } 11519 } 11520 11521 /** 11522 * Utility method to transform a given Rect by the current matrix of this view. 11523 */ 11524 void transformRect(final Rect rect) { 11525 if (!getMatrix().isIdentity()) { 11526 RectF boundingRect = mAttachInfo.mTmpTransformRect; 11527 boundingRect.set(rect); 11528 getMatrix().mapRect(boundingRect); 11529 rect.set((int) Math.floor(boundingRect.left), 11530 (int) Math.floor(boundingRect.top), 11531 (int) Math.ceil(boundingRect.right), 11532 (int) Math.ceil(boundingRect.bottom)); 11533 } 11534 } 11535 11536 /** 11537 * Used to indicate that the parent of this view should clear its caches. This functionality 11538 * is used to force the parent to rebuild its display list (when hardware-accelerated), 11539 * which is necessary when various parent-managed properties of the view change, such as 11540 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 11541 * clears the parent caches and does not causes an invalidate event. 11542 * 11543 * @hide 11544 */ 11545 protected void invalidateParentCaches() { 11546 if (mParent instanceof View) { 11547 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 11548 } 11549 } 11550 11551 /** 11552 * Used to indicate that the parent of this view should be invalidated. This functionality 11553 * is used to force the parent to rebuild its display list (when hardware-accelerated), 11554 * which is necessary when various parent-managed properties of the view change, such as 11555 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 11556 * an invalidation event to the parent. 11557 * 11558 * @hide 11559 */ 11560 protected void invalidateParentIfNeeded() { 11561 if (isHardwareAccelerated() && mParent instanceof View) { 11562 ((View) mParent).invalidate(true); 11563 } 11564 } 11565 11566 /** 11567 * @hide 11568 */ 11569 protected void invalidateParentIfNeededAndWasQuickRejected() { 11570 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) { 11571 // View was rejected last time it was drawn by its parent; this may have changed 11572 invalidateParentIfNeeded(); 11573 } 11574 } 11575 11576 /** 11577 * Indicates whether this View is opaque. An opaque View guarantees that it will 11578 * draw all the pixels overlapping its bounds using a fully opaque color. 11579 * 11580 * Subclasses of View should override this method whenever possible to indicate 11581 * whether an instance is opaque. Opaque Views are treated in a special way by 11582 * the View hierarchy, possibly allowing it to perform optimizations during 11583 * invalidate/draw passes. 11584 * 11585 * @return True if this View is guaranteed to be fully opaque, false otherwise. 11586 */ 11587 @ViewDebug.ExportedProperty(category = "drawing") 11588 public boolean isOpaque() { 11589 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 11590 getFinalAlpha() >= 1.0f; 11591 } 11592 11593 /** 11594 * @hide 11595 */ 11596 protected void computeOpaqueFlags() { 11597 // Opaque if: 11598 // - Has a background 11599 // - Background is opaque 11600 // - Doesn't have scrollbars or scrollbars overlay 11601 11602 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 11603 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 11604 } else { 11605 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 11606 } 11607 11608 final int flags = mViewFlags; 11609 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 11610 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY || 11611 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) { 11612 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 11613 } else { 11614 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 11615 } 11616 } 11617 11618 /** 11619 * @hide 11620 */ 11621 protected boolean hasOpaqueScrollbars() { 11622 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 11623 } 11624 11625 /** 11626 * @return A handler associated with the thread running the View. This 11627 * handler can be used to pump events in the UI events queue. 11628 */ 11629 public Handler getHandler() { 11630 final AttachInfo attachInfo = mAttachInfo; 11631 if (attachInfo != null) { 11632 return attachInfo.mHandler; 11633 } 11634 return null; 11635 } 11636 11637 /** 11638 * Gets the view root associated with the View. 11639 * @return The view root, or null if none. 11640 * @hide 11641 */ 11642 public ViewRootImpl getViewRootImpl() { 11643 if (mAttachInfo != null) { 11644 return mAttachInfo.mViewRootImpl; 11645 } 11646 return null; 11647 } 11648 11649 /** 11650 * @hide 11651 */ 11652 public HardwareRenderer getHardwareRenderer() { 11653 return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null; 11654 } 11655 11656 /** 11657 * <p>Causes the Runnable to be added to the message queue. 11658 * The runnable will be run on the user interface thread.</p> 11659 * 11660 * @param action The Runnable that will be executed. 11661 * 11662 * @return Returns true if the Runnable was successfully placed in to the 11663 * message queue. Returns false on failure, usually because the 11664 * looper processing the message queue is exiting. 11665 * 11666 * @see #postDelayed 11667 * @see #removeCallbacks 11668 */ 11669 public boolean post(Runnable action) { 11670 final AttachInfo attachInfo = mAttachInfo; 11671 if (attachInfo != null) { 11672 return attachInfo.mHandler.post(action); 11673 } 11674 // Assume that post will succeed later 11675 ViewRootImpl.getRunQueue().post(action); 11676 return true; 11677 } 11678 11679 /** 11680 * <p>Causes the Runnable to be added to the message queue, to be run 11681 * after the specified amount of time elapses. 11682 * The runnable will be run on the user interface thread.</p> 11683 * 11684 * @param action The Runnable that will be executed. 11685 * @param delayMillis The delay (in milliseconds) until the Runnable 11686 * will be executed. 11687 * 11688 * @return true if the Runnable was successfully placed in to the 11689 * message queue. Returns false on failure, usually because the 11690 * looper processing the message queue is exiting. Note that a 11691 * result of true does not mean the Runnable will be processed -- 11692 * if the looper is quit before the delivery time of the message 11693 * occurs then the message will be dropped. 11694 * 11695 * @see #post 11696 * @see #removeCallbacks 11697 */ 11698 public boolean postDelayed(Runnable action, long delayMillis) { 11699 final AttachInfo attachInfo = mAttachInfo; 11700 if (attachInfo != null) { 11701 return attachInfo.mHandler.postDelayed(action, delayMillis); 11702 } 11703 // Assume that post will succeed later 11704 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 11705 return true; 11706 } 11707 11708 /** 11709 * <p>Causes the Runnable to execute on the next animation time step. 11710 * The runnable will be run on the user interface thread.</p> 11711 * 11712 * @param action The Runnable that will be executed. 11713 * 11714 * @see #postOnAnimationDelayed 11715 * @see #removeCallbacks 11716 */ 11717 public void postOnAnimation(Runnable action) { 11718 final AttachInfo attachInfo = mAttachInfo; 11719 if (attachInfo != null) { 11720 attachInfo.mViewRootImpl.mChoreographer.postCallback( 11721 Choreographer.CALLBACK_ANIMATION, action, null); 11722 } else { 11723 // Assume that post will succeed later 11724 ViewRootImpl.getRunQueue().post(action); 11725 } 11726 } 11727 11728 /** 11729 * <p>Causes the Runnable to execute on the next animation time step, 11730 * after the specified amount of time elapses. 11731 * The runnable will be run on the user interface thread.</p> 11732 * 11733 * @param action The Runnable that will be executed. 11734 * @param delayMillis The delay (in milliseconds) until the Runnable 11735 * will be executed. 11736 * 11737 * @see #postOnAnimation 11738 * @see #removeCallbacks 11739 */ 11740 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 11741 final AttachInfo attachInfo = mAttachInfo; 11742 if (attachInfo != null) { 11743 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 11744 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 11745 } else { 11746 // Assume that post will succeed later 11747 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 11748 } 11749 } 11750 11751 /** 11752 * <p>Removes the specified Runnable from the message queue.</p> 11753 * 11754 * @param action The Runnable to remove from the message handling queue 11755 * 11756 * @return true if this view could ask the Handler to remove the Runnable, 11757 * false otherwise. When the returned value is true, the Runnable 11758 * may or may not have been actually removed from the message queue 11759 * (for instance, if the Runnable was not in the queue already.) 11760 * 11761 * @see #post 11762 * @see #postDelayed 11763 * @see #postOnAnimation 11764 * @see #postOnAnimationDelayed 11765 */ 11766 public boolean removeCallbacks(Runnable action) { 11767 if (action != null) { 11768 final AttachInfo attachInfo = mAttachInfo; 11769 if (attachInfo != null) { 11770 attachInfo.mHandler.removeCallbacks(action); 11771 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 11772 Choreographer.CALLBACK_ANIMATION, action, null); 11773 } 11774 // Assume that post will succeed later 11775 ViewRootImpl.getRunQueue().removeCallbacks(action); 11776 } 11777 return true; 11778 } 11779 11780 /** 11781 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 11782 * Use this to invalidate the View from a non-UI thread.</p> 11783 * 11784 * <p>This method can be invoked from outside of the UI thread 11785 * only when this View is attached to a window.</p> 11786 * 11787 * @see #invalidate() 11788 * @see #postInvalidateDelayed(long) 11789 */ 11790 public void postInvalidate() { 11791 postInvalidateDelayed(0); 11792 } 11793 11794 /** 11795 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 11796 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 11797 * 11798 * <p>This method can be invoked from outside of the UI thread 11799 * only when this View is attached to a window.</p> 11800 * 11801 * @param left The left coordinate of the rectangle to invalidate. 11802 * @param top The top coordinate of the rectangle to invalidate. 11803 * @param right The right coordinate of the rectangle to invalidate. 11804 * @param bottom The bottom coordinate of the rectangle to invalidate. 11805 * 11806 * @see #invalidate(int, int, int, int) 11807 * @see #invalidate(Rect) 11808 * @see #postInvalidateDelayed(long, int, int, int, int) 11809 */ 11810 public void postInvalidate(int left, int top, int right, int bottom) { 11811 postInvalidateDelayed(0, left, top, right, bottom); 11812 } 11813 11814 /** 11815 * <p>Cause an invalidate to happen on a subsequent cycle through the event 11816 * loop. Waits for the specified amount of time.</p> 11817 * 11818 * <p>This method can be invoked from outside of the UI thread 11819 * only when this View is attached to a window.</p> 11820 * 11821 * @param delayMilliseconds the duration in milliseconds to delay the 11822 * invalidation by 11823 * 11824 * @see #invalidate() 11825 * @see #postInvalidate() 11826 */ 11827 public void postInvalidateDelayed(long delayMilliseconds) { 11828 // We try only with the AttachInfo because there's no point in invalidating 11829 // if we are not attached to our window 11830 final AttachInfo attachInfo = mAttachInfo; 11831 if (attachInfo != null) { 11832 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 11833 } 11834 } 11835 11836 /** 11837 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 11838 * through the event loop. Waits for the specified amount of time.</p> 11839 * 11840 * <p>This method can be invoked from outside of the UI thread 11841 * only when this View is attached to a window.</p> 11842 * 11843 * @param delayMilliseconds the duration in milliseconds to delay the 11844 * invalidation by 11845 * @param left The left coordinate of the rectangle to invalidate. 11846 * @param top The top coordinate of the rectangle to invalidate. 11847 * @param right The right coordinate of the rectangle to invalidate. 11848 * @param bottom The bottom coordinate of the rectangle to invalidate. 11849 * 11850 * @see #invalidate(int, int, int, int) 11851 * @see #invalidate(Rect) 11852 * @see #postInvalidate(int, int, int, int) 11853 */ 11854 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 11855 int right, int bottom) { 11856 11857 // We try only with the AttachInfo because there's no point in invalidating 11858 // if we are not attached to our window 11859 final AttachInfo attachInfo = mAttachInfo; 11860 if (attachInfo != null) { 11861 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 11862 info.target = this; 11863 info.left = left; 11864 info.top = top; 11865 info.right = right; 11866 info.bottom = bottom; 11867 11868 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 11869 } 11870 } 11871 11872 /** 11873 * <p>Cause an invalidate to happen on the next animation time step, typically the 11874 * next display frame.</p> 11875 * 11876 * <p>This method can be invoked from outside of the UI thread 11877 * only when this View is attached to a window.</p> 11878 * 11879 * @see #invalidate() 11880 */ 11881 public void postInvalidateOnAnimation() { 11882 // We try only with the AttachInfo because there's no point in invalidating 11883 // if we are not attached to our window 11884 final AttachInfo attachInfo = mAttachInfo; 11885 if (attachInfo != null) { 11886 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 11887 } 11888 } 11889 11890 /** 11891 * <p>Cause an invalidate of the specified area to happen on the next animation 11892 * time step, typically the next display frame.</p> 11893 * 11894 * <p>This method can be invoked from outside of the UI thread 11895 * only when this View is attached to a window.</p> 11896 * 11897 * @param left The left coordinate of the rectangle to invalidate. 11898 * @param top The top coordinate of the rectangle to invalidate. 11899 * @param right The right coordinate of the rectangle to invalidate. 11900 * @param bottom The bottom coordinate of the rectangle to invalidate. 11901 * 11902 * @see #invalidate(int, int, int, int) 11903 * @see #invalidate(Rect) 11904 */ 11905 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 11906 // We try only with the AttachInfo because there's no point in invalidating 11907 // if we are not attached to our window 11908 final AttachInfo attachInfo = mAttachInfo; 11909 if (attachInfo != null) { 11910 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 11911 info.target = this; 11912 info.left = left; 11913 info.top = top; 11914 info.right = right; 11915 info.bottom = bottom; 11916 11917 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 11918 } 11919 } 11920 11921 /** 11922 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 11923 * This event is sent at most once every 11924 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 11925 */ 11926 private void postSendViewScrolledAccessibilityEventCallback() { 11927 if (mSendViewScrolledAccessibilityEvent == null) { 11928 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 11929 } 11930 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 11931 mSendViewScrolledAccessibilityEvent.mIsPending = true; 11932 postDelayed(mSendViewScrolledAccessibilityEvent, 11933 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 11934 } 11935 } 11936 11937 /** 11938 * Called by a parent to request that a child update its values for mScrollX 11939 * and mScrollY if necessary. This will typically be done if the child is 11940 * animating a scroll using a {@link android.widget.Scroller Scroller} 11941 * object. 11942 */ 11943 public void computeScroll() { 11944 } 11945 11946 /** 11947 * <p>Indicate whether the horizontal edges are faded when the view is 11948 * scrolled horizontally.</p> 11949 * 11950 * @return true if the horizontal edges should are faded on scroll, false 11951 * otherwise 11952 * 11953 * @see #setHorizontalFadingEdgeEnabled(boolean) 11954 * 11955 * @attr ref android.R.styleable#View_requiresFadingEdge 11956 */ 11957 public boolean isHorizontalFadingEdgeEnabled() { 11958 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 11959 } 11960 11961 /** 11962 * <p>Define whether the horizontal edges should be faded when this view 11963 * is scrolled horizontally.</p> 11964 * 11965 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 11966 * be faded when the view is scrolled 11967 * horizontally 11968 * 11969 * @see #isHorizontalFadingEdgeEnabled() 11970 * 11971 * @attr ref android.R.styleable#View_requiresFadingEdge 11972 */ 11973 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 11974 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 11975 if (horizontalFadingEdgeEnabled) { 11976 initScrollCache(); 11977 } 11978 11979 mViewFlags ^= FADING_EDGE_HORIZONTAL; 11980 } 11981 } 11982 11983 /** 11984 * <p>Indicate whether the vertical edges are faded when the view is 11985 * scrolled horizontally.</p> 11986 * 11987 * @return true if the vertical edges should are faded on scroll, false 11988 * otherwise 11989 * 11990 * @see #setVerticalFadingEdgeEnabled(boolean) 11991 * 11992 * @attr ref android.R.styleable#View_requiresFadingEdge 11993 */ 11994 public boolean isVerticalFadingEdgeEnabled() { 11995 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 11996 } 11997 11998 /** 11999 * <p>Define whether the vertical edges should be faded when this view 12000 * is scrolled vertically.</p> 12001 * 12002 * @param verticalFadingEdgeEnabled true if the vertical edges should 12003 * be faded when the view is scrolled 12004 * vertically 12005 * 12006 * @see #isVerticalFadingEdgeEnabled() 12007 * 12008 * @attr ref android.R.styleable#View_requiresFadingEdge 12009 */ 12010 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 12011 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 12012 if (verticalFadingEdgeEnabled) { 12013 initScrollCache(); 12014 } 12015 12016 mViewFlags ^= FADING_EDGE_VERTICAL; 12017 } 12018 } 12019 12020 /** 12021 * Returns the strength, or intensity, of the top faded edge. The strength is 12022 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12023 * returns 0.0 or 1.0 but no value in between. 12024 * 12025 * Subclasses should override this method to provide a smoother fade transition 12026 * when scrolling occurs. 12027 * 12028 * @return the intensity of the top fade as a float between 0.0f and 1.0f 12029 */ 12030 protected float getTopFadingEdgeStrength() { 12031 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 12032 } 12033 12034 /** 12035 * Returns the strength, or intensity, of the bottom faded edge. The strength is 12036 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12037 * returns 0.0 or 1.0 but no value in between. 12038 * 12039 * Subclasses should override this method to provide a smoother fade transition 12040 * when scrolling occurs. 12041 * 12042 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 12043 */ 12044 protected float getBottomFadingEdgeStrength() { 12045 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 12046 computeVerticalScrollRange() ? 1.0f : 0.0f; 12047 } 12048 12049 /** 12050 * Returns the strength, or intensity, of the left faded edge. The strength is 12051 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12052 * returns 0.0 or 1.0 but no value in between. 12053 * 12054 * Subclasses should override this method to provide a smoother fade transition 12055 * when scrolling occurs. 12056 * 12057 * @return the intensity of the left fade as a float between 0.0f and 1.0f 12058 */ 12059 protected float getLeftFadingEdgeStrength() { 12060 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 12061 } 12062 12063 /** 12064 * Returns the strength, or intensity, of the right faded edge. The strength is 12065 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12066 * returns 0.0 or 1.0 but no value in between. 12067 * 12068 * Subclasses should override this method to provide a smoother fade transition 12069 * when scrolling occurs. 12070 * 12071 * @return the intensity of the right fade as a float between 0.0f and 1.0f 12072 */ 12073 protected float getRightFadingEdgeStrength() { 12074 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 12075 computeHorizontalScrollRange() ? 1.0f : 0.0f; 12076 } 12077 12078 /** 12079 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 12080 * scrollbar is not drawn by default.</p> 12081 * 12082 * @return true if the horizontal scrollbar should be painted, false 12083 * otherwise 12084 * 12085 * @see #setHorizontalScrollBarEnabled(boolean) 12086 */ 12087 public boolean isHorizontalScrollBarEnabled() { 12088 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 12089 } 12090 12091 /** 12092 * <p>Define whether the horizontal scrollbar should be drawn or not. The 12093 * scrollbar is not drawn by default.</p> 12094 * 12095 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 12096 * be painted 12097 * 12098 * @see #isHorizontalScrollBarEnabled() 12099 */ 12100 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 12101 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 12102 mViewFlags ^= SCROLLBARS_HORIZONTAL; 12103 computeOpaqueFlags(); 12104 resolvePadding(); 12105 } 12106 } 12107 12108 /** 12109 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 12110 * scrollbar is not drawn by default.</p> 12111 * 12112 * @return true if the vertical scrollbar should be painted, false 12113 * otherwise 12114 * 12115 * @see #setVerticalScrollBarEnabled(boolean) 12116 */ 12117 public boolean isVerticalScrollBarEnabled() { 12118 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 12119 } 12120 12121 /** 12122 * <p>Define whether the vertical scrollbar should be drawn or not. The 12123 * scrollbar is not drawn by default.</p> 12124 * 12125 * @param verticalScrollBarEnabled true if the vertical scrollbar should 12126 * be painted 12127 * 12128 * @see #isVerticalScrollBarEnabled() 12129 */ 12130 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 12131 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 12132 mViewFlags ^= SCROLLBARS_VERTICAL; 12133 computeOpaqueFlags(); 12134 resolvePadding(); 12135 } 12136 } 12137 12138 /** 12139 * @hide 12140 */ 12141 protected void recomputePadding() { 12142 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 12143 } 12144 12145 /** 12146 * Define whether scrollbars will fade when the view is not scrolling. 12147 * 12148 * @param fadeScrollbars wheter to enable fading 12149 * 12150 * @attr ref android.R.styleable#View_fadeScrollbars 12151 */ 12152 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 12153 initScrollCache(); 12154 final ScrollabilityCache scrollabilityCache = mScrollCache; 12155 scrollabilityCache.fadeScrollBars = fadeScrollbars; 12156 if (fadeScrollbars) { 12157 scrollabilityCache.state = ScrollabilityCache.OFF; 12158 } else { 12159 scrollabilityCache.state = ScrollabilityCache.ON; 12160 } 12161 } 12162 12163 /** 12164 * 12165 * Returns true if scrollbars will fade when this view is not scrolling 12166 * 12167 * @return true if scrollbar fading is enabled 12168 * 12169 * @attr ref android.R.styleable#View_fadeScrollbars 12170 */ 12171 public boolean isScrollbarFadingEnabled() { 12172 return mScrollCache != null && mScrollCache.fadeScrollBars; 12173 } 12174 12175 /** 12176 * 12177 * Returns the delay before scrollbars fade. 12178 * 12179 * @return the delay before scrollbars fade 12180 * 12181 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 12182 */ 12183 public int getScrollBarDefaultDelayBeforeFade() { 12184 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 12185 mScrollCache.scrollBarDefaultDelayBeforeFade; 12186 } 12187 12188 /** 12189 * Define the delay before scrollbars fade. 12190 * 12191 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 12192 * 12193 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 12194 */ 12195 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 12196 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 12197 } 12198 12199 /** 12200 * 12201 * Returns the scrollbar fade duration. 12202 * 12203 * @return the scrollbar fade duration 12204 * 12205 * @attr ref android.R.styleable#View_scrollbarFadeDuration 12206 */ 12207 public int getScrollBarFadeDuration() { 12208 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 12209 mScrollCache.scrollBarFadeDuration; 12210 } 12211 12212 /** 12213 * Define the scrollbar fade duration. 12214 * 12215 * @param scrollBarFadeDuration - the scrollbar fade duration 12216 * 12217 * @attr ref android.R.styleable#View_scrollbarFadeDuration 12218 */ 12219 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 12220 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 12221 } 12222 12223 /** 12224 * 12225 * Returns the scrollbar size. 12226 * 12227 * @return the scrollbar size 12228 * 12229 * @attr ref android.R.styleable#View_scrollbarSize 12230 */ 12231 public int getScrollBarSize() { 12232 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 12233 mScrollCache.scrollBarSize; 12234 } 12235 12236 /** 12237 * Define the scrollbar size. 12238 * 12239 * @param scrollBarSize - the scrollbar size 12240 * 12241 * @attr ref android.R.styleable#View_scrollbarSize 12242 */ 12243 public void setScrollBarSize(int scrollBarSize) { 12244 getScrollCache().scrollBarSize = scrollBarSize; 12245 } 12246 12247 /** 12248 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 12249 * inset. When inset, they add to the padding of the view. And the scrollbars 12250 * can be drawn inside the padding area or on the edge of the view. For example, 12251 * if a view has a background drawable and you want to draw the scrollbars 12252 * inside the padding specified by the drawable, you can use 12253 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 12254 * appear at the edge of the view, ignoring the padding, then you can use 12255 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 12256 * @param style the style of the scrollbars. Should be one of 12257 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 12258 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 12259 * @see #SCROLLBARS_INSIDE_OVERLAY 12260 * @see #SCROLLBARS_INSIDE_INSET 12261 * @see #SCROLLBARS_OUTSIDE_OVERLAY 12262 * @see #SCROLLBARS_OUTSIDE_INSET 12263 * 12264 * @attr ref android.R.styleable#View_scrollbarStyle 12265 */ 12266 public void setScrollBarStyle(@ScrollBarStyle int style) { 12267 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 12268 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 12269 computeOpaqueFlags(); 12270 resolvePadding(); 12271 } 12272 } 12273 12274 /** 12275 * <p>Returns the current scrollbar style.</p> 12276 * @return the current scrollbar style 12277 * @see #SCROLLBARS_INSIDE_OVERLAY 12278 * @see #SCROLLBARS_INSIDE_INSET 12279 * @see #SCROLLBARS_OUTSIDE_OVERLAY 12280 * @see #SCROLLBARS_OUTSIDE_INSET 12281 * 12282 * @attr ref android.R.styleable#View_scrollbarStyle 12283 */ 12284 @ViewDebug.ExportedProperty(mapping = { 12285 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 12286 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 12287 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 12288 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 12289 }) 12290 @ScrollBarStyle 12291 public int getScrollBarStyle() { 12292 return mViewFlags & SCROLLBARS_STYLE_MASK; 12293 } 12294 12295 /** 12296 * <p>Compute the horizontal range that the horizontal scrollbar 12297 * represents.</p> 12298 * 12299 * <p>The range is expressed in arbitrary units that must be the same as the 12300 * units used by {@link #computeHorizontalScrollExtent()} and 12301 * {@link #computeHorizontalScrollOffset()}.</p> 12302 * 12303 * <p>The default range is the drawing width of this view.</p> 12304 * 12305 * @return the total horizontal range represented by the horizontal 12306 * scrollbar 12307 * 12308 * @see #computeHorizontalScrollExtent() 12309 * @see #computeHorizontalScrollOffset() 12310 * @see android.widget.ScrollBarDrawable 12311 */ 12312 protected int computeHorizontalScrollRange() { 12313 return getWidth(); 12314 } 12315 12316 /** 12317 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 12318 * within the horizontal range. This value is used to compute the position 12319 * of the thumb within the scrollbar's track.</p> 12320 * 12321 * <p>The range is expressed in arbitrary units that must be the same as the 12322 * units used by {@link #computeHorizontalScrollRange()} and 12323 * {@link #computeHorizontalScrollExtent()}.</p> 12324 * 12325 * <p>The default offset is the scroll offset of this view.</p> 12326 * 12327 * @return the horizontal offset of the scrollbar's thumb 12328 * 12329 * @see #computeHorizontalScrollRange() 12330 * @see #computeHorizontalScrollExtent() 12331 * @see android.widget.ScrollBarDrawable 12332 */ 12333 protected int computeHorizontalScrollOffset() { 12334 return mScrollX; 12335 } 12336 12337 /** 12338 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 12339 * within the horizontal range. This value is used to compute the length 12340 * of the thumb within the scrollbar's track.</p> 12341 * 12342 * <p>The range is expressed in arbitrary units that must be the same as the 12343 * units used by {@link #computeHorizontalScrollRange()} and 12344 * {@link #computeHorizontalScrollOffset()}.</p> 12345 * 12346 * <p>The default extent is the drawing width of this view.</p> 12347 * 12348 * @return the horizontal extent of the scrollbar's thumb 12349 * 12350 * @see #computeHorizontalScrollRange() 12351 * @see #computeHorizontalScrollOffset() 12352 * @see android.widget.ScrollBarDrawable 12353 */ 12354 protected int computeHorizontalScrollExtent() { 12355 return getWidth(); 12356 } 12357 12358 /** 12359 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 12360 * 12361 * <p>The range is expressed in arbitrary units that must be the same as the 12362 * units used by {@link #computeVerticalScrollExtent()} and 12363 * {@link #computeVerticalScrollOffset()}.</p> 12364 * 12365 * @return the total vertical range represented by the vertical scrollbar 12366 * 12367 * <p>The default range is the drawing height of this view.</p> 12368 * 12369 * @see #computeVerticalScrollExtent() 12370 * @see #computeVerticalScrollOffset() 12371 * @see android.widget.ScrollBarDrawable 12372 */ 12373 protected int computeVerticalScrollRange() { 12374 return getHeight(); 12375 } 12376 12377 /** 12378 * <p>Compute the vertical offset of the vertical scrollbar's thumb 12379 * within the horizontal range. This value is used to compute the position 12380 * of the thumb within the scrollbar's track.</p> 12381 * 12382 * <p>The range is expressed in arbitrary units that must be the same as the 12383 * units used by {@link #computeVerticalScrollRange()} and 12384 * {@link #computeVerticalScrollExtent()}.</p> 12385 * 12386 * <p>The default offset is the scroll offset of this view.</p> 12387 * 12388 * @return the vertical offset of the scrollbar's thumb 12389 * 12390 * @see #computeVerticalScrollRange() 12391 * @see #computeVerticalScrollExtent() 12392 * @see android.widget.ScrollBarDrawable 12393 */ 12394 protected int computeVerticalScrollOffset() { 12395 return mScrollY; 12396 } 12397 12398 /** 12399 * <p>Compute the vertical extent of the vertical scrollbar's thumb 12400 * within the vertical range. This value is used to compute the length 12401 * of the thumb within the scrollbar's track.</p> 12402 * 12403 * <p>The range is expressed in arbitrary units that must be the same as the 12404 * units used by {@link #computeVerticalScrollRange()} and 12405 * {@link #computeVerticalScrollOffset()}.</p> 12406 * 12407 * <p>The default extent is the drawing height of this view.</p> 12408 * 12409 * @return the vertical extent of the scrollbar's thumb 12410 * 12411 * @see #computeVerticalScrollRange() 12412 * @see #computeVerticalScrollOffset() 12413 * @see android.widget.ScrollBarDrawable 12414 */ 12415 protected int computeVerticalScrollExtent() { 12416 return getHeight(); 12417 } 12418 12419 /** 12420 * Check if this view can be scrolled horizontally in a certain direction. 12421 * 12422 * @param direction Negative to check scrolling left, positive to check scrolling right. 12423 * @return true if this view can be scrolled in the specified direction, false otherwise. 12424 */ 12425 public boolean canScrollHorizontally(int direction) { 12426 final int offset = computeHorizontalScrollOffset(); 12427 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 12428 if (range == 0) return false; 12429 if (direction < 0) { 12430 return offset > 0; 12431 } else { 12432 return offset < range - 1; 12433 } 12434 } 12435 12436 /** 12437 * Check if this view can be scrolled vertically in a certain direction. 12438 * 12439 * @param direction Negative to check scrolling up, positive to check scrolling down. 12440 * @return true if this view can be scrolled in the specified direction, false otherwise. 12441 */ 12442 public boolean canScrollVertically(int direction) { 12443 final int offset = computeVerticalScrollOffset(); 12444 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 12445 if (range == 0) return false; 12446 if (direction < 0) { 12447 return offset > 0; 12448 } else { 12449 return offset < range - 1; 12450 } 12451 } 12452 12453 /** 12454 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 12455 * scrollbars are painted only if they have been awakened first.</p> 12456 * 12457 * @param canvas the canvas on which to draw the scrollbars 12458 * 12459 * @see #awakenScrollBars(int) 12460 */ 12461 protected final void onDrawScrollBars(Canvas canvas) { 12462 // scrollbars are drawn only when the animation is running 12463 final ScrollabilityCache cache = mScrollCache; 12464 if (cache != null) { 12465 12466 int state = cache.state; 12467 12468 if (state == ScrollabilityCache.OFF) { 12469 return; 12470 } 12471 12472 boolean invalidate = false; 12473 12474 if (state == ScrollabilityCache.FADING) { 12475 // We're fading -- get our fade interpolation 12476 if (cache.interpolatorValues == null) { 12477 cache.interpolatorValues = new float[1]; 12478 } 12479 12480 float[] values = cache.interpolatorValues; 12481 12482 // Stops the animation if we're done 12483 if (cache.scrollBarInterpolator.timeToValues(values) == 12484 Interpolator.Result.FREEZE_END) { 12485 cache.state = ScrollabilityCache.OFF; 12486 } else { 12487 cache.scrollBar.setAlpha(Math.round(values[0])); 12488 } 12489 12490 // This will make the scroll bars inval themselves after 12491 // drawing. We only want this when we're fading so that 12492 // we prevent excessive redraws 12493 invalidate = true; 12494 } else { 12495 // We're just on -- but we may have been fading before so 12496 // reset alpha 12497 cache.scrollBar.setAlpha(255); 12498 } 12499 12500 12501 final int viewFlags = mViewFlags; 12502 12503 final boolean drawHorizontalScrollBar = 12504 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 12505 final boolean drawVerticalScrollBar = 12506 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 12507 && !isVerticalScrollBarHidden(); 12508 12509 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 12510 final int width = mRight - mLeft; 12511 final int height = mBottom - mTop; 12512 12513 final ScrollBarDrawable scrollBar = cache.scrollBar; 12514 12515 final int scrollX = mScrollX; 12516 final int scrollY = mScrollY; 12517 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 12518 12519 int left; 12520 int top; 12521 int right; 12522 int bottom; 12523 12524 if (drawHorizontalScrollBar) { 12525 int size = scrollBar.getSize(false); 12526 if (size <= 0) { 12527 size = cache.scrollBarSize; 12528 } 12529 12530 scrollBar.setParameters(computeHorizontalScrollRange(), 12531 computeHorizontalScrollOffset(), 12532 computeHorizontalScrollExtent(), false); 12533 final int verticalScrollBarGap = drawVerticalScrollBar ? 12534 getVerticalScrollbarWidth() : 0; 12535 top = scrollY + height - size - (mUserPaddingBottom & inside); 12536 left = scrollX + (mPaddingLeft & inside); 12537 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 12538 bottom = top + size; 12539 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 12540 if (invalidate) { 12541 invalidate(left, top, right, bottom); 12542 } 12543 } 12544 12545 if (drawVerticalScrollBar) { 12546 int size = scrollBar.getSize(true); 12547 if (size <= 0) { 12548 size = cache.scrollBarSize; 12549 } 12550 12551 scrollBar.setParameters(computeVerticalScrollRange(), 12552 computeVerticalScrollOffset(), 12553 computeVerticalScrollExtent(), true); 12554 int verticalScrollbarPosition = mVerticalScrollbarPosition; 12555 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 12556 verticalScrollbarPosition = isLayoutRtl() ? 12557 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 12558 } 12559 switch (verticalScrollbarPosition) { 12560 default: 12561 case SCROLLBAR_POSITION_RIGHT: 12562 left = scrollX + width - size - (mUserPaddingRight & inside); 12563 break; 12564 case SCROLLBAR_POSITION_LEFT: 12565 left = scrollX + (mUserPaddingLeft & inside); 12566 break; 12567 } 12568 top = scrollY + (mPaddingTop & inside); 12569 right = left + size; 12570 bottom = scrollY + height - (mUserPaddingBottom & inside); 12571 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 12572 if (invalidate) { 12573 invalidate(left, top, right, bottom); 12574 } 12575 } 12576 } 12577 } 12578 } 12579 12580 /** 12581 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 12582 * FastScroller is visible. 12583 * @return whether to temporarily hide the vertical scrollbar 12584 * @hide 12585 */ 12586 protected boolean isVerticalScrollBarHidden() { 12587 return false; 12588 } 12589 12590 /** 12591 * <p>Draw the horizontal scrollbar if 12592 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 12593 * 12594 * @param canvas the canvas on which to draw the scrollbar 12595 * @param scrollBar the scrollbar's drawable 12596 * 12597 * @see #isHorizontalScrollBarEnabled() 12598 * @see #computeHorizontalScrollRange() 12599 * @see #computeHorizontalScrollExtent() 12600 * @see #computeHorizontalScrollOffset() 12601 * @see android.widget.ScrollBarDrawable 12602 * @hide 12603 */ 12604 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 12605 int l, int t, int r, int b) { 12606 scrollBar.setBounds(l, t, r, b); 12607 scrollBar.draw(canvas); 12608 } 12609 12610 /** 12611 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 12612 * returns true.</p> 12613 * 12614 * @param canvas the canvas on which to draw the scrollbar 12615 * @param scrollBar the scrollbar's drawable 12616 * 12617 * @see #isVerticalScrollBarEnabled() 12618 * @see #computeVerticalScrollRange() 12619 * @see #computeVerticalScrollExtent() 12620 * @see #computeVerticalScrollOffset() 12621 * @see android.widget.ScrollBarDrawable 12622 * @hide 12623 */ 12624 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 12625 int l, int t, int r, int b) { 12626 scrollBar.setBounds(l, t, r, b); 12627 scrollBar.draw(canvas); 12628 } 12629 12630 /** 12631 * Implement this to do your drawing. 12632 * 12633 * @param canvas the canvas on which the background will be drawn 12634 */ 12635 protected void onDraw(Canvas canvas) { 12636 } 12637 12638 /* 12639 * Caller is responsible for calling requestLayout if necessary. 12640 * (This allows addViewInLayout to not request a new layout.) 12641 */ 12642 void assignParent(ViewParent parent) { 12643 if (mParent == null) { 12644 mParent = parent; 12645 } else if (parent == null) { 12646 mParent = null; 12647 } else { 12648 throw new RuntimeException("view " + this + " being added, but" 12649 + " it already has a parent"); 12650 } 12651 } 12652 12653 /** 12654 * This is called when the view is attached to a window. At this point it 12655 * has a Surface and will start drawing. Note that this function is 12656 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 12657 * however it may be called any time before the first onDraw -- including 12658 * before or after {@link #onMeasure(int, int)}. 12659 * 12660 * @see #onDetachedFromWindow() 12661 */ 12662 protected void onAttachedToWindow() { 12663 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 12664 mParent.requestTransparentRegion(this); 12665 } 12666 12667 if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 12668 initialAwakenScrollBars(); 12669 mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 12670 } 12671 12672 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 12673 12674 jumpDrawablesToCurrentState(); 12675 12676 resetSubtreeAccessibilityStateChanged(); 12677 12678 invalidateOutline(); 12679 12680 if (isFocused()) { 12681 InputMethodManager imm = InputMethodManager.peekInstance(); 12682 imm.focusIn(this); 12683 } 12684 } 12685 12686 /** 12687 * Resolve all RTL related properties. 12688 * 12689 * @return true if resolution of RTL properties has been done 12690 * 12691 * @hide 12692 */ 12693 public boolean resolveRtlPropertiesIfNeeded() { 12694 if (!needRtlPropertiesResolution()) return false; 12695 12696 // Order is important here: LayoutDirection MUST be resolved first 12697 if (!isLayoutDirectionResolved()) { 12698 resolveLayoutDirection(); 12699 resolveLayoutParams(); 12700 } 12701 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 12702 if (!isTextDirectionResolved()) { 12703 resolveTextDirection(); 12704 } 12705 if (!isTextAlignmentResolved()) { 12706 resolveTextAlignment(); 12707 } 12708 // Should resolve Drawables before Padding because we need the layout direction of the 12709 // Drawable to correctly resolve Padding. 12710 if (!isDrawablesResolved()) { 12711 resolveDrawables(); 12712 } 12713 if (!isPaddingResolved()) { 12714 resolvePadding(); 12715 } 12716 onRtlPropertiesChanged(getLayoutDirection()); 12717 return true; 12718 } 12719 12720 /** 12721 * Reset resolution of all RTL related properties. 12722 * 12723 * @hide 12724 */ 12725 public void resetRtlProperties() { 12726 resetResolvedLayoutDirection(); 12727 resetResolvedTextDirection(); 12728 resetResolvedTextAlignment(); 12729 resetResolvedPadding(); 12730 resetResolvedDrawables(); 12731 } 12732 12733 /** 12734 * @see #onScreenStateChanged(int) 12735 */ 12736 void dispatchScreenStateChanged(int screenState) { 12737 onScreenStateChanged(screenState); 12738 } 12739 12740 /** 12741 * This method is called whenever the state of the screen this view is 12742 * attached to changes. A state change will usually occurs when the screen 12743 * turns on or off (whether it happens automatically or the user does it 12744 * manually.) 12745 * 12746 * @param screenState The new state of the screen. Can be either 12747 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 12748 */ 12749 public void onScreenStateChanged(int screenState) { 12750 } 12751 12752 /** 12753 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 12754 */ 12755 private boolean hasRtlSupport() { 12756 return mContext.getApplicationInfo().hasRtlSupport(); 12757 } 12758 12759 /** 12760 * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or 12761 * RTL not supported) 12762 */ 12763 private boolean isRtlCompatibilityMode() { 12764 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 12765 return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport(); 12766 } 12767 12768 /** 12769 * @return true if RTL properties need resolution. 12770 * 12771 */ 12772 private boolean needRtlPropertiesResolution() { 12773 return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED; 12774 } 12775 12776 /** 12777 * Called when any RTL property (layout direction or text direction or text alignment) has 12778 * been changed. 12779 * 12780 * Subclasses need to override this method to take care of cached information that depends on the 12781 * resolved layout direction, or to inform child views that inherit their layout direction. 12782 * 12783 * The default implementation does nothing. 12784 * 12785 * @param layoutDirection the direction of the layout 12786 * 12787 * @see #LAYOUT_DIRECTION_LTR 12788 * @see #LAYOUT_DIRECTION_RTL 12789 */ 12790 public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) { 12791 } 12792 12793 /** 12794 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 12795 * that the parent directionality can and will be resolved before its children. 12796 * 12797 * @return true if resolution has been done, false otherwise. 12798 * 12799 * @hide 12800 */ 12801 public boolean resolveLayoutDirection() { 12802 // Clear any previous layout direction resolution 12803 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 12804 12805 if (hasRtlSupport()) { 12806 // Set resolved depending on layout direction 12807 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 12808 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 12809 case LAYOUT_DIRECTION_INHERIT: 12810 // We cannot resolve yet. LTR is by default and let the resolution happen again 12811 // later to get the correct resolved value 12812 if (!canResolveLayoutDirection()) return false; 12813 12814 // Parent has not yet resolved, LTR is still the default 12815 try { 12816 if (!mParent.isLayoutDirectionResolved()) return false; 12817 12818 if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 12819 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12820 } 12821 } catch (AbstractMethodError e) { 12822 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 12823 " does not fully implement ViewParent", e); 12824 } 12825 break; 12826 case LAYOUT_DIRECTION_RTL: 12827 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12828 break; 12829 case LAYOUT_DIRECTION_LOCALE: 12830 if((LAYOUT_DIRECTION_RTL == 12831 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) { 12832 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12833 } 12834 break; 12835 default: 12836 // Nothing to do, LTR by default 12837 } 12838 } 12839 12840 // Set to resolved 12841 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 12842 return true; 12843 } 12844 12845 /** 12846 * Check if layout direction resolution can be done. 12847 * 12848 * @return true if layout direction resolution can be done otherwise return false. 12849 */ 12850 public boolean canResolveLayoutDirection() { 12851 switch (getRawLayoutDirection()) { 12852 case LAYOUT_DIRECTION_INHERIT: 12853 if (mParent != null) { 12854 try { 12855 return mParent.canResolveLayoutDirection(); 12856 } catch (AbstractMethodError e) { 12857 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 12858 " does not fully implement ViewParent", e); 12859 } 12860 } 12861 return false; 12862 12863 default: 12864 return true; 12865 } 12866 } 12867 12868 /** 12869 * Reset the resolved layout direction. Layout direction will be resolved during a call to 12870 * {@link #onMeasure(int, int)}. 12871 * 12872 * @hide 12873 */ 12874 public void resetResolvedLayoutDirection() { 12875 // Reset the current resolved bits 12876 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 12877 } 12878 12879 /** 12880 * @return true if the layout direction is inherited. 12881 * 12882 * @hide 12883 */ 12884 public boolean isLayoutDirectionInherited() { 12885 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT); 12886 } 12887 12888 /** 12889 * @return true if layout direction has been resolved. 12890 */ 12891 public boolean isLayoutDirectionResolved() { 12892 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED; 12893 } 12894 12895 /** 12896 * Return if padding has been resolved 12897 * 12898 * @hide 12899 */ 12900 boolean isPaddingResolved() { 12901 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED; 12902 } 12903 12904 /** 12905 * Resolves padding depending on layout direction, if applicable, and 12906 * recomputes internal padding values to adjust for scroll bars. 12907 * 12908 * @hide 12909 */ 12910 public void resolvePadding() { 12911 final int resolvedLayoutDirection = getLayoutDirection(); 12912 12913 if (!isRtlCompatibilityMode()) { 12914 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 12915 // If start / end padding are defined, they will be resolved (hence overriding) to 12916 // left / right or right / left depending on the resolved layout direction. 12917 // If start / end padding are not defined, use the left / right ones. 12918 if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) { 12919 Rect padding = sThreadLocal.get(); 12920 if (padding == null) { 12921 padding = new Rect(); 12922 sThreadLocal.set(padding); 12923 } 12924 mBackground.getPadding(padding); 12925 if (!mLeftPaddingDefined) { 12926 mUserPaddingLeftInitial = padding.left; 12927 } 12928 if (!mRightPaddingDefined) { 12929 mUserPaddingRightInitial = padding.right; 12930 } 12931 } 12932 switch (resolvedLayoutDirection) { 12933 case LAYOUT_DIRECTION_RTL: 12934 if (mUserPaddingStart != UNDEFINED_PADDING) { 12935 mUserPaddingRight = mUserPaddingStart; 12936 } else { 12937 mUserPaddingRight = mUserPaddingRightInitial; 12938 } 12939 if (mUserPaddingEnd != UNDEFINED_PADDING) { 12940 mUserPaddingLeft = mUserPaddingEnd; 12941 } else { 12942 mUserPaddingLeft = mUserPaddingLeftInitial; 12943 } 12944 break; 12945 case LAYOUT_DIRECTION_LTR: 12946 default: 12947 if (mUserPaddingStart != UNDEFINED_PADDING) { 12948 mUserPaddingLeft = mUserPaddingStart; 12949 } else { 12950 mUserPaddingLeft = mUserPaddingLeftInitial; 12951 } 12952 if (mUserPaddingEnd != UNDEFINED_PADDING) { 12953 mUserPaddingRight = mUserPaddingEnd; 12954 } else { 12955 mUserPaddingRight = mUserPaddingRightInitial; 12956 } 12957 } 12958 12959 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 12960 } 12961 12962 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 12963 onRtlPropertiesChanged(resolvedLayoutDirection); 12964 12965 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 12966 } 12967 12968 /** 12969 * Reset the resolved layout direction. 12970 * 12971 * @hide 12972 */ 12973 public void resetResolvedPadding() { 12974 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 12975 } 12976 12977 /** 12978 * This is called when the view is detached from a window. At this point it 12979 * no longer has a surface for drawing. 12980 * 12981 * @see #onAttachedToWindow() 12982 */ 12983 protected void onDetachedFromWindow() { 12984 } 12985 12986 /** 12987 * This is a framework-internal mirror of onDetachedFromWindow() that's called 12988 * after onDetachedFromWindow(). 12989 * 12990 * If you override this you *MUST* call super.onDetachedFromWindowInternal()! 12991 * The super method should be called at the end of the overriden method to ensure 12992 * subclasses are destroyed first 12993 * 12994 * @hide 12995 */ 12996 protected void onDetachedFromWindowInternal() { 12997 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 12998 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 12999 13000 removeUnsetPressCallback(); 13001 removeLongPressCallback(); 13002 removePerformClickCallback(); 13003 removeSendViewScrolledAccessibilityEventCallback(); 13004 stopNestedScroll(); 13005 13006 destroyDrawingCache(); 13007 13008 cleanupDraw(); 13009 mCurrentAnimation = null; 13010 } 13011 13012 private void cleanupDraw() { 13013 resetDisplayList(); 13014 if (mAttachInfo != null) { 13015 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 13016 } 13017 } 13018 13019 void invalidateInheritedLayoutMode(int layoutModeOfRoot) { 13020 } 13021 13022 /** 13023 * @return The number of times this view has been attached to a window 13024 */ 13025 protected int getWindowAttachCount() { 13026 return mWindowAttachCount; 13027 } 13028 13029 /** 13030 * Retrieve a unique token identifying the window this view is attached to. 13031 * @return Return the window's token for use in 13032 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 13033 */ 13034 public IBinder getWindowToken() { 13035 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 13036 } 13037 13038 /** 13039 * Retrieve the {@link WindowId} for the window this view is 13040 * currently attached to. 13041 */ 13042 public WindowId getWindowId() { 13043 if (mAttachInfo == null) { 13044 return null; 13045 } 13046 if (mAttachInfo.mWindowId == null) { 13047 try { 13048 mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId( 13049 mAttachInfo.mWindowToken); 13050 mAttachInfo.mWindowId = new WindowId( 13051 mAttachInfo.mIWindowId); 13052 } catch (RemoteException e) { 13053 } 13054 } 13055 return mAttachInfo.mWindowId; 13056 } 13057 13058 /** 13059 * Retrieve a unique token identifying the top-level "real" window of 13060 * the window that this view is attached to. That is, this is like 13061 * {@link #getWindowToken}, except if the window this view in is a panel 13062 * window (attached to another containing window), then the token of 13063 * the containing window is returned instead. 13064 * 13065 * @return Returns the associated window token, either 13066 * {@link #getWindowToken()} or the containing window's token. 13067 */ 13068 public IBinder getApplicationWindowToken() { 13069 AttachInfo ai = mAttachInfo; 13070 if (ai != null) { 13071 IBinder appWindowToken = ai.mPanelParentWindowToken; 13072 if (appWindowToken == null) { 13073 appWindowToken = ai.mWindowToken; 13074 } 13075 return appWindowToken; 13076 } 13077 return null; 13078 } 13079 13080 /** 13081 * Gets the logical display to which the view's window has been attached. 13082 * 13083 * @return The logical display, or null if the view is not currently attached to a window. 13084 */ 13085 public Display getDisplay() { 13086 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 13087 } 13088 13089 /** 13090 * Retrieve private session object this view hierarchy is using to 13091 * communicate with the window manager. 13092 * @return the session object to communicate with the window manager 13093 */ 13094 /*package*/ IWindowSession getWindowSession() { 13095 return mAttachInfo != null ? mAttachInfo.mSession : null; 13096 } 13097 13098 /** 13099 * @param info the {@link android.view.View.AttachInfo} to associated with 13100 * this view 13101 */ 13102 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 13103 //System.out.println("Attached! " + this); 13104 mAttachInfo = info; 13105 if (mOverlay != null) { 13106 mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility); 13107 } 13108 mWindowAttachCount++; 13109 // We will need to evaluate the drawable state at least once. 13110 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 13111 if (mFloatingTreeObserver != null) { 13112 info.mTreeObserver.merge(mFloatingTreeObserver); 13113 mFloatingTreeObserver = null; 13114 } 13115 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 13116 mAttachInfo.mScrollContainers.add(this); 13117 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 13118 } 13119 performCollectViewAttributes(mAttachInfo, visibility); 13120 onAttachedToWindow(); 13121 13122 ListenerInfo li = mListenerInfo; 13123 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 13124 li != null ? li.mOnAttachStateChangeListeners : null; 13125 if (listeners != null && listeners.size() > 0) { 13126 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 13127 // perform the dispatching. The iterator is a safe guard against listeners that 13128 // could mutate the list by calling the various add/remove methods. This prevents 13129 // the array from being modified while we iterate it. 13130 for (OnAttachStateChangeListener listener : listeners) { 13131 listener.onViewAttachedToWindow(this); 13132 } 13133 } 13134 13135 int vis = info.mWindowVisibility; 13136 if (vis != GONE) { 13137 onWindowVisibilityChanged(vis); 13138 } 13139 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 13140 // If nobody has evaluated the drawable state yet, then do it now. 13141 refreshDrawableState(); 13142 } 13143 needGlobalAttributesUpdate(false); 13144 } 13145 13146 void dispatchDetachedFromWindow() { 13147 AttachInfo info = mAttachInfo; 13148 if (info != null) { 13149 int vis = info.mWindowVisibility; 13150 if (vis != GONE) { 13151 onWindowVisibilityChanged(GONE); 13152 } 13153 } 13154 13155 onDetachedFromWindow(); 13156 onDetachedFromWindowInternal(); 13157 13158 ListenerInfo li = mListenerInfo; 13159 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 13160 li != null ? li.mOnAttachStateChangeListeners : null; 13161 if (listeners != null && listeners.size() > 0) { 13162 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 13163 // perform the dispatching. The iterator is a safe guard against listeners that 13164 // could mutate the list by calling the various add/remove methods. This prevents 13165 // the array from being modified while we iterate it. 13166 for (OnAttachStateChangeListener listener : listeners) { 13167 listener.onViewDetachedFromWindow(this); 13168 } 13169 } 13170 13171 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 13172 mAttachInfo.mScrollContainers.remove(this); 13173 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 13174 } 13175 13176 mAttachInfo = null; 13177 if (mOverlay != null) { 13178 mOverlay.getOverlayView().dispatchDetachedFromWindow(); 13179 } 13180 } 13181 13182 /** 13183 * Cancel any deferred high-level input events that were previously posted to the event queue. 13184 * 13185 * <p>Many views post high-level events such as click handlers to the event queue 13186 * to run deferred in order to preserve a desired user experience - clearing visible 13187 * pressed states before executing, etc. This method will abort any events of this nature 13188 * that are currently in flight.</p> 13189 * 13190 * <p>Custom views that generate their own high-level deferred input events should override 13191 * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p> 13192 * 13193 * <p>This will also cancel pending input events for any child views.</p> 13194 * 13195 * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases. 13196 * This will not impact newer events posted after this call that may occur as a result of 13197 * lower-level input events still waiting in the queue. If you are trying to prevent 13198 * double-submitted events for the duration of some sort of asynchronous transaction 13199 * you should also take other steps to protect against unexpected double inputs e.g. calling 13200 * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when 13201 * the transaction completes, tracking already submitted transaction IDs, etc.</p> 13202 */ 13203 public final void cancelPendingInputEvents() { 13204 dispatchCancelPendingInputEvents(); 13205 } 13206 13207 /** 13208 * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight. 13209 * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling. 13210 */ 13211 void dispatchCancelPendingInputEvents() { 13212 mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER; 13213 onCancelPendingInputEvents(); 13214 if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) { 13215 throw new SuperNotCalledException("View " + getClass().getSimpleName() + 13216 " did not call through to super.onCancelPendingInputEvents()"); 13217 } 13218 } 13219 13220 /** 13221 * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or 13222 * a parent view. 13223 * 13224 * <p>This method is responsible for removing any pending high-level input events that were 13225 * posted to the event queue to run later. Custom view classes that post their own deferred 13226 * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or 13227 * {@link android.os.Handler} should override this method, call 13228 * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate. 13229 * </p> 13230 */ 13231 public void onCancelPendingInputEvents() { 13232 removePerformClickCallback(); 13233 cancelLongPress(); 13234 mPrivateFlags3 |= PFLAG3_CALLED_SUPER; 13235 } 13236 13237 /** 13238 * Store this view hierarchy's frozen state into the given container. 13239 * 13240 * @param container The SparseArray in which to save the view's state. 13241 * 13242 * @see #restoreHierarchyState(android.util.SparseArray) 13243 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13244 * @see #onSaveInstanceState() 13245 */ 13246 public void saveHierarchyState(SparseArray<Parcelable> container) { 13247 dispatchSaveInstanceState(container); 13248 } 13249 13250 /** 13251 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 13252 * this view and its children. May be overridden to modify how freezing happens to a 13253 * view's children; for example, some views may want to not store state for their children. 13254 * 13255 * @param container The SparseArray in which to save the view's state. 13256 * 13257 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13258 * @see #saveHierarchyState(android.util.SparseArray) 13259 * @see #onSaveInstanceState() 13260 */ 13261 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 13262 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 13263 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 13264 Parcelable state = onSaveInstanceState(); 13265 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 13266 throw new IllegalStateException( 13267 "Derived class did not call super.onSaveInstanceState()"); 13268 } 13269 if (state != null) { 13270 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 13271 // + ": " + state); 13272 container.put(mID, state); 13273 } 13274 } 13275 } 13276 13277 /** 13278 * Hook allowing a view to generate a representation of its internal state 13279 * that can later be used to create a new instance with that same state. 13280 * This state should only contain information that is not persistent or can 13281 * not be reconstructed later. For example, you will never store your 13282 * current position on screen because that will be computed again when a 13283 * new instance of the view is placed in its view hierarchy. 13284 * <p> 13285 * Some examples of things you may store here: the current cursor position 13286 * in a text view (but usually not the text itself since that is stored in a 13287 * content provider or other persistent storage), the currently selected 13288 * item in a list view. 13289 * 13290 * @return Returns a Parcelable object containing the view's current dynamic 13291 * state, or null if there is nothing interesting to save. The 13292 * default implementation returns null. 13293 * @see #onRestoreInstanceState(android.os.Parcelable) 13294 * @see #saveHierarchyState(android.util.SparseArray) 13295 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13296 * @see #setSaveEnabled(boolean) 13297 */ 13298 protected Parcelable onSaveInstanceState() { 13299 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 13300 return BaseSavedState.EMPTY_STATE; 13301 } 13302 13303 /** 13304 * Restore this view hierarchy's frozen state from the given container. 13305 * 13306 * @param container The SparseArray which holds previously frozen states. 13307 * 13308 * @see #saveHierarchyState(android.util.SparseArray) 13309 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13310 * @see #onRestoreInstanceState(android.os.Parcelable) 13311 */ 13312 public void restoreHierarchyState(SparseArray<Parcelable> container) { 13313 dispatchRestoreInstanceState(container); 13314 } 13315 13316 /** 13317 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 13318 * state for this view and its children. May be overridden to modify how restoring 13319 * happens to a view's children; for example, some views may want to not store state 13320 * for their children. 13321 * 13322 * @param container The SparseArray which holds previously saved state. 13323 * 13324 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13325 * @see #restoreHierarchyState(android.util.SparseArray) 13326 * @see #onRestoreInstanceState(android.os.Parcelable) 13327 */ 13328 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 13329 if (mID != NO_ID) { 13330 Parcelable state = container.get(mID); 13331 if (state != null) { 13332 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 13333 // + ": " + state); 13334 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 13335 onRestoreInstanceState(state); 13336 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 13337 throw new IllegalStateException( 13338 "Derived class did not call super.onRestoreInstanceState()"); 13339 } 13340 } 13341 } 13342 } 13343 13344 /** 13345 * Hook allowing a view to re-apply a representation of its internal state that had previously 13346 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 13347 * null state. 13348 * 13349 * @param state The frozen state that had previously been returned by 13350 * {@link #onSaveInstanceState}. 13351 * 13352 * @see #onSaveInstanceState() 13353 * @see #restoreHierarchyState(android.util.SparseArray) 13354 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13355 */ 13356 protected void onRestoreInstanceState(Parcelable state) { 13357 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 13358 if (state != BaseSavedState.EMPTY_STATE && state != null) { 13359 throw new IllegalArgumentException("Wrong state class, expecting View State but " 13360 + "received " + state.getClass().toString() + " instead. This usually happens " 13361 + "when two views of different type have the same id in the same hierarchy. " 13362 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 13363 + "other views do not use the same id."); 13364 } 13365 } 13366 13367 /** 13368 * <p>Return the time at which the drawing of the view hierarchy started.</p> 13369 * 13370 * @return the drawing start time in milliseconds 13371 */ 13372 public long getDrawingTime() { 13373 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 13374 } 13375 13376 /** 13377 * <p>Enables or disables the duplication of the parent's state into this view. When 13378 * duplication is enabled, this view gets its drawable state from its parent rather 13379 * than from its own internal properties.</p> 13380 * 13381 * <p>Note: in the current implementation, setting this property to true after the 13382 * view was added to a ViewGroup might have no effect at all. This property should 13383 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 13384 * 13385 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 13386 * property is enabled, an exception will be thrown.</p> 13387 * 13388 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 13389 * parent, these states should not be affected by this method.</p> 13390 * 13391 * @param enabled True to enable duplication of the parent's drawable state, false 13392 * to disable it. 13393 * 13394 * @see #getDrawableState() 13395 * @see #isDuplicateParentStateEnabled() 13396 */ 13397 public void setDuplicateParentStateEnabled(boolean enabled) { 13398 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 13399 } 13400 13401 /** 13402 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 13403 * 13404 * @return True if this view's drawable state is duplicated from the parent, 13405 * false otherwise 13406 * 13407 * @see #getDrawableState() 13408 * @see #setDuplicateParentStateEnabled(boolean) 13409 */ 13410 public boolean isDuplicateParentStateEnabled() { 13411 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 13412 } 13413 13414 /** 13415 * <p>Specifies the type of layer backing this view. The layer can be 13416 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13417 * {@link #LAYER_TYPE_HARDWARE}.</p> 13418 * 13419 * <p>A layer is associated with an optional {@link android.graphics.Paint} 13420 * instance that controls how the layer is composed on screen. The following 13421 * properties of the paint are taken into account when composing the layer:</p> 13422 * <ul> 13423 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 13424 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 13425 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 13426 * </ul> 13427 * 13428 * <p>If this view has an alpha value set to < 1.0 by calling 13429 * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded 13430 * by this view's alpha value.</p> 13431 * 13432 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE}, 13433 * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE} 13434 * for more information on when and how to use layers.</p> 13435 * 13436 * @param layerType The type of layer to use with this view, must be one of 13437 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13438 * {@link #LAYER_TYPE_HARDWARE} 13439 * @param paint The paint used to compose the layer. This argument is optional 13440 * and can be null. It is ignored when the layer type is 13441 * {@link #LAYER_TYPE_NONE} 13442 * 13443 * @see #getLayerType() 13444 * @see #LAYER_TYPE_NONE 13445 * @see #LAYER_TYPE_SOFTWARE 13446 * @see #LAYER_TYPE_HARDWARE 13447 * @see #setAlpha(float) 13448 * 13449 * @attr ref android.R.styleable#View_layerType 13450 */ 13451 public void setLayerType(int layerType, Paint paint) { 13452 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 13453 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 13454 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 13455 } 13456 13457 boolean typeChanged = mRenderNode.setLayerType(layerType); 13458 13459 if (!typeChanged) { 13460 setLayerPaint(paint); 13461 return; 13462 } 13463 13464 // Destroy any previous software drawing cache if needed 13465 if (mLayerType == LAYER_TYPE_SOFTWARE) { 13466 destroyDrawingCache(); 13467 } 13468 13469 mLayerType = layerType; 13470 final boolean layerDisabled = (mLayerType == LAYER_TYPE_NONE); 13471 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 13472 mRenderNode.setLayerPaint(mLayerPaint); 13473 13474 // draw() behaves differently if we are on a layer, so we need to 13475 // invalidate() here 13476 invalidateParentCaches(); 13477 invalidate(true); 13478 } 13479 13480 /** 13481 * Updates the {@link Paint} object used with the current layer (used only if the current 13482 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 13483 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 13484 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 13485 * ensure that the view gets redrawn immediately. 13486 * 13487 * <p>A layer is associated with an optional {@link android.graphics.Paint} 13488 * instance that controls how the layer is composed on screen. The following 13489 * properties of the paint are taken into account when composing the layer:</p> 13490 * <ul> 13491 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 13492 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 13493 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 13494 * </ul> 13495 * 13496 * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the 13497 * alpha value of the layer's paint is superceded by this view's alpha value.</p> 13498 * 13499 * @param paint The paint used to compose the layer. This argument is optional 13500 * and can be null. It is ignored when the layer type is 13501 * {@link #LAYER_TYPE_NONE} 13502 * 13503 * @see #setLayerType(int, android.graphics.Paint) 13504 */ 13505 public void setLayerPaint(Paint paint) { 13506 int layerType = getLayerType(); 13507 if (layerType != LAYER_TYPE_NONE) { 13508 mLayerPaint = paint == null ? new Paint() : paint; 13509 if (layerType == LAYER_TYPE_HARDWARE) { 13510 if (mRenderNode.setLayerPaint(mLayerPaint)) { 13511 invalidateViewProperty(false, false); 13512 } 13513 } else { 13514 invalidate(); 13515 } 13516 } 13517 } 13518 13519 /** 13520 * Indicates whether this view has a static layer. A view with layer type 13521 * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are 13522 * dynamic. 13523 */ 13524 boolean hasStaticLayer() { 13525 return true; 13526 } 13527 13528 /** 13529 * Indicates what type of layer is currently associated with this view. By default 13530 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 13531 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 13532 * for more information on the different types of layers. 13533 * 13534 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13535 * {@link #LAYER_TYPE_HARDWARE} 13536 * 13537 * @see #setLayerType(int, android.graphics.Paint) 13538 * @see #buildLayer() 13539 * @see #LAYER_TYPE_NONE 13540 * @see #LAYER_TYPE_SOFTWARE 13541 * @see #LAYER_TYPE_HARDWARE 13542 */ 13543 public int getLayerType() { 13544 return mLayerType; 13545 } 13546 13547 /** 13548 * Forces this view's layer to be created and this view to be rendered 13549 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 13550 * invoking this method will have no effect. 13551 * 13552 * This method can for instance be used to render a view into its layer before 13553 * starting an animation. If this view is complex, rendering into the layer 13554 * before starting the animation will avoid skipping frames. 13555 * 13556 * @throws IllegalStateException If this view is not attached to a window 13557 * 13558 * @see #setLayerType(int, android.graphics.Paint) 13559 */ 13560 public void buildLayer() { 13561 if (mLayerType == LAYER_TYPE_NONE) return; 13562 13563 final AttachInfo attachInfo = mAttachInfo; 13564 if (attachInfo == null) { 13565 throw new IllegalStateException("This view must be attached to a window first"); 13566 } 13567 13568 if (getWidth() == 0 || getHeight() == 0) { 13569 return; 13570 } 13571 13572 switch (mLayerType) { 13573 case LAYER_TYPE_HARDWARE: 13574 // The only part of a hardware layer we can build in response to 13575 // this call is to ensure the display list is up to date. 13576 // The actual rendering of the display list into the layer must 13577 // be done at playback time 13578 updateDisplayListIfDirty(); 13579 break; 13580 case LAYER_TYPE_SOFTWARE: 13581 buildDrawingCache(true); 13582 break; 13583 } 13584 } 13585 13586 /** 13587 * If this View draws with a HardwareLayer, returns it. 13588 * Otherwise returns null 13589 * 13590 * TODO: Only TextureView uses this, can we eliminate it? 13591 */ 13592 HardwareLayer getHardwareLayer() { 13593 return null; 13594 } 13595 13596 /** 13597 * Destroys all hardware rendering resources. This method is invoked 13598 * when the system needs to reclaim resources. Upon execution of this 13599 * method, you should free any OpenGL resources created by the view. 13600 * 13601 * Note: you <strong>must</strong> call 13602 * <code>super.destroyHardwareResources()</code> when overriding 13603 * this method. 13604 * 13605 * @hide 13606 */ 13607 protected void destroyHardwareResources() { 13608 // Although the Layer will be destroyed by RenderNode, we want to release 13609 // the staging display list, which is also a signal to RenderNode that it's 13610 // safe to free its copy of the display list as it knows that we will 13611 // push an updated DisplayList if we try to draw again 13612 resetDisplayList(); 13613 } 13614 13615 /** 13616 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 13617 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 13618 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 13619 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 13620 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 13621 * null.</p> 13622 * 13623 * <p>Enabling the drawing cache is similar to 13624 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 13625 * acceleration is turned off. When hardware acceleration is turned on, enabling the 13626 * drawing cache has no effect on rendering because the system uses a different mechanism 13627 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 13628 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 13629 * for information on how to enable software and hardware layers.</p> 13630 * 13631 * <p>This API can be used to manually generate 13632 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 13633 * {@link #getDrawingCache()}.</p> 13634 * 13635 * @param enabled true to enable the drawing cache, false otherwise 13636 * 13637 * @see #isDrawingCacheEnabled() 13638 * @see #getDrawingCache() 13639 * @see #buildDrawingCache() 13640 * @see #setLayerType(int, android.graphics.Paint) 13641 */ 13642 public void setDrawingCacheEnabled(boolean enabled) { 13643 mCachingFailed = false; 13644 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 13645 } 13646 13647 /** 13648 * <p>Indicates whether the drawing cache is enabled for this view.</p> 13649 * 13650 * @return true if the drawing cache is enabled 13651 * 13652 * @see #setDrawingCacheEnabled(boolean) 13653 * @see #getDrawingCache() 13654 */ 13655 @ViewDebug.ExportedProperty(category = "drawing") 13656 public boolean isDrawingCacheEnabled() { 13657 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 13658 } 13659 13660 /** 13661 * Debugging utility which recursively outputs the dirty state of a view and its 13662 * descendants. 13663 * 13664 * @hide 13665 */ 13666 @SuppressWarnings({"UnusedDeclaration"}) 13667 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 13668 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 13669 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 13670 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 13671 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 13672 if (clear) { 13673 mPrivateFlags &= clearMask; 13674 } 13675 if (this instanceof ViewGroup) { 13676 ViewGroup parent = (ViewGroup) this; 13677 final int count = parent.getChildCount(); 13678 for (int i = 0; i < count; i++) { 13679 final View child = parent.getChildAt(i); 13680 child.outputDirtyFlags(indent + " ", clear, clearMask); 13681 } 13682 } 13683 } 13684 13685 /** 13686 * This method is used by ViewGroup to cause its children to restore or recreate their 13687 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 13688 * to recreate its own display list, which would happen if it went through the normal 13689 * draw/dispatchDraw mechanisms. 13690 * 13691 * @hide 13692 */ 13693 protected void dispatchGetDisplayList() {} 13694 13695 /** 13696 * A view that is not attached or hardware accelerated cannot create a display list. 13697 * This method checks these conditions and returns the appropriate result. 13698 * 13699 * @return true if view has the ability to create a display list, false otherwise. 13700 * 13701 * @hide 13702 */ 13703 public boolean canHaveDisplayList() { 13704 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 13705 } 13706 13707 private void updateDisplayListIfDirty() { 13708 final RenderNode renderNode = mRenderNode; 13709 if (!canHaveDisplayList()) { 13710 // can't populate RenderNode, don't try 13711 return; 13712 } 13713 13714 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 13715 || !renderNode.isValid() 13716 || (mRecreateDisplayList)) { 13717 // Don't need to recreate the display list, just need to tell our 13718 // children to restore/recreate theirs 13719 if (renderNode.isValid() 13720 && !mRecreateDisplayList) { 13721 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13722 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13723 dispatchGetDisplayList(); 13724 13725 return; // no work needed 13726 } 13727 13728 // If we got here, we're recreating it. Mark it as such to ensure that 13729 // we copy in child display lists into ours in drawChild() 13730 mRecreateDisplayList = true; 13731 13732 int width = mRight - mLeft; 13733 int height = mBottom - mTop; 13734 int layerType = getLayerType(); 13735 13736 final HardwareCanvas canvas = renderNode.start(width, height); 13737 canvas.setHighContrastText(mAttachInfo.mHighContrastText); 13738 13739 try { 13740 final HardwareLayer layer = getHardwareLayer(); 13741 if (layer != null && layer.isValid()) { 13742 canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint); 13743 } else if (layerType == LAYER_TYPE_SOFTWARE) { 13744 buildDrawingCache(true); 13745 Bitmap cache = getDrawingCache(true); 13746 if (cache != null) { 13747 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 13748 } 13749 } else { 13750 computeScroll(); 13751 13752 canvas.translate(-mScrollX, -mScrollY); 13753 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13754 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13755 13756 // Fast path for layouts with no backgrounds 13757 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 13758 dispatchDraw(canvas); 13759 if (mOverlay != null && !mOverlay.isEmpty()) { 13760 mOverlay.getOverlayView().draw(canvas); 13761 } 13762 } else { 13763 draw(canvas); 13764 } 13765 } 13766 } finally { 13767 renderNode.end(canvas); 13768 setDisplayListProperties(renderNode); 13769 } 13770 } else { 13771 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13772 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13773 } 13774 } 13775 13776 /** 13777 * Returns a RenderNode with View draw content recorded, which can be 13778 * used to draw this view again without executing its draw method. 13779 * 13780 * @return A RenderNode ready to replay, or null if caching is not enabled. 13781 * 13782 * @hide 13783 */ 13784 public RenderNode getDisplayList() { 13785 updateDisplayListIfDirty(); 13786 return mRenderNode; 13787 } 13788 13789 private void resetDisplayList() { 13790 if (mRenderNode.isValid()) { 13791 mRenderNode.destroyDisplayListData(); 13792 } 13793 13794 if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) { 13795 mBackgroundRenderNode.destroyDisplayListData(); 13796 } 13797 } 13798 13799 /** 13800 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 13801 * 13802 * @return A non-scaled bitmap representing this view or null if cache is disabled. 13803 * 13804 * @see #getDrawingCache(boolean) 13805 */ 13806 public Bitmap getDrawingCache() { 13807 return getDrawingCache(false); 13808 } 13809 13810 /** 13811 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 13812 * is null when caching is disabled. If caching is enabled and the cache is not ready, 13813 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 13814 * draw from the cache when the cache is enabled. To benefit from the cache, you must 13815 * request the drawing cache by calling this method and draw it on screen if the 13816 * returned bitmap is not null.</p> 13817 * 13818 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 13819 * this method will create a bitmap of the same size as this view. Because this bitmap 13820 * will be drawn scaled by the parent ViewGroup, the result on screen might show 13821 * scaling artifacts. To avoid such artifacts, you should call this method by setting 13822 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 13823 * size than the view. This implies that your application must be able to handle this 13824 * size.</p> 13825 * 13826 * @param autoScale Indicates whether the generated bitmap should be scaled based on 13827 * the current density of the screen when the application is in compatibility 13828 * mode. 13829 * 13830 * @return A bitmap representing this view or null if cache is disabled. 13831 * 13832 * @see #setDrawingCacheEnabled(boolean) 13833 * @see #isDrawingCacheEnabled() 13834 * @see #buildDrawingCache(boolean) 13835 * @see #destroyDrawingCache() 13836 */ 13837 public Bitmap getDrawingCache(boolean autoScale) { 13838 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 13839 return null; 13840 } 13841 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 13842 buildDrawingCache(autoScale); 13843 } 13844 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 13845 } 13846 13847 /** 13848 * <p>Frees the resources used by the drawing cache. If you call 13849 * {@link #buildDrawingCache()} manually without calling 13850 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 13851 * should cleanup the cache with this method afterwards.</p> 13852 * 13853 * @see #setDrawingCacheEnabled(boolean) 13854 * @see #buildDrawingCache() 13855 * @see #getDrawingCache() 13856 */ 13857 public void destroyDrawingCache() { 13858 if (mDrawingCache != null) { 13859 mDrawingCache.recycle(); 13860 mDrawingCache = null; 13861 } 13862 if (mUnscaledDrawingCache != null) { 13863 mUnscaledDrawingCache.recycle(); 13864 mUnscaledDrawingCache = null; 13865 } 13866 } 13867 13868 /** 13869 * Setting a solid background color for the drawing cache's bitmaps will improve 13870 * performance and memory usage. Note, though that this should only be used if this 13871 * view will always be drawn on top of a solid color. 13872 * 13873 * @param color The background color to use for the drawing cache's bitmap 13874 * 13875 * @see #setDrawingCacheEnabled(boolean) 13876 * @see #buildDrawingCache() 13877 * @see #getDrawingCache() 13878 */ 13879 public void setDrawingCacheBackgroundColor(int color) { 13880 if (color != mDrawingCacheBackgroundColor) { 13881 mDrawingCacheBackgroundColor = color; 13882 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 13883 } 13884 } 13885 13886 /** 13887 * @see #setDrawingCacheBackgroundColor(int) 13888 * 13889 * @return The background color to used for the drawing cache's bitmap 13890 */ 13891 public int getDrawingCacheBackgroundColor() { 13892 return mDrawingCacheBackgroundColor; 13893 } 13894 13895 /** 13896 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 13897 * 13898 * @see #buildDrawingCache(boolean) 13899 */ 13900 public void buildDrawingCache() { 13901 buildDrawingCache(false); 13902 } 13903 13904 /** 13905 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 13906 * 13907 * <p>If you call {@link #buildDrawingCache()} manually without calling 13908 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 13909 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 13910 * 13911 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 13912 * this method will create a bitmap of the same size as this view. Because this bitmap 13913 * will be drawn scaled by the parent ViewGroup, the result on screen might show 13914 * scaling artifacts. To avoid such artifacts, you should call this method by setting 13915 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 13916 * size than the view. This implies that your application must be able to handle this 13917 * size.</p> 13918 * 13919 * <p>You should avoid calling this method when hardware acceleration is enabled. If 13920 * you do not need the drawing cache bitmap, calling this method will increase memory 13921 * usage and cause the view to be rendered in software once, thus negatively impacting 13922 * performance.</p> 13923 * 13924 * @see #getDrawingCache() 13925 * @see #destroyDrawingCache() 13926 */ 13927 public void buildDrawingCache(boolean autoScale) { 13928 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 13929 mDrawingCache == null : mUnscaledDrawingCache == null)) { 13930 mCachingFailed = false; 13931 13932 int width = mRight - mLeft; 13933 int height = mBottom - mTop; 13934 13935 final AttachInfo attachInfo = mAttachInfo; 13936 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 13937 13938 if (autoScale && scalingRequired) { 13939 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 13940 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 13941 } 13942 13943 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 13944 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 13945 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 13946 13947 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 13948 final long drawingCacheSize = 13949 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 13950 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 13951 if (width > 0 && height > 0) { 13952 Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs " 13953 + projectedBitmapSize + " bytes, only " 13954 + drawingCacheSize + " available"); 13955 } 13956 destroyDrawingCache(); 13957 mCachingFailed = true; 13958 return; 13959 } 13960 13961 boolean clear = true; 13962 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 13963 13964 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 13965 Bitmap.Config quality; 13966 if (!opaque) { 13967 // Never pick ARGB_4444 because it looks awful 13968 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 13969 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 13970 case DRAWING_CACHE_QUALITY_AUTO: 13971 case DRAWING_CACHE_QUALITY_LOW: 13972 case DRAWING_CACHE_QUALITY_HIGH: 13973 default: 13974 quality = Bitmap.Config.ARGB_8888; 13975 break; 13976 } 13977 } else { 13978 // Optimization for translucent windows 13979 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 13980 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 13981 } 13982 13983 // Try to cleanup memory 13984 if (bitmap != null) bitmap.recycle(); 13985 13986 try { 13987 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 13988 width, height, quality); 13989 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 13990 if (autoScale) { 13991 mDrawingCache = bitmap; 13992 } else { 13993 mUnscaledDrawingCache = bitmap; 13994 } 13995 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 13996 } catch (OutOfMemoryError e) { 13997 // If there is not enough memory to create the bitmap cache, just 13998 // ignore the issue as bitmap caches are not required to draw the 13999 // view hierarchy 14000 if (autoScale) { 14001 mDrawingCache = null; 14002 } else { 14003 mUnscaledDrawingCache = null; 14004 } 14005 mCachingFailed = true; 14006 return; 14007 } 14008 14009 clear = drawingCacheBackgroundColor != 0; 14010 } 14011 14012 Canvas canvas; 14013 if (attachInfo != null) { 14014 canvas = attachInfo.mCanvas; 14015 if (canvas == null) { 14016 canvas = new Canvas(); 14017 } 14018 canvas.setBitmap(bitmap); 14019 // Temporarily clobber the cached Canvas in case one of our children 14020 // is also using a drawing cache. Without this, the children would 14021 // steal the canvas by attaching their own bitmap to it and bad, bad 14022 // thing would happen (invisible views, corrupted drawings, etc.) 14023 attachInfo.mCanvas = null; 14024 } else { 14025 // This case should hopefully never or seldom happen 14026 canvas = new Canvas(bitmap); 14027 } 14028 14029 if (clear) { 14030 bitmap.eraseColor(drawingCacheBackgroundColor); 14031 } 14032 14033 computeScroll(); 14034 final int restoreCount = canvas.save(); 14035 14036 if (autoScale && scalingRequired) { 14037 final float scale = attachInfo.mApplicationScale; 14038 canvas.scale(scale, scale); 14039 } 14040 14041 canvas.translate(-mScrollX, -mScrollY); 14042 14043 mPrivateFlags |= PFLAG_DRAWN; 14044 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 14045 mLayerType != LAYER_TYPE_NONE) { 14046 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 14047 } 14048 14049 // Fast path for layouts with no backgrounds 14050 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14051 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14052 dispatchDraw(canvas); 14053 if (mOverlay != null && !mOverlay.isEmpty()) { 14054 mOverlay.getOverlayView().draw(canvas); 14055 } 14056 } else { 14057 draw(canvas); 14058 } 14059 14060 canvas.restoreToCount(restoreCount); 14061 canvas.setBitmap(null); 14062 14063 if (attachInfo != null) { 14064 // Restore the cached Canvas for our siblings 14065 attachInfo.mCanvas = canvas; 14066 } 14067 } 14068 } 14069 14070 /** 14071 * Create a snapshot of the view into a bitmap. We should probably make 14072 * some form of this public, but should think about the API. 14073 */ 14074 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 14075 int width = mRight - mLeft; 14076 int height = mBottom - mTop; 14077 14078 final AttachInfo attachInfo = mAttachInfo; 14079 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 14080 width = (int) ((width * scale) + 0.5f); 14081 height = (int) ((height * scale) + 0.5f); 14082 14083 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 14084 width > 0 ? width : 1, height > 0 ? height : 1, quality); 14085 if (bitmap == null) { 14086 throw new OutOfMemoryError(); 14087 } 14088 14089 Resources resources = getResources(); 14090 if (resources != null) { 14091 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 14092 } 14093 14094 Canvas canvas; 14095 if (attachInfo != null) { 14096 canvas = attachInfo.mCanvas; 14097 if (canvas == null) { 14098 canvas = new Canvas(); 14099 } 14100 canvas.setBitmap(bitmap); 14101 // Temporarily clobber the cached Canvas in case one of our children 14102 // is also using a drawing cache. Without this, the children would 14103 // steal the canvas by attaching their own bitmap to it and bad, bad 14104 // things would happen (invisible views, corrupted drawings, etc.) 14105 attachInfo.mCanvas = null; 14106 } else { 14107 // This case should hopefully never or seldom happen 14108 canvas = new Canvas(bitmap); 14109 } 14110 14111 if ((backgroundColor & 0xff000000) != 0) { 14112 bitmap.eraseColor(backgroundColor); 14113 } 14114 14115 computeScroll(); 14116 final int restoreCount = canvas.save(); 14117 canvas.scale(scale, scale); 14118 canvas.translate(-mScrollX, -mScrollY); 14119 14120 // Temporarily remove the dirty mask 14121 int flags = mPrivateFlags; 14122 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14123 14124 // Fast path for layouts with no backgrounds 14125 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14126 dispatchDraw(canvas); 14127 if (mOverlay != null && !mOverlay.isEmpty()) { 14128 mOverlay.getOverlayView().draw(canvas); 14129 } 14130 } else { 14131 draw(canvas); 14132 } 14133 14134 mPrivateFlags = flags; 14135 14136 canvas.restoreToCount(restoreCount); 14137 canvas.setBitmap(null); 14138 14139 if (attachInfo != null) { 14140 // Restore the cached Canvas for our siblings 14141 attachInfo.mCanvas = canvas; 14142 } 14143 14144 return bitmap; 14145 } 14146 14147 /** 14148 * Indicates whether this View is currently in edit mode. A View is usually 14149 * in edit mode when displayed within a developer tool. For instance, if 14150 * this View is being drawn by a visual user interface builder, this method 14151 * should return true. 14152 * 14153 * Subclasses should check the return value of this method to provide 14154 * different behaviors if their normal behavior might interfere with the 14155 * host environment. For instance: the class spawns a thread in its 14156 * constructor, the drawing code relies on device-specific features, etc. 14157 * 14158 * This method is usually checked in the drawing code of custom widgets. 14159 * 14160 * @return True if this View is in edit mode, false otherwise. 14161 */ 14162 public boolean isInEditMode() { 14163 return false; 14164 } 14165 14166 /** 14167 * If the View draws content inside its padding and enables fading edges, 14168 * it needs to support padding offsets. Padding offsets are added to the 14169 * fading edges to extend the length of the fade so that it covers pixels 14170 * drawn inside the padding. 14171 * 14172 * Subclasses of this class should override this method if they need 14173 * to draw content inside the padding. 14174 * 14175 * @return True if padding offset must be applied, false otherwise. 14176 * 14177 * @see #getLeftPaddingOffset() 14178 * @see #getRightPaddingOffset() 14179 * @see #getTopPaddingOffset() 14180 * @see #getBottomPaddingOffset() 14181 * 14182 * @since CURRENT 14183 */ 14184 protected boolean isPaddingOffsetRequired() { 14185 return false; 14186 } 14187 14188 /** 14189 * Amount by which to extend the left fading region. Called only when 14190 * {@link #isPaddingOffsetRequired()} returns true. 14191 * 14192 * @return The left padding offset in pixels. 14193 * 14194 * @see #isPaddingOffsetRequired() 14195 * 14196 * @since CURRENT 14197 */ 14198 protected int getLeftPaddingOffset() { 14199 return 0; 14200 } 14201 14202 /** 14203 * Amount by which to extend the right fading region. Called only when 14204 * {@link #isPaddingOffsetRequired()} returns true. 14205 * 14206 * @return The right padding offset in pixels. 14207 * 14208 * @see #isPaddingOffsetRequired() 14209 * 14210 * @since CURRENT 14211 */ 14212 protected int getRightPaddingOffset() { 14213 return 0; 14214 } 14215 14216 /** 14217 * Amount by which to extend the top fading region. Called only when 14218 * {@link #isPaddingOffsetRequired()} returns true. 14219 * 14220 * @return The top padding offset in pixels. 14221 * 14222 * @see #isPaddingOffsetRequired() 14223 * 14224 * @since CURRENT 14225 */ 14226 protected int getTopPaddingOffset() { 14227 return 0; 14228 } 14229 14230 /** 14231 * Amount by which to extend the bottom fading region. Called only when 14232 * {@link #isPaddingOffsetRequired()} returns true. 14233 * 14234 * @return The bottom padding offset in pixels. 14235 * 14236 * @see #isPaddingOffsetRequired() 14237 * 14238 * @since CURRENT 14239 */ 14240 protected int getBottomPaddingOffset() { 14241 return 0; 14242 } 14243 14244 /** 14245 * @hide 14246 * @param offsetRequired 14247 */ 14248 protected int getFadeTop(boolean offsetRequired) { 14249 int top = mPaddingTop; 14250 if (offsetRequired) top += getTopPaddingOffset(); 14251 return top; 14252 } 14253 14254 /** 14255 * @hide 14256 * @param offsetRequired 14257 */ 14258 protected int getFadeHeight(boolean offsetRequired) { 14259 int padding = mPaddingTop; 14260 if (offsetRequired) padding += getTopPaddingOffset(); 14261 return mBottom - mTop - mPaddingBottom - padding; 14262 } 14263 14264 /** 14265 * <p>Indicates whether this view is attached to a hardware accelerated 14266 * window or not.</p> 14267 * 14268 * <p>Even if this method returns true, it does not mean that every call 14269 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 14270 * accelerated {@link android.graphics.Canvas}. For instance, if this view 14271 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 14272 * window is hardware accelerated, 14273 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 14274 * return false, and this method will return true.</p> 14275 * 14276 * @return True if the view is attached to a window and the window is 14277 * hardware accelerated; false in any other case. 14278 */ 14279 @ViewDebug.ExportedProperty(category = "drawing") 14280 public boolean isHardwareAccelerated() { 14281 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14282 } 14283 14284 /** 14285 * Sets a rectangular area on this view to which the view will be clipped 14286 * when it is drawn. Setting the value to null will remove the clip bounds 14287 * and the view will draw normally, using its full bounds. 14288 * 14289 * @param clipBounds The rectangular area, in the local coordinates of 14290 * this view, to which future drawing operations will be clipped. 14291 */ 14292 public void setClipBounds(Rect clipBounds) { 14293 if (clipBounds != null) { 14294 if (clipBounds.equals(mClipBounds)) { 14295 return; 14296 } 14297 if (mClipBounds == null) { 14298 invalidate(); 14299 mClipBounds = new Rect(clipBounds); 14300 } else { 14301 invalidate(Math.min(mClipBounds.left, clipBounds.left), 14302 Math.min(mClipBounds.top, clipBounds.top), 14303 Math.max(mClipBounds.right, clipBounds.right), 14304 Math.max(mClipBounds.bottom, clipBounds.bottom)); 14305 mClipBounds.set(clipBounds); 14306 } 14307 } else { 14308 if (mClipBounds != null) { 14309 invalidate(); 14310 mClipBounds = null; 14311 } 14312 } 14313 mRenderNode.setClipBounds(mClipBounds); 14314 } 14315 14316 /** 14317 * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}. 14318 * 14319 * @return A copy of the current clip bounds if clip bounds are set, 14320 * otherwise null. 14321 */ 14322 public Rect getClipBounds() { 14323 return (mClipBounds != null) ? new Rect(mClipBounds) : null; 14324 } 14325 14326 /** 14327 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 14328 * case of an active Animation being run on the view. 14329 */ 14330 private boolean drawAnimation(ViewGroup parent, long drawingTime, 14331 Animation a, boolean scalingRequired) { 14332 Transformation invalidationTransform; 14333 final int flags = parent.mGroupFlags; 14334 final boolean initialized = a.isInitialized(); 14335 if (!initialized) { 14336 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 14337 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 14338 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 14339 onAnimationStart(); 14340 } 14341 14342 final Transformation t = parent.getChildTransformation(); 14343 boolean more = a.getTransformation(drawingTime, t, 1f); 14344 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 14345 if (parent.mInvalidationTransformation == null) { 14346 parent.mInvalidationTransformation = new Transformation(); 14347 } 14348 invalidationTransform = parent.mInvalidationTransformation; 14349 a.getTransformation(drawingTime, invalidationTransform, 1f); 14350 } else { 14351 invalidationTransform = t; 14352 } 14353 14354 if (more) { 14355 if (!a.willChangeBounds()) { 14356 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 14357 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 14358 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 14359 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 14360 // The child need to draw an animation, potentially offscreen, so 14361 // make sure we do not cancel invalidate requests 14362 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14363 parent.invalidate(mLeft, mTop, mRight, mBottom); 14364 } 14365 } else { 14366 if (parent.mInvalidateRegion == null) { 14367 parent.mInvalidateRegion = new RectF(); 14368 } 14369 final RectF region = parent.mInvalidateRegion; 14370 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 14371 invalidationTransform); 14372 14373 // The child need to draw an animation, potentially offscreen, so 14374 // make sure we do not cancel invalidate requests 14375 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14376 14377 final int left = mLeft + (int) region.left; 14378 final int top = mTop + (int) region.top; 14379 parent.invalidate(left, top, left + (int) (region.width() + .5f), 14380 top + (int) (region.height() + .5f)); 14381 } 14382 } 14383 return more; 14384 } 14385 14386 /** 14387 * This method is called by getDisplayList() when a display list is recorded for a View. 14388 * It pushes any properties to the RenderNode that aren't managed by the RenderNode. 14389 */ 14390 void setDisplayListProperties(RenderNode renderNode) { 14391 if (renderNode != null) { 14392 renderNode.setHasOverlappingRendering(hasOverlappingRendering()); 14393 if (mParent instanceof ViewGroup) { 14394 renderNode.setClipToBounds( 14395 (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0); 14396 } 14397 float alpha = 1; 14398 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 14399 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14400 ViewGroup parentVG = (ViewGroup) mParent; 14401 final Transformation t = parentVG.getChildTransformation(); 14402 if (parentVG.getChildStaticTransformation(this, t)) { 14403 final int transformType = t.getTransformationType(); 14404 if (transformType != Transformation.TYPE_IDENTITY) { 14405 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 14406 alpha = t.getAlpha(); 14407 } 14408 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 14409 renderNode.setStaticMatrix(t.getMatrix()); 14410 } 14411 } 14412 } 14413 } 14414 if (mTransformationInfo != null) { 14415 alpha *= getFinalAlpha(); 14416 if (alpha < 1) { 14417 final int multipliedAlpha = (int) (255 * alpha); 14418 if (onSetAlpha(multipliedAlpha)) { 14419 alpha = 1; 14420 } 14421 } 14422 renderNode.setAlpha(alpha); 14423 } else if (alpha < 1) { 14424 renderNode.setAlpha(alpha); 14425 } 14426 } 14427 } 14428 14429 /** 14430 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 14431 * This draw() method is an implementation detail and is not intended to be overridden or 14432 * to be called from anywhere else other than ViewGroup.drawChild(). 14433 */ 14434 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 14435 boolean usingRenderNodeProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14436 boolean more = false; 14437 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 14438 final int flags = parent.mGroupFlags; 14439 14440 if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) { 14441 parent.getChildTransformation().clear(); 14442 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14443 } 14444 14445 Transformation transformToApply = null; 14446 boolean concatMatrix = false; 14447 14448 boolean scalingRequired = false; 14449 boolean caching; 14450 int layerType = getLayerType(); 14451 14452 final boolean hardwareAccelerated = canvas.isHardwareAccelerated(); 14453 if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 || 14454 (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) { 14455 caching = true; 14456 // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList 14457 if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired; 14458 } else { 14459 caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated; 14460 } 14461 14462 final Animation a = getAnimation(); 14463 if (a != null) { 14464 more = drawAnimation(parent, drawingTime, a, scalingRequired); 14465 concatMatrix = a.willChangeTransformationMatrix(); 14466 if (concatMatrix) { 14467 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14468 } 14469 transformToApply = parent.getChildTransformation(); 14470 } else { 14471 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) { 14472 // No longer animating: clear out old animation matrix 14473 mRenderNode.setAnimationMatrix(null); 14474 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14475 } 14476 if (!usingRenderNodeProperties && 14477 (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14478 final Transformation t = parent.getChildTransformation(); 14479 final boolean hasTransform = parent.getChildStaticTransformation(this, t); 14480 if (hasTransform) { 14481 final int transformType = t.getTransformationType(); 14482 transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null; 14483 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 14484 } 14485 } 14486 } 14487 14488 concatMatrix |= !childHasIdentityMatrix; 14489 14490 // Sets the flag as early as possible to allow draw() implementations 14491 // to call invalidate() successfully when doing animations 14492 mPrivateFlags |= PFLAG_DRAWN; 14493 14494 if (!concatMatrix && 14495 (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 14496 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 14497 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 14498 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 14499 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 14500 return more; 14501 } 14502 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 14503 14504 if (hardwareAccelerated) { 14505 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 14506 // retain the flag's value temporarily in the mRecreateDisplayList flag 14507 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED; 14508 mPrivateFlags &= ~PFLAG_INVALIDATED; 14509 } 14510 14511 RenderNode renderNode = null; 14512 Bitmap cache = null; 14513 boolean hasDisplayList = false; 14514 if (caching) { 14515 if (!hardwareAccelerated) { 14516 if (layerType != LAYER_TYPE_NONE) { 14517 layerType = LAYER_TYPE_SOFTWARE; 14518 buildDrawingCache(true); 14519 } 14520 cache = getDrawingCache(true); 14521 } else { 14522 switch (layerType) { 14523 case LAYER_TYPE_SOFTWARE: 14524 if (usingRenderNodeProperties) { 14525 hasDisplayList = canHaveDisplayList(); 14526 } else { 14527 buildDrawingCache(true); 14528 cache = getDrawingCache(true); 14529 } 14530 break; 14531 case LAYER_TYPE_HARDWARE: 14532 if (usingRenderNodeProperties) { 14533 hasDisplayList = canHaveDisplayList(); 14534 } 14535 break; 14536 case LAYER_TYPE_NONE: 14537 // Delay getting the display list until animation-driven alpha values are 14538 // set up and possibly passed on to the view 14539 hasDisplayList = canHaveDisplayList(); 14540 break; 14541 } 14542 } 14543 } 14544 usingRenderNodeProperties &= hasDisplayList; 14545 if (usingRenderNodeProperties) { 14546 renderNode = getDisplayList(); 14547 if (!renderNode.isValid()) { 14548 // Uncommon, but possible. If a view is removed from the hierarchy during the call 14549 // to getDisplayList(), the display list will be marked invalid and we should not 14550 // try to use it again. 14551 renderNode = null; 14552 hasDisplayList = false; 14553 usingRenderNodeProperties = false; 14554 } 14555 } 14556 14557 int sx = 0; 14558 int sy = 0; 14559 if (!hasDisplayList) { 14560 computeScroll(); 14561 sx = mScrollX; 14562 sy = mScrollY; 14563 } 14564 14565 final boolean hasNoCache = cache == null || hasDisplayList; 14566 final boolean offsetForScroll = cache == null && !hasDisplayList && 14567 layerType != LAYER_TYPE_HARDWARE; 14568 14569 int restoreTo = -1; 14570 if (!usingRenderNodeProperties || transformToApply != null) { 14571 restoreTo = canvas.save(); 14572 } 14573 if (offsetForScroll) { 14574 canvas.translate(mLeft - sx, mTop - sy); 14575 } else { 14576 if (!usingRenderNodeProperties) { 14577 canvas.translate(mLeft, mTop); 14578 } 14579 if (scalingRequired) { 14580 if (usingRenderNodeProperties) { 14581 // TODO: Might not need this if we put everything inside the DL 14582 restoreTo = canvas.save(); 14583 } 14584 // mAttachInfo cannot be null, otherwise scalingRequired == false 14585 final float scale = 1.0f / mAttachInfo.mApplicationScale; 14586 canvas.scale(scale, scale); 14587 } 14588 } 14589 14590 float alpha = usingRenderNodeProperties ? 1 : (getAlpha() * getTransitionAlpha()); 14591 if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() || 14592 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 14593 if (transformToApply != null || !childHasIdentityMatrix) { 14594 int transX = 0; 14595 int transY = 0; 14596 14597 if (offsetForScroll) { 14598 transX = -sx; 14599 transY = -sy; 14600 } 14601 14602 if (transformToApply != null) { 14603 if (concatMatrix) { 14604 if (usingRenderNodeProperties) { 14605 renderNode.setAnimationMatrix(transformToApply.getMatrix()); 14606 } else { 14607 // Undo the scroll translation, apply the transformation matrix, 14608 // then redo the scroll translate to get the correct result. 14609 canvas.translate(-transX, -transY); 14610 canvas.concat(transformToApply.getMatrix()); 14611 canvas.translate(transX, transY); 14612 } 14613 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14614 } 14615 14616 float transformAlpha = transformToApply.getAlpha(); 14617 if (transformAlpha < 1) { 14618 alpha *= transformAlpha; 14619 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14620 } 14621 } 14622 14623 if (!childHasIdentityMatrix && !usingRenderNodeProperties) { 14624 canvas.translate(-transX, -transY); 14625 canvas.concat(getMatrix()); 14626 canvas.translate(transX, transY); 14627 } 14628 } 14629 14630 // Deal with alpha if it is or used to be <1 14631 if (alpha < 1 || 14632 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 14633 if (alpha < 1) { 14634 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 14635 } else { 14636 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 14637 } 14638 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14639 if (hasNoCache) { 14640 final int multipliedAlpha = (int) (255 * alpha); 14641 if (!onSetAlpha(multipliedAlpha)) { 14642 int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 14643 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 || 14644 layerType != LAYER_TYPE_NONE) { 14645 layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG; 14646 } 14647 if (usingRenderNodeProperties) { 14648 renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha()); 14649 } else if (layerType == LAYER_TYPE_NONE) { 14650 final int scrollX = hasDisplayList ? 0 : sx; 14651 final int scrollY = hasDisplayList ? 0 : sy; 14652 canvas.saveLayerAlpha(scrollX, scrollY, 14653 scrollX + (mRight - mLeft), scrollY + (mBottom - mTop), 14654 multipliedAlpha, layerFlags); 14655 } 14656 } else { 14657 // Alpha is handled by the child directly, clobber the layer's alpha 14658 mPrivateFlags |= PFLAG_ALPHA_SET; 14659 } 14660 } 14661 } 14662 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 14663 onSetAlpha(255); 14664 mPrivateFlags &= ~PFLAG_ALPHA_SET; 14665 } 14666 14667 if (!usingRenderNodeProperties) { 14668 // apply clips directly, since RenderNode won't do it for this draw 14669 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN 14670 && cache == null) { 14671 if (offsetForScroll) { 14672 canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop)); 14673 } else { 14674 if (!scalingRequired || cache == null) { 14675 canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop); 14676 } else { 14677 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 14678 } 14679 } 14680 } 14681 14682 if (mClipBounds != null) { 14683 // clip bounds ignore scroll 14684 canvas.clipRect(mClipBounds); 14685 } 14686 } 14687 14688 14689 14690 if (!usingRenderNodeProperties && hasDisplayList) { 14691 renderNode = getDisplayList(); 14692 if (!renderNode.isValid()) { 14693 // Uncommon, but possible. If a view is removed from the hierarchy during the call 14694 // to getDisplayList(), the display list will be marked invalid and we should not 14695 // try to use it again. 14696 renderNode = null; 14697 hasDisplayList = false; 14698 } 14699 } 14700 14701 if (hasNoCache) { 14702 boolean layerRendered = false; 14703 if (layerType == LAYER_TYPE_HARDWARE && !usingRenderNodeProperties) { 14704 final HardwareLayer layer = getHardwareLayer(); 14705 if (layer != null && layer.isValid()) { 14706 int restoreAlpha = mLayerPaint.getAlpha(); 14707 mLayerPaint.setAlpha((int) (alpha * 255)); 14708 ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint); 14709 mLayerPaint.setAlpha(restoreAlpha); 14710 layerRendered = true; 14711 } else { 14712 final int scrollX = hasDisplayList ? 0 : sx; 14713 final int scrollY = hasDisplayList ? 0 : sy; 14714 canvas.saveLayer(scrollX, scrollY, 14715 scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint, 14716 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG); 14717 } 14718 } 14719 14720 if (!layerRendered) { 14721 if (!hasDisplayList) { 14722 // Fast path for layouts with no backgrounds 14723 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14724 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14725 dispatchDraw(canvas); 14726 } else { 14727 draw(canvas); 14728 } 14729 } else { 14730 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14731 ((HardwareCanvas) canvas).drawRenderNode(renderNode, null, flags); 14732 } 14733 } 14734 } else if (cache != null) { 14735 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14736 Paint cachePaint; 14737 int restoreAlpha = 0; 14738 14739 if (layerType == LAYER_TYPE_NONE) { 14740 cachePaint = parent.mCachePaint; 14741 if (cachePaint == null) { 14742 cachePaint = new Paint(); 14743 cachePaint.setDither(false); 14744 parent.mCachePaint = cachePaint; 14745 } 14746 } else { 14747 cachePaint = mLayerPaint; 14748 restoreAlpha = mLayerPaint.getAlpha(); 14749 } 14750 cachePaint.setAlpha((int) (alpha * 255)); 14751 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 14752 cachePaint.setAlpha(restoreAlpha); 14753 } 14754 14755 if (restoreTo >= 0) { 14756 canvas.restoreToCount(restoreTo); 14757 } 14758 14759 if (a != null && !more) { 14760 if (!hardwareAccelerated && !a.getFillAfter()) { 14761 onSetAlpha(255); 14762 } 14763 parent.finishAnimatingView(this, a); 14764 } 14765 14766 if (more && hardwareAccelerated) { 14767 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 14768 // alpha animations should cause the child to recreate its display list 14769 invalidate(true); 14770 } 14771 } 14772 14773 mRecreateDisplayList = false; 14774 14775 return more; 14776 } 14777 14778 /** 14779 * Manually render this view (and all of its children) to the given Canvas. 14780 * The view must have already done a full layout before this function is 14781 * called. When implementing a view, implement 14782 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 14783 * If you do need to override this method, call the superclass version. 14784 * 14785 * @param canvas The Canvas to which the View is rendered. 14786 */ 14787 public void draw(Canvas canvas) { 14788 final int privateFlags = mPrivateFlags; 14789 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 14790 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 14791 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 14792 14793 /* 14794 * Draw traversal performs several drawing steps which must be executed 14795 * in the appropriate order: 14796 * 14797 * 1. Draw the background 14798 * 2. If necessary, save the canvas' layers to prepare for fading 14799 * 3. Draw view's content 14800 * 4. Draw children 14801 * 5. If necessary, draw the fading edges and restore layers 14802 * 6. Draw decorations (scrollbars for instance) 14803 */ 14804 14805 // Step 1, draw the background, if needed 14806 int saveCount; 14807 14808 if (!dirtyOpaque) { 14809 drawBackground(canvas); 14810 } 14811 14812 // skip step 2 & 5 if possible (common case) 14813 final int viewFlags = mViewFlags; 14814 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 14815 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 14816 if (!verticalEdges && !horizontalEdges) { 14817 // Step 3, draw the content 14818 if (!dirtyOpaque) onDraw(canvas); 14819 14820 // Step 4, draw the children 14821 dispatchDraw(canvas); 14822 14823 // Step 6, draw decorations (scrollbars) 14824 onDrawScrollBars(canvas); 14825 14826 if (mOverlay != null && !mOverlay.isEmpty()) { 14827 mOverlay.getOverlayView().dispatchDraw(canvas); 14828 } 14829 14830 // we're done... 14831 return; 14832 } 14833 14834 /* 14835 * Here we do the full fledged routine... 14836 * (this is an uncommon case where speed matters less, 14837 * this is why we repeat some of the tests that have been 14838 * done above) 14839 */ 14840 14841 boolean drawTop = false; 14842 boolean drawBottom = false; 14843 boolean drawLeft = false; 14844 boolean drawRight = false; 14845 14846 float topFadeStrength = 0.0f; 14847 float bottomFadeStrength = 0.0f; 14848 float leftFadeStrength = 0.0f; 14849 float rightFadeStrength = 0.0f; 14850 14851 // Step 2, save the canvas' layers 14852 int paddingLeft = mPaddingLeft; 14853 14854 final boolean offsetRequired = isPaddingOffsetRequired(); 14855 if (offsetRequired) { 14856 paddingLeft += getLeftPaddingOffset(); 14857 } 14858 14859 int left = mScrollX + paddingLeft; 14860 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 14861 int top = mScrollY + getFadeTop(offsetRequired); 14862 int bottom = top + getFadeHeight(offsetRequired); 14863 14864 if (offsetRequired) { 14865 right += getRightPaddingOffset(); 14866 bottom += getBottomPaddingOffset(); 14867 } 14868 14869 final ScrollabilityCache scrollabilityCache = mScrollCache; 14870 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 14871 int length = (int) fadeHeight; 14872 14873 // clip the fade length if top and bottom fades overlap 14874 // overlapping fades produce odd-looking artifacts 14875 if (verticalEdges && (top + length > bottom - length)) { 14876 length = (bottom - top) / 2; 14877 } 14878 14879 // also clip horizontal fades if necessary 14880 if (horizontalEdges && (left + length > right - length)) { 14881 length = (right - left) / 2; 14882 } 14883 14884 if (verticalEdges) { 14885 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 14886 drawTop = topFadeStrength * fadeHeight > 1.0f; 14887 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 14888 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 14889 } 14890 14891 if (horizontalEdges) { 14892 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 14893 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 14894 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 14895 drawRight = rightFadeStrength * fadeHeight > 1.0f; 14896 } 14897 14898 saveCount = canvas.getSaveCount(); 14899 14900 int solidColor = getSolidColor(); 14901 if (solidColor == 0) { 14902 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 14903 14904 if (drawTop) { 14905 canvas.saveLayer(left, top, right, top + length, null, flags); 14906 } 14907 14908 if (drawBottom) { 14909 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 14910 } 14911 14912 if (drawLeft) { 14913 canvas.saveLayer(left, top, left + length, bottom, null, flags); 14914 } 14915 14916 if (drawRight) { 14917 canvas.saveLayer(right - length, top, right, bottom, null, flags); 14918 } 14919 } else { 14920 scrollabilityCache.setFadeColor(solidColor); 14921 } 14922 14923 // Step 3, draw the content 14924 if (!dirtyOpaque) onDraw(canvas); 14925 14926 // Step 4, draw the children 14927 dispatchDraw(canvas); 14928 14929 // Step 5, draw the fade effect and restore layers 14930 final Paint p = scrollabilityCache.paint; 14931 final Matrix matrix = scrollabilityCache.matrix; 14932 final Shader fade = scrollabilityCache.shader; 14933 14934 if (drawTop) { 14935 matrix.setScale(1, fadeHeight * topFadeStrength); 14936 matrix.postTranslate(left, top); 14937 fade.setLocalMatrix(matrix); 14938 p.setShader(fade); 14939 canvas.drawRect(left, top, right, top + length, p); 14940 } 14941 14942 if (drawBottom) { 14943 matrix.setScale(1, fadeHeight * bottomFadeStrength); 14944 matrix.postRotate(180); 14945 matrix.postTranslate(left, bottom); 14946 fade.setLocalMatrix(matrix); 14947 p.setShader(fade); 14948 canvas.drawRect(left, bottom - length, right, bottom, p); 14949 } 14950 14951 if (drawLeft) { 14952 matrix.setScale(1, fadeHeight * leftFadeStrength); 14953 matrix.postRotate(-90); 14954 matrix.postTranslate(left, top); 14955 fade.setLocalMatrix(matrix); 14956 p.setShader(fade); 14957 canvas.drawRect(left, top, left + length, bottom, p); 14958 } 14959 14960 if (drawRight) { 14961 matrix.setScale(1, fadeHeight * rightFadeStrength); 14962 matrix.postRotate(90); 14963 matrix.postTranslate(right, top); 14964 fade.setLocalMatrix(matrix); 14965 p.setShader(fade); 14966 canvas.drawRect(right - length, top, right, bottom, p); 14967 } 14968 14969 canvas.restoreToCount(saveCount); 14970 14971 // Step 6, draw decorations (scrollbars) 14972 onDrawScrollBars(canvas); 14973 14974 if (mOverlay != null && !mOverlay.isEmpty()) { 14975 mOverlay.getOverlayView().dispatchDraw(canvas); 14976 } 14977 } 14978 14979 /** 14980 * Draws the background onto the specified canvas. 14981 * 14982 * @param canvas Canvas on which to draw the background 14983 */ 14984 private void drawBackground(Canvas canvas) { 14985 final Drawable background = mBackground; 14986 if (background == null) { 14987 return; 14988 } 14989 14990 if (mBackgroundSizeChanged) { 14991 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 14992 mBackgroundSizeChanged = false; 14993 invalidateOutline(); 14994 } 14995 14996 // Attempt to use a display list if requested. 14997 if (canvas.isHardwareAccelerated() && mAttachInfo != null 14998 && mAttachInfo.mHardwareRenderer != null) { 14999 mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode); 15000 15001 final RenderNode displayList = mBackgroundRenderNode; 15002 if (displayList != null && displayList.isValid()) { 15003 setBackgroundDisplayListProperties(displayList); 15004 ((HardwareCanvas) canvas).drawRenderNode(displayList); 15005 return; 15006 } 15007 } 15008 15009 final int scrollX = mScrollX; 15010 final int scrollY = mScrollY; 15011 if ((scrollX | scrollY) == 0) { 15012 background.draw(canvas); 15013 } else { 15014 canvas.translate(scrollX, scrollY); 15015 background.draw(canvas); 15016 canvas.translate(-scrollX, -scrollY); 15017 } 15018 } 15019 15020 /** 15021 * Set up background drawable display list properties. 15022 * 15023 * @param displayList Valid display list for the background drawable 15024 */ 15025 private void setBackgroundDisplayListProperties(RenderNode displayList) { 15026 displayList.setTranslationX(mScrollX); 15027 displayList.setTranslationY(mScrollY); 15028 } 15029 15030 /** 15031 * Creates a new display list or updates the existing display list for the 15032 * specified Drawable. 15033 * 15034 * @param drawable Drawable for which to create a display list 15035 * @param renderNode Existing RenderNode, or {@code null} 15036 * @return A valid display list for the specified drawable 15037 */ 15038 private static RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) { 15039 if (renderNode == null) { 15040 renderNode = RenderNode.create(drawable.getClass().getName()); 15041 } 15042 15043 final Rect bounds = drawable.getBounds(); 15044 final int width = bounds.width(); 15045 final int height = bounds.height(); 15046 final HardwareCanvas canvas = renderNode.start(width, height); 15047 try { 15048 drawable.draw(canvas); 15049 } finally { 15050 renderNode.end(canvas); 15051 } 15052 15053 // Set up drawable properties that are view-independent. 15054 renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom); 15055 renderNode.setProjectBackwards(drawable.isProjected()); 15056 renderNode.setProjectionReceiver(true); 15057 renderNode.setClipToBounds(false); 15058 return renderNode; 15059 } 15060 15061 /** 15062 * Returns the overlay for this view, creating it if it does not yet exist. 15063 * Adding drawables to the overlay will cause them to be displayed whenever 15064 * the view itself is redrawn. Objects in the overlay should be actively 15065 * managed: remove them when they should not be displayed anymore. The 15066 * overlay will always have the same size as its host view. 15067 * 15068 * <p>Note: Overlays do not currently work correctly with {@link 15069 * SurfaceView} or {@link TextureView}; contents in overlays for these 15070 * types of views may not display correctly.</p> 15071 * 15072 * @return The ViewOverlay object for this view. 15073 * @see ViewOverlay 15074 */ 15075 public ViewOverlay getOverlay() { 15076 if (mOverlay == null) { 15077 mOverlay = new ViewOverlay(mContext, this); 15078 } 15079 return mOverlay; 15080 } 15081 15082 /** 15083 * Override this if your view is known to always be drawn on top of a solid color background, 15084 * and needs to draw fading edges. Returning a non-zero color enables the view system to 15085 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 15086 * should be set to 0xFF. 15087 * 15088 * @see #setVerticalFadingEdgeEnabled(boolean) 15089 * @see #setHorizontalFadingEdgeEnabled(boolean) 15090 * 15091 * @return The known solid color background for this view, or 0 if the color may vary 15092 */ 15093 @ViewDebug.ExportedProperty(category = "drawing") 15094 public int getSolidColor() { 15095 return 0; 15096 } 15097 15098 /** 15099 * Build a human readable string representation of the specified view flags. 15100 * 15101 * @param flags the view flags to convert to a string 15102 * @return a String representing the supplied flags 15103 */ 15104 private static String printFlags(int flags) { 15105 String output = ""; 15106 int numFlags = 0; 15107 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 15108 output += "TAKES_FOCUS"; 15109 numFlags++; 15110 } 15111 15112 switch (flags & VISIBILITY_MASK) { 15113 case INVISIBLE: 15114 if (numFlags > 0) { 15115 output += " "; 15116 } 15117 output += "INVISIBLE"; 15118 // USELESS HERE numFlags++; 15119 break; 15120 case GONE: 15121 if (numFlags > 0) { 15122 output += " "; 15123 } 15124 output += "GONE"; 15125 // USELESS HERE numFlags++; 15126 break; 15127 default: 15128 break; 15129 } 15130 return output; 15131 } 15132 15133 /** 15134 * Build a human readable string representation of the specified private 15135 * view flags. 15136 * 15137 * @param privateFlags the private view flags to convert to a string 15138 * @return a String representing the supplied flags 15139 */ 15140 private static String printPrivateFlags(int privateFlags) { 15141 String output = ""; 15142 int numFlags = 0; 15143 15144 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 15145 output += "WANTS_FOCUS"; 15146 numFlags++; 15147 } 15148 15149 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 15150 if (numFlags > 0) { 15151 output += " "; 15152 } 15153 output += "FOCUSED"; 15154 numFlags++; 15155 } 15156 15157 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 15158 if (numFlags > 0) { 15159 output += " "; 15160 } 15161 output += "SELECTED"; 15162 numFlags++; 15163 } 15164 15165 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 15166 if (numFlags > 0) { 15167 output += " "; 15168 } 15169 output += "IS_ROOT_NAMESPACE"; 15170 numFlags++; 15171 } 15172 15173 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 15174 if (numFlags > 0) { 15175 output += " "; 15176 } 15177 output += "HAS_BOUNDS"; 15178 numFlags++; 15179 } 15180 15181 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 15182 if (numFlags > 0) { 15183 output += " "; 15184 } 15185 output += "DRAWN"; 15186 // USELESS HERE numFlags++; 15187 } 15188 return output; 15189 } 15190 15191 /** 15192 * <p>Indicates whether or not this view's layout will be requested during 15193 * the next hierarchy layout pass.</p> 15194 * 15195 * @return true if the layout will be forced during next layout pass 15196 */ 15197 public boolean isLayoutRequested() { 15198 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 15199 } 15200 15201 /** 15202 * Return true if o is a ViewGroup that is laying out using optical bounds. 15203 * @hide 15204 */ 15205 public static boolean isLayoutModeOptical(Object o) { 15206 return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical(); 15207 } 15208 15209 private boolean setOpticalFrame(int left, int top, int right, int bottom) { 15210 Insets parentInsets = mParent instanceof View ? 15211 ((View) mParent).getOpticalInsets() : Insets.NONE; 15212 Insets childInsets = getOpticalInsets(); 15213 return setFrame( 15214 left + parentInsets.left - childInsets.left, 15215 top + parentInsets.top - childInsets.top, 15216 right + parentInsets.left + childInsets.right, 15217 bottom + parentInsets.top + childInsets.bottom); 15218 } 15219 15220 /** 15221 * Assign a size and position to a view and all of its 15222 * descendants 15223 * 15224 * <p>This is the second phase of the layout mechanism. 15225 * (The first is measuring). In this phase, each parent calls 15226 * layout on all of its children to position them. 15227 * This is typically done using the child measurements 15228 * that were stored in the measure pass().</p> 15229 * 15230 * <p>Derived classes should not override this method. 15231 * Derived classes with children should override 15232 * onLayout. In that method, they should 15233 * call layout on each of their children.</p> 15234 * 15235 * @param l Left position, relative to parent 15236 * @param t Top position, relative to parent 15237 * @param r Right position, relative to parent 15238 * @param b Bottom position, relative to parent 15239 */ 15240 @SuppressWarnings({"unchecked"}) 15241 public void layout(int l, int t, int r, int b) { 15242 if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) { 15243 onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec); 15244 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 15245 } 15246 15247 int oldL = mLeft; 15248 int oldT = mTop; 15249 int oldB = mBottom; 15250 int oldR = mRight; 15251 15252 boolean changed = isLayoutModeOptical(mParent) ? 15253 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); 15254 15255 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 15256 onLayout(changed, l, t, r, b); 15257 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 15258 15259 ListenerInfo li = mListenerInfo; 15260 if (li != null && li.mOnLayoutChangeListeners != null) { 15261 ArrayList<OnLayoutChangeListener> listenersCopy = 15262 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 15263 int numListeners = listenersCopy.size(); 15264 for (int i = 0; i < numListeners; ++i) { 15265 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 15266 } 15267 } 15268 } 15269 15270 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 15271 mPrivateFlags3 |= PFLAG3_IS_LAID_OUT; 15272 } 15273 15274 /** 15275 * Called from layout when this view should 15276 * assign a size and position to each of its children. 15277 * 15278 * Derived classes with children should override 15279 * this method and call layout on each of 15280 * their children. 15281 * @param changed This is a new size or position for this view 15282 * @param left Left position, relative to parent 15283 * @param top Top position, relative to parent 15284 * @param right Right position, relative to parent 15285 * @param bottom Bottom position, relative to parent 15286 */ 15287 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 15288 } 15289 15290 /** 15291 * Assign a size and position to this view. 15292 * 15293 * This is called from layout. 15294 * 15295 * @param left Left position, relative to parent 15296 * @param top Top position, relative to parent 15297 * @param right Right position, relative to parent 15298 * @param bottom Bottom position, relative to parent 15299 * @return true if the new size and position are different than the 15300 * previous ones 15301 * {@hide} 15302 */ 15303 protected boolean setFrame(int left, int top, int right, int bottom) { 15304 boolean changed = false; 15305 15306 if (DBG) { 15307 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 15308 + right + "," + bottom + ")"); 15309 } 15310 15311 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 15312 changed = true; 15313 15314 // Remember our drawn bit 15315 int drawn = mPrivateFlags & PFLAG_DRAWN; 15316 15317 int oldWidth = mRight - mLeft; 15318 int oldHeight = mBottom - mTop; 15319 int newWidth = right - left; 15320 int newHeight = bottom - top; 15321 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 15322 15323 // Invalidate our old position 15324 invalidate(sizeChanged); 15325 15326 mLeft = left; 15327 mTop = top; 15328 mRight = right; 15329 mBottom = bottom; 15330 mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 15331 15332 mPrivateFlags |= PFLAG_HAS_BOUNDS; 15333 15334 15335 if (sizeChanged) { 15336 sizeChange(newWidth, newHeight, oldWidth, oldHeight); 15337 } 15338 15339 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 15340 // If we are visible, force the DRAWN bit to on so that 15341 // this invalidate will go through (at least to our parent). 15342 // This is because someone may have invalidated this view 15343 // before this call to setFrame came in, thereby clearing 15344 // the DRAWN bit. 15345 mPrivateFlags |= PFLAG_DRAWN; 15346 invalidate(sizeChanged); 15347 // parent display list may need to be recreated based on a change in the bounds 15348 // of any child 15349 invalidateParentCaches(); 15350 } 15351 15352 // Reset drawn bit to original value (invalidate turns it off) 15353 mPrivateFlags |= drawn; 15354 15355 mBackgroundSizeChanged = true; 15356 15357 notifySubtreeAccessibilityStateChangedIfNeeded(); 15358 } 15359 return changed; 15360 } 15361 15362 private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) { 15363 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 15364 if (mOverlay != null) { 15365 mOverlay.getOverlayView().setRight(newWidth); 15366 mOverlay.getOverlayView().setBottom(newHeight); 15367 } 15368 invalidateOutline(); 15369 } 15370 15371 /** 15372 * Finalize inflating a view from XML. This is called as the last phase 15373 * of inflation, after all child views have been added. 15374 * 15375 * <p>Even if the subclass overrides onFinishInflate, they should always be 15376 * sure to call the super method, so that we get called. 15377 */ 15378 protected void onFinishInflate() { 15379 } 15380 15381 /** 15382 * Returns the resources associated with this view. 15383 * 15384 * @return Resources object. 15385 */ 15386 public Resources getResources() { 15387 return mResources; 15388 } 15389 15390 /** 15391 * Invalidates the specified Drawable. 15392 * 15393 * @param drawable the drawable to invalidate 15394 */ 15395 @Override 15396 public void invalidateDrawable(@NonNull Drawable drawable) { 15397 if (verifyDrawable(drawable)) { 15398 final Rect dirty = drawable.getDirtyBounds(); 15399 final int scrollX = mScrollX; 15400 final int scrollY = mScrollY; 15401 15402 invalidate(dirty.left + scrollX, dirty.top + scrollY, 15403 dirty.right + scrollX, dirty.bottom + scrollY); 15404 15405 invalidateOutline(); 15406 } 15407 } 15408 15409 /** 15410 * Schedules an action on a drawable to occur at a specified time. 15411 * 15412 * @param who the recipient of the action 15413 * @param what the action to run on the drawable 15414 * @param when the time at which the action must occur. Uses the 15415 * {@link SystemClock#uptimeMillis} timebase. 15416 */ 15417 @Override 15418 public void scheduleDrawable(Drawable who, Runnable what, long when) { 15419 if (verifyDrawable(who) && what != null) { 15420 final long delay = when - SystemClock.uptimeMillis(); 15421 if (mAttachInfo != null) { 15422 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 15423 Choreographer.CALLBACK_ANIMATION, what, who, 15424 Choreographer.subtractFrameDelay(delay)); 15425 } else { 15426 ViewRootImpl.getRunQueue().postDelayed(what, delay); 15427 } 15428 } 15429 } 15430 15431 /** 15432 * Cancels a scheduled action on a drawable. 15433 * 15434 * @param who the recipient of the action 15435 * @param what the action to cancel 15436 */ 15437 @Override 15438 public void unscheduleDrawable(Drawable who, Runnable what) { 15439 if (verifyDrawable(who) && what != null) { 15440 if (mAttachInfo != null) { 15441 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15442 Choreographer.CALLBACK_ANIMATION, what, who); 15443 } 15444 ViewRootImpl.getRunQueue().removeCallbacks(what); 15445 } 15446 } 15447 15448 /** 15449 * Unschedule any events associated with the given Drawable. This can be 15450 * used when selecting a new Drawable into a view, so that the previous 15451 * one is completely unscheduled. 15452 * 15453 * @param who The Drawable to unschedule. 15454 * 15455 * @see #drawableStateChanged 15456 */ 15457 public void unscheduleDrawable(Drawable who) { 15458 if (mAttachInfo != null && who != null) { 15459 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15460 Choreographer.CALLBACK_ANIMATION, null, who); 15461 } 15462 } 15463 15464 /** 15465 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 15466 * that the View directionality can and will be resolved before its Drawables. 15467 * 15468 * Will call {@link View#onResolveDrawables} when resolution is done. 15469 * 15470 * @hide 15471 */ 15472 protected void resolveDrawables() { 15473 // Drawables resolution may need to happen before resolving the layout direction (which is 15474 // done only during the measure() call). 15475 // If the layout direction is not resolved yet, we cannot resolve the Drawables except in 15476 // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT. 15477 // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or 15478 // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout 15479 // direction to be resolved as its resolved value will be the same as its raw value. 15480 if (!isLayoutDirectionResolved() && 15481 getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) { 15482 return; 15483 } 15484 15485 final int layoutDirection = isLayoutDirectionResolved() ? 15486 getLayoutDirection() : getRawLayoutDirection(); 15487 15488 if (mBackground != null) { 15489 mBackground.setLayoutDirection(layoutDirection); 15490 } 15491 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED; 15492 onResolveDrawables(layoutDirection); 15493 } 15494 15495 /** 15496 * Called when layout direction has been resolved. 15497 * 15498 * The default implementation does nothing. 15499 * 15500 * @param layoutDirection The resolved layout direction. 15501 * 15502 * @see #LAYOUT_DIRECTION_LTR 15503 * @see #LAYOUT_DIRECTION_RTL 15504 * 15505 * @hide 15506 */ 15507 public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) { 15508 } 15509 15510 /** 15511 * @hide 15512 */ 15513 protected void resetResolvedDrawables() { 15514 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED; 15515 } 15516 15517 private boolean isDrawablesResolved() { 15518 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED; 15519 } 15520 15521 /** 15522 * If your view subclass is displaying its own Drawable objects, it should 15523 * override this function and return true for any Drawable it is 15524 * displaying. This allows animations for those drawables to be 15525 * scheduled. 15526 * 15527 * <p>Be sure to call through to the super class when overriding this 15528 * function. 15529 * 15530 * @param who The Drawable to verify. Return true if it is one you are 15531 * displaying, else return the result of calling through to the 15532 * super class. 15533 * 15534 * @return boolean If true than the Drawable is being displayed in the 15535 * view; else false and it is not allowed to animate. 15536 * 15537 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 15538 * @see #drawableStateChanged() 15539 */ 15540 protected boolean verifyDrawable(Drawable who) { 15541 return who == mBackground; 15542 } 15543 15544 /** 15545 * This function is called whenever the state of the view changes in such 15546 * a way that it impacts the state of drawables being shown. 15547 * <p> 15548 * If the View has a StateListAnimator, it will also be called to run necessary state 15549 * change animations. 15550 * <p> 15551 * Be sure to call through to the superclass when overriding this function. 15552 * 15553 * @see Drawable#setState(int[]) 15554 */ 15555 protected void drawableStateChanged() { 15556 final Drawable d = mBackground; 15557 if (d != null && d.isStateful()) { 15558 d.setState(getDrawableState()); 15559 } 15560 15561 if (mStateListAnimator != null) { 15562 mStateListAnimator.setState(getDrawableState()); 15563 } 15564 } 15565 15566 /** 15567 * This function is called whenever the view hotspot changes and needs to 15568 * be propagated to drawables managed by the view. 15569 * <p> 15570 * Be sure to call through to the superclass when overriding this function. 15571 * 15572 * @param x hotspot x coordinate 15573 * @param y hotspot y coordinate 15574 */ 15575 public void drawableHotspotChanged(float x, float y) { 15576 if (mBackground != null) { 15577 mBackground.setHotspot(x, y); 15578 } 15579 } 15580 15581 /** 15582 * Call this to force a view to update its drawable state. This will cause 15583 * drawableStateChanged to be called on this view. Views that are interested 15584 * in the new state should call getDrawableState. 15585 * 15586 * @see #drawableStateChanged 15587 * @see #getDrawableState 15588 */ 15589 public void refreshDrawableState() { 15590 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 15591 drawableStateChanged(); 15592 15593 ViewParent parent = mParent; 15594 if (parent != null) { 15595 parent.childDrawableStateChanged(this); 15596 } 15597 } 15598 15599 /** 15600 * Return an array of resource IDs of the drawable states representing the 15601 * current state of the view. 15602 * 15603 * @return The current drawable state 15604 * 15605 * @see Drawable#setState(int[]) 15606 * @see #drawableStateChanged() 15607 * @see #onCreateDrawableState(int) 15608 */ 15609 public final int[] getDrawableState() { 15610 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 15611 return mDrawableState; 15612 } else { 15613 mDrawableState = onCreateDrawableState(0); 15614 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 15615 return mDrawableState; 15616 } 15617 } 15618 15619 /** 15620 * Generate the new {@link android.graphics.drawable.Drawable} state for 15621 * this view. This is called by the view 15622 * system when the cached Drawable state is determined to be invalid. To 15623 * retrieve the current state, you should use {@link #getDrawableState}. 15624 * 15625 * @param extraSpace if non-zero, this is the number of extra entries you 15626 * would like in the returned array in which you can place your own 15627 * states. 15628 * 15629 * @return Returns an array holding the current {@link Drawable} state of 15630 * the view. 15631 * 15632 * @see #mergeDrawableStates(int[], int[]) 15633 */ 15634 protected int[] onCreateDrawableState(int extraSpace) { 15635 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 15636 mParent instanceof View) { 15637 return ((View) mParent).onCreateDrawableState(extraSpace); 15638 } 15639 15640 int[] drawableState; 15641 15642 int privateFlags = mPrivateFlags; 15643 15644 int viewStateIndex = 0; 15645 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 15646 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 15647 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 15648 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 15649 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 15650 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 15651 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 15652 HardwareRenderer.isAvailable()) { 15653 // This is set if HW acceleration is requested, even if the current 15654 // process doesn't allow it. This is just to allow app preview 15655 // windows to better match their app. 15656 viewStateIndex |= VIEW_STATE_ACCELERATED; 15657 } 15658 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 15659 15660 final int privateFlags2 = mPrivateFlags2; 15661 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 15662 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 15663 15664 drawableState = VIEW_STATE_SETS[viewStateIndex]; 15665 15666 //noinspection ConstantIfStatement 15667 if (false) { 15668 Log.i("View", "drawableStateIndex=" + viewStateIndex); 15669 Log.i("View", toString() 15670 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 15671 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 15672 + " fo=" + hasFocus() 15673 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 15674 + " wf=" + hasWindowFocus() 15675 + ": " + Arrays.toString(drawableState)); 15676 } 15677 15678 if (extraSpace == 0) { 15679 return drawableState; 15680 } 15681 15682 final int[] fullState; 15683 if (drawableState != null) { 15684 fullState = new int[drawableState.length + extraSpace]; 15685 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 15686 } else { 15687 fullState = new int[extraSpace]; 15688 } 15689 15690 return fullState; 15691 } 15692 15693 /** 15694 * Merge your own state values in <var>additionalState</var> into the base 15695 * state values <var>baseState</var> that were returned by 15696 * {@link #onCreateDrawableState(int)}. 15697 * 15698 * @param baseState The base state values returned by 15699 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 15700 * own additional state values. 15701 * 15702 * @param additionalState The additional state values you would like 15703 * added to <var>baseState</var>; this array is not modified. 15704 * 15705 * @return As a convenience, the <var>baseState</var> array you originally 15706 * passed into the function is returned. 15707 * 15708 * @see #onCreateDrawableState(int) 15709 */ 15710 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 15711 final int N = baseState.length; 15712 int i = N - 1; 15713 while (i >= 0 && baseState[i] == 0) { 15714 i--; 15715 } 15716 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 15717 return baseState; 15718 } 15719 15720 /** 15721 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 15722 * on all Drawable objects associated with this view. 15723 * <p> 15724 * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator 15725 * attached to this view. 15726 */ 15727 public void jumpDrawablesToCurrentState() { 15728 if (mBackground != null) { 15729 mBackground.jumpToCurrentState(); 15730 } 15731 if (mStateListAnimator != null) { 15732 mStateListAnimator.jumpToCurrentState(); 15733 } 15734 } 15735 15736 /** 15737 * Sets the background color for this view. 15738 * @param color the color of the background 15739 */ 15740 @RemotableViewMethod 15741 public void setBackgroundColor(int color) { 15742 if (mBackground instanceof ColorDrawable) { 15743 ((ColorDrawable) mBackground.mutate()).setColor(color); 15744 computeOpaqueFlags(); 15745 mBackgroundResource = 0; 15746 } else { 15747 setBackground(new ColorDrawable(color)); 15748 } 15749 } 15750 15751 /** 15752 * Set the background to a given resource. The resource should refer to 15753 * a Drawable object or 0 to remove the background. 15754 * @param resid The identifier of the resource. 15755 * 15756 * @attr ref android.R.styleable#View_background 15757 */ 15758 @RemotableViewMethod 15759 public void setBackgroundResource(int resid) { 15760 if (resid != 0 && resid == mBackgroundResource) { 15761 return; 15762 } 15763 15764 Drawable d = null; 15765 if (resid != 0) { 15766 d = mContext.getDrawable(resid); 15767 } 15768 setBackground(d); 15769 15770 mBackgroundResource = resid; 15771 } 15772 15773 /** 15774 * Set the background to a given Drawable, or remove the background. If the 15775 * background has padding, this View's padding is set to the background's 15776 * padding. However, when a background is removed, this View's padding isn't 15777 * touched. If setting the padding is desired, please use 15778 * {@link #setPadding(int, int, int, int)}. 15779 * 15780 * @param background The Drawable to use as the background, or null to remove the 15781 * background 15782 */ 15783 public void setBackground(Drawable background) { 15784 //noinspection deprecation 15785 setBackgroundDrawable(background); 15786 } 15787 15788 /** 15789 * @deprecated use {@link #setBackground(Drawable)} instead 15790 */ 15791 @Deprecated 15792 public void setBackgroundDrawable(Drawable background) { 15793 computeOpaqueFlags(); 15794 15795 if (background == mBackground) { 15796 return; 15797 } 15798 15799 boolean requestLayout = false; 15800 15801 mBackgroundResource = 0; 15802 15803 /* 15804 * Regardless of whether we're setting a new background or not, we want 15805 * to clear the previous drawable. 15806 */ 15807 if (mBackground != null) { 15808 mBackground.setCallback(null); 15809 unscheduleDrawable(mBackground); 15810 } 15811 15812 if (background != null) { 15813 Rect padding = sThreadLocal.get(); 15814 if (padding == null) { 15815 padding = new Rect(); 15816 sThreadLocal.set(padding); 15817 } 15818 resetResolvedDrawables(); 15819 background.setLayoutDirection(getLayoutDirection()); 15820 if (background.getPadding(padding)) { 15821 resetResolvedPadding(); 15822 switch (background.getLayoutDirection()) { 15823 case LAYOUT_DIRECTION_RTL: 15824 mUserPaddingLeftInitial = padding.right; 15825 mUserPaddingRightInitial = padding.left; 15826 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 15827 break; 15828 case LAYOUT_DIRECTION_LTR: 15829 default: 15830 mUserPaddingLeftInitial = padding.left; 15831 mUserPaddingRightInitial = padding.right; 15832 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 15833 } 15834 mLeftPaddingDefined = false; 15835 mRightPaddingDefined = false; 15836 } 15837 15838 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 15839 // if it has a different minimum size, we should layout again 15840 if (mBackground == null 15841 || mBackground.getMinimumHeight() != background.getMinimumHeight() 15842 || mBackground.getMinimumWidth() != background.getMinimumWidth()) { 15843 requestLayout = true; 15844 } 15845 15846 background.setCallback(this); 15847 if (background.isStateful()) { 15848 background.setState(getDrawableState()); 15849 } 15850 background.setVisible(getVisibility() == VISIBLE, false); 15851 mBackground = background; 15852 15853 applyBackgroundTint(); 15854 15855 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 15856 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 15857 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 15858 requestLayout = true; 15859 } 15860 } else { 15861 /* Remove the background */ 15862 mBackground = null; 15863 15864 if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) { 15865 /* 15866 * This view ONLY drew the background before and we're removing 15867 * the background, so now it won't draw anything 15868 * (hence we SKIP_DRAW) 15869 */ 15870 mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND; 15871 mPrivateFlags |= PFLAG_SKIP_DRAW; 15872 } 15873 15874 /* 15875 * When the background is set, we try to apply its padding to this 15876 * View. When the background is removed, we don't touch this View's 15877 * padding. This is noted in the Javadocs. Hence, we don't need to 15878 * requestLayout(), the invalidate() below is sufficient. 15879 */ 15880 15881 // The old background's minimum size could have affected this 15882 // View's layout, so let's requestLayout 15883 requestLayout = true; 15884 } 15885 15886 computeOpaqueFlags(); 15887 15888 if (requestLayout) { 15889 requestLayout(); 15890 } 15891 15892 mBackgroundSizeChanged = true; 15893 invalidate(true); 15894 } 15895 15896 /** 15897 * Gets the background drawable 15898 * 15899 * @return The drawable used as the background for this view, if any. 15900 * 15901 * @see #setBackground(Drawable) 15902 * 15903 * @attr ref android.R.styleable#View_background 15904 */ 15905 public Drawable getBackground() { 15906 return mBackground; 15907 } 15908 15909 /** 15910 * Applies a tint to the background drawable. Does not modify the current tint 15911 * mode, which is {@link PorterDuff.Mode#SRC_ATOP} by default. 15912 * <p> 15913 * Subsequent calls to {@link #setBackground(Drawable)} will automatically 15914 * mutate the drawable and apply the specified tint and tint mode using 15915 * {@link Drawable#setTintList(ColorStateList)}. 15916 * 15917 * @param tint the tint to apply, may be {@code null} to clear tint 15918 * 15919 * @attr ref android.R.styleable#View_backgroundTint 15920 * @see #getBackgroundTintList() 15921 * @see Drawable#setTintList(ColorStateList) 15922 */ 15923 public void setBackgroundTintList(@Nullable ColorStateList tint) { 15924 mBackgroundTintList = tint; 15925 mHasBackgroundTint = true; 15926 15927 applyBackgroundTint(); 15928 } 15929 15930 /** 15931 * @return the tint applied to the background drawable 15932 * @attr ref android.R.styleable#View_backgroundTint 15933 * @see #setBackgroundTintList(ColorStateList) 15934 */ 15935 @Nullable 15936 public ColorStateList getBackgroundTintList() { 15937 return mBackgroundTintList; 15938 } 15939 15940 /** 15941 * Specifies the blending mode used to apply the tint specified by 15942 * {@link #setBackgroundTintList(ColorStateList)}} to the background drawable. 15943 * The default mode is {@link PorterDuff.Mode#SRC_ATOP}. 15944 * 15945 * @param tintMode the blending mode used to apply the tint, may be 15946 * {@code null} to clear tint 15947 * @attr ref android.R.styleable#View_backgroundTintMode 15948 * @see #getBackgroundTintMode() 15949 * @see Drawable#setTintMode(PorterDuff.Mode) 15950 */ 15951 public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) { 15952 mBackgroundTintMode = tintMode; 15953 15954 applyBackgroundTint(); 15955 } 15956 15957 /** 15958 * @return the blending mode used to apply the tint to the background drawable 15959 * @attr ref android.R.styleable#View_backgroundTintMode 15960 * @see #setBackgroundTintMode(PorterDuff.Mode) 15961 */ 15962 @Nullable 15963 public PorterDuff.Mode getBackgroundTintMode() { 15964 return mBackgroundTintMode; 15965 } 15966 15967 private void applyBackgroundTint() { 15968 if (mBackground != null && mHasBackgroundTint) { 15969 mBackground = mBackground.mutate(); 15970 mBackground.setTintList(mBackgroundTintList); 15971 mBackground.setTintMode(mBackgroundTintMode); 15972 } 15973 } 15974 15975 /** 15976 * Sets the padding. The view may add on the space required to display 15977 * the scrollbars, depending on the style and visibility of the scrollbars. 15978 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 15979 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 15980 * from the values set in this call. 15981 * 15982 * @attr ref android.R.styleable#View_padding 15983 * @attr ref android.R.styleable#View_paddingBottom 15984 * @attr ref android.R.styleable#View_paddingLeft 15985 * @attr ref android.R.styleable#View_paddingRight 15986 * @attr ref android.R.styleable#View_paddingTop 15987 * @param left the left padding in pixels 15988 * @param top the top padding in pixels 15989 * @param right the right padding in pixels 15990 * @param bottom the bottom padding in pixels 15991 */ 15992 public void setPadding(int left, int top, int right, int bottom) { 15993 resetResolvedPadding(); 15994 15995 mUserPaddingStart = UNDEFINED_PADDING; 15996 mUserPaddingEnd = UNDEFINED_PADDING; 15997 15998 mUserPaddingLeftInitial = left; 15999 mUserPaddingRightInitial = right; 16000 16001 mLeftPaddingDefined = true; 16002 mRightPaddingDefined = true; 16003 16004 internalSetPadding(left, top, right, bottom); 16005 } 16006 16007 /** 16008 * @hide 16009 */ 16010 protected void internalSetPadding(int left, int top, int right, int bottom) { 16011 mUserPaddingLeft = left; 16012 mUserPaddingRight = right; 16013 mUserPaddingBottom = bottom; 16014 16015 final int viewFlags = mViewFlags; 16016 boolean changed = false; 16017 16018 // Common case is there are no scroll bars. 16019 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 16020 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 16021 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 16022 ? 0 : getVerticalScrollbarWidth(); 16023 switch (mVerticalScrollbarPosition) { 16024 case SCROLLBAR_POSITION_DEFAULT: 16025 if (isLayoutRtl()) { 16026 left += offset; 16027 } else { 16028 right += offset; 16029 } 16030 break; 16031 case SCROLLBAR_POSITION_RIGHT: 16032 right += offset; 16033 break; 16034 case SCROLLBAR_POSITION_LEFT: 16035 left += offset; 16036 break; 16037 } 16038 } 16039 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 16040 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 16041 ? 0 : getHorizontalScrollbarHeight(); 16042 } 16043 } 16044 16045 if (mPaddingLeft != left) { 16046 changed = true; 16047 mPaddingLeft = left; 16048 } 16049 if (mPaddingTop != top) { 16050 changed = true; 16051 mPaddingTop = top; 16052 } 16053 if (mPaddingRight != right) { 16054 changed = true; 16055 mPaddingRight = right; 16056 } 16057 if (mPaddingBottom != bottom) { 16058 changed = true; 16059 mPaddingBottom = bottom; 16060 } 16061 16062 if (changed) { 16063 requestLayout(); 16064 } 16065 } 16066 16067 /** 16068 * Sets the relative padding. The view may add on the space required to display 16069 * the scrollbars, depending on the style and visibility of the scrollbars. 16070 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 16071 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 16072 * from the values set in this call. 16073 * 16074 * @attr ref android.R.styleable#View_padding 16075 * @attr ref android.R.styleable#View_paddingBottom 16076 * @attr ref android.R.styleable#View_paddingStart 16077 * @attr ref android.R.styleable#View_paddingEnd 16078 * @attr ref android.R.styleable#View_paddingTop 16079 * @param start the start padding in pixels 16080 * @param top the top padding in pixels 16081 * @param end the end padding in pixels 16082 * @param bottom the bottom padding in pixels 16083 */ 16084 public void setPaddingRelative(int start, int top, int end, int bottom) { 16085 resetResolvedPadding(); 16086 16087 mUserPaddingStart = start; 16088 mUserPaddingEnd = end; 16089 mLeftPaddingDefined = true; 16090 mRightPaddingDefined = true; 16091 16092 switch(getLayoutDirection()) { 16093 case LAYOUT_DIRECTION_RTL: 16094 mUserPaddingLeftInitial = end; 16095 mUserPaddingRightInitial = start; 16096 internalSetPadding(end, top, start, bottom); 16097 break; 16098 case LAYOUT_DIRECTION_LTR: 16099 default: 16100 mUserPaddingLeftInitial = start; 16101 mUserPaddingRightInitial = end; 16102 internalSetPadding(start, top, end, bottom); 16103 } 16104 } 16105 16106 /** 16107 * Returns the top padding of this view. 16108 * 16109 * @return the top padding in pixels 16110 */ 16111 public int getPaddingTop() { 16112 return mPaddingTop; 16113 } 16114 16115 /** 16116 * Returns the bottom padding of this view. If there are inset and enabled 16117 * scrollbars, this value may include the space required to display the 16118 * scrollbars as well. 16119 * 16120 * @return the bottom padding in pixels 16121 */ 16122 public int getPaddingBottom() { 16123 return mPaddingBottom; 16124 } 16125 16126 /** 16127 * Returns the left padding of this view. If there are inset and enabled 16128 * scrollbars, this value may include the space required to display the 16129 * scrollbars as well. 16130 * 16131 * @return the left padding in pixels 16132 */ 16133 public int getPaddingLeft() { 16134 if (!isPaddingResolved()) { 16135 resolvePadding(); 16136 } 16137 return mPaddingLeft; 16138 } 16139 16140 /** 16141 * Returns the start padding of this view depending on its resolved layout direction. 16142 * If there are inset and enabled scrollbars, this value may include the space 16143 * required to display the scrollbars as well. 16144 * 16145 * @return the start padding in pixels 16146 */ 16147 public int getPaddingStart() { 16148 if (!isPaddingResolved()) { 16149 resolvePadding(); 16150 } 16151 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 16152 mPaddingRight : mPaddingLeft; 16153 } 16154 16155 /** 16156 * Returns the right padding of this view. If there are inset and enabled 16157 * scrollbars, this value may include the space required to display the 16158 * scrollbars as well. 16159 * 16160 * @return the right padding in pixels 16161 */ 16162 public int getPaddingRight() { 16163 if (!isPaddingResolved()) { 16164 resolvePadding(); 16165 } 16166 return mPaddingRight; 16167 } 16168 16169 /** 16170 * Returns the end padding of this view depending on its resolved layout direction. 16171 * If there are inset and enabled scrollbars, this value may include the space 16172 * required to display the scrollbars as well. 16173 * 16174 * @return the end padding in pixels 16175 */ 16176 public int getPaddingEnd() { 16177 if (!isPaddingResolved()) { 16178 resolvePadding(); 16179 } 16180 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 16181 mPaddingLeft : mPaddingRight; 16182 } 16183 16184 /** 16185 * Return if the padding as been set thru relative values 16186 * {@link #setPaddingRelative(int, int, int, int)} or thru 16187 * @attr ref android.R.styleable#View_paddingStart or 16188 * @attr ref android.R.styleable#View_paddingEnd 16189 * 16190 * @return true if the padding is relative or false if it is not. 16191 */ 16192 public boolean isPaddingRelative() { 16193 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 16194 } 16195 16196 Insets computeOpticalInsets() { 16197 return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets(); 16198 } 16199 16200 /** 16201 * @hide 16202 */ 16203 public void resetPaddingToInitialValues() { 16204 if (isRtlCompatibilityMode()) { 16205 mPaddingLeft = mUserPaddingLeftInitial; 16206 mPaddingRight = mUserPaddingRightInitial; 16207 return; 16208 } 16209 if (isLayoutRtl()) { 16210 mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial; 16211 mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial; 16212 } else { 16213 mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial; 16214 mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial; 16215 } 16216 } 16217 16218 /** 16219 * @hide 16220 */ 16221 public Insets getOpticalInsets() { 16222 if (mLayoutInsets == null) { 16223 mLayoutInsets = computeOpticalInsets(); 16224 } 16225 return mLayoutInsets; 16226 } 16227 16228 /** 16229 * Set this view's optical insets. 16230 * 16231 * <p>This method should be treated similarly to setMeasuredDimension and not as a general 16232 * property. Views that compute their own optical insets should call it as part of measurement. 16233 * This method does not request layout. If you are setting optical insets outside of 16234 * measure/layout itself you will want to call requestLayout() yourself. 16235 * </p> 16236 * @hide 16237 */ 16238 public void setOpticalInsets(Insets insets) { 16239 mLayoutInsets = insets; 16240 } 16241 16242 /** 16243 * Changes the selection state of this view. A view can be selected or not. 16244 * Note that selection is not the same as focus. Views are typically 16245 * selected in the context of an AdapterView like ListView or GridView; 16246 * the selected view is the view that is highlighted. 16247 * 16248 * @param selected true if the view must be selected, false otherwise 16249 */ 16250 public void setSelected(boolean selected) { 16251 //noinspection DoubleNegation 16252 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 16253 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 16254 if (!selected) resetPressedState(); 16255 invalidate(true); 16256 refreshDrawableState(); 16257 dispatchSetSelected(selected); 16258 notifyViewAccessibilityStateChangedIfNeeded( 16259 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 16260 } 16261 } 16262 16263 /** 16264 * Dispatch setSelected to all of this View's children. 16265 * 16266 * @see #setSelected(boolean) 16267 * 16268 * @param selected The new selected state 16269 */ 16270 protected void dispatchSetSelected(boolean selected) { 16271 } 16272 16273 /** 16274 * Indicates the selection state of this view. 16275 * 16276 * @return true if the view is selected, false otherwise 16277 */ 16278 @ViewDebug.ExportedProperty 16279 public boolean isSelected() { 16280 return (mPrivateFlags & PFLAG_SELECTED) != 0; 16281 } 16282 16283 /** 16284 * Changes the activated state of this view. A view can be activated or not. 16285 * Note that activation is not the same as selection. Selection is 16286 * a transient property, representing the view (hierarchy) the user is 16287 * currently interacting with. Activation is a longer-term state that the 16288 * user can move views in and out of. For example, in a list view with 16289 * single or multiple selection enabled, the views in the current selection 16290 * set are activated. (Um, yeah, we are deeply sorry about the terminology 16291 * here.) The activated state is propagated down to children of the view it 16292 * is set on. 16293 * 16294 * @param activated true if the view must be activated, false otherwise 16295 */ 16296 public void setActivated(boolean activated) { 16297 //noinspection DoubleNegation 16298 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 16299 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 16300 invalidate(true); 16301 refreshDrawableState(); 16302 dispatchSetActivated(activated); 16303 } 16304 } 16305 16306 /** 16307 * Dispatch setActivated to all of this View's children. 16308 * 16309 * @see #setActivated(boolean) 16310 * 16311 * @param activated The new activated state 16312 */ 16313 protected void dispatchSetActivated(boolean activated) { 16314 } 16315 16316 /** 16317 * Indicates the activation state of this view. 16318 * 16319 * @return true if the view is activated, false otherwise 16320 */ 16321 @ViewDebug.ExportedProperty 16322 public boolean isActivated() { 16323 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 16324 } 16325 16326 /** 16327 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 16328 * observer can be used to get notifications when global events, like 16329 * layout, happen. 16330 * 16331 * The returned ViewTreeObserver observer is not guaranteed to remain 16332 * valid for the lifetime of this View. If the caller of this method keeps 16333 * a long-lived reference to ViewTreeObserver, it should always check for 16334 * the return value of {@link ViewTreeObserver#isAlive()}. 16335 * 16336 * @return The ViewTreeObserver for this view's hierarchy. 16337 */ 16338 public ViewTreeObserver getViewTreeObserver() { 16339 if (mAttachInfo != null) { 16340 return mAttachInfo.mTreeObserver; 16341 } 16342 if (mFloatingTreeObserver == null) { 16343 mFloatingTreeObserver = new ViewTreeObserver(); 16344 } 16345 return mFloatingTreeObserver; 16346 } 16347 16348 /** 16349 * <p>Finds the topmost view in the current view hierarchy.</p> 16350 * 16351 * @return the topmost view containing this view 16352 */ 16353 public View getRootView() { 16354 if (mAttachInfo != null) { 16355 final View v = mAttachInfo.mRootView; 16356 if (v != null) { 16357 return v; 16358 } 16359 } 16360 16361 View parent = this; 16362 16363 while (parent.mParent != null && parent.mParent instanceof View) { 16364 parent = (View) parent.mParent; 16365 } 16366 16367 return parent; 16368 } 16369 16370 /** 16371 * Transforms a motion event from view-local coordinates to on-screen 16372 * coordinates. 16373 * 16374 * @param ev the view-local motion event 16375 * @return false if the transformation could not be applied 16376 * @hide 16377 */ 16378 public boolean toGlobalMotionEvent(MotionEvent ev) { 16379 final AttachInfo info = mAttachInfo; 16380 if (info == null) { 16381 return false; 16382 } 16383 16384 final Matrix m = info.mTmpMatrix; 16385 m.set(Matrix.IDENTITY_MATRIX); 16386 transformMatrixToGlobal(m); 16387 ev.transform(m); 16388 return true; 16389 } 16390 16391 /** 16392 * Transforms a motion event from on-screen coordinates to view-local 16393 * coordinates. 16394 * 16395 * @param ev the on-screen motion event 16396 * @return false if the transformation could not be applied 16397 * @hide 16398 */ 16399 public boolean toLocalMotionEvent(MotionEvent ev) { 16400 final AttachInfo info = mAttachInfo; 16401 if (info == null) { 16402 return false; 16403 } 16404 16405 final Matrix m = info.mTmpMatrix; 16406 m.set(Matrix.IDENTITY_MATRIX); 16407 transformMatrixToLocal(m); 16408 ev.transform(m); 16409 return true; 16410 } 16411 16412 /** 16413 * Modifies the input matrix such that it maps view-local coordinates to 16414 * on-screen coordinates. 16415 * 16416 * @param m input matrix to modify 16417 * @hide 16418 */ 16419 public void transformMatrixToGlobal(Matrix m) { 16420 final ViewParent parent = mParent; 16421 if (parent instanceof View) { 16422 final View vp = (View) parent; 16423 vp.transformMatrixToGlobal(m); 16424 m.preTranslate(-vp.mScrollX, -vp.mScrollY); 16425 } else if (parent instanceof ViewRootImpl) { 16426 final ViewRootImpl vr = (ViewRootImpl) parent; 16427 vr.transformMatrixToGlobal(m); 16428 m.preTranslate(0, -vr.mCurScrollY); 16429 } 16430 16431 m.preTranslate(mLeft, mTop); 16432 16433 if (!hasIdentityMatrix()) { 16434 m.preConcat(getMatrix()); 16435 } 16436 } 16437 16438 /** 16439 * Modifies the input matrix such that it maps on-screen coordinates to 16440 * view-local coordinates. 16441 * 16442 * @param m input matrix to modify 16443 * @hide 16444 */ 16445 public void transformMatrixToLocal(Matrix m) { 16446 final ViewParent parent = mParent; 16447 if (parent instanceof View) { 16448 final View vp = (View) parent; 16449 vp.transformMatrixToLocal(m); 16450 m.postTranslate(vp.mScrollX, vp.mScrollY); 16451 } else if (parent instanceof ViewRootImpl) { 16452 final ViewRootImpl vr = (ViewRootImpl) parent; 16453 vr.transformMatrixToLocal(m); 16454 m.postTranslate(0, vr.mCurScrollY); 16455 } 16456 16457 m.postTranslate(-mLeft, -mTop); 16458 16459 if (!hasIdentityMatrix()) { 16460 m.postConcat(getInverseMatrix()); 16461 } 16462 } 16463 16464 /** 16465 * @hide 16466 */ 16467 @ViewDebug.ExportedProperty(category = "layout", indexMapping = { 16468 @ViewDebug.IntToString(from = 0, to = "x"), 16469 @ViewDebug.IntToString(from = 1, to = "y") 16470 }) 16471 public int[] getLocationOnScreen() { 16472 int[] location = new int[2]; 16473 getLocationOnScreen(location); 16474 return location; 16475 } 16476 16477 /** 16478 * <p>Computes the coordinates of this view on the screen. The argument 16479 * must be an array of two integers. After the method returns, the array 16480 * contains the x and y location in that order.</p> 16481 * 16482 * @param location an array of two integers in which to hold the coordinates 16483 */ 16484 public void getLocationOnScreen(int[] location) { 16485 getLocationInWindow(location); 16486 16487 final AttachInfo info = mAttachInfo; 16488 if (info != null) { 16489 location[0] += info.mWindowLeft; 16490 location[1] += info.mWindowTop; 16491 } 16492 } 16493 16494 /** 16495 * <p>Computes the coordinates of this view in its window. The argument 16496 * must be an array of two integers. After the method returns, the array 16497 * contains the x and y location in that order.</p> 16498 * 16499 * @param location an array of two integers in which to hold the coordinates 16500 */ 16501 public void getLocationInWindow(int[] location) { 16502 if (location == null || location.length < 2) { 16503 throw new IllegalArgumentException("location must be an array of two integers"); 16504 } 16505 16506 if (mAttachInfo == null) { 16507 // When the view is not attached to a window, this method does not make sense 16508 location[0] = location[1] = 0; 16509 return; 16510 } 16511 16512 float[] position = mAttachInfo.mTmpTransformLocation; 16513 position[0] = position[1] = 0.0f; 16514 16515 if (!hasIdentityMatrix()) { 16516 getMatrix().mapPoints(position); 16517 } 16518 16519 position[0] += mLeft; 16520 position[1] += mTop; 16521 16522 ViewParent viewParent = mParent; 16523 while (viewParent instanceof View) { 16524 final View view = (View) viewParent; 16525 16526 position[0] -= view.mScrollX; 16527 position[1] -= view.mScrollY; 16528 16529 if (!view.hasIdentityMatrix()) { 16530 view.getMatrix().mapPoints(position); 16531 } 16532 16533 position[0] += view.mLeft; 16534 position[1] += view.mTop; 16535 16536 viewParent = view.mParent; 16537 } 16538 16539 if (viewParent instanceof ViewRootImpl) { 16540 // *cough* 16541 final ViewRootImpl vr = (ViewRootImpl) viewParent; 16542 position[1] -= vr.mCurScrollY; 16543 } 16544 16545 location[0] = (int) (position[0] + 0.5f); 16546 location[1] = (int) (position[1] + 0.5f); 16547 } 16548 16549 /** 16550 * {@hide} 16551 * @param id the id of the view to be found 16552 * @return the view of the specified id, null if cannot be found 16553 */ 16554 protected View findViewTraversal(int id) { 16555 if (id == mID) { 16556 return this; 16557 } 16558 return null; 16559 } 16560 16561 /** 16562 * {@hide} 16563 * @param tag the tag of the view to be found 16564 * @return the view of specified tag, null if cannot be found 16565 */ 16566 protected View findViewWithTagTraversal(Object tag) { 16567 if (tag != null && tag.equals(mTag)) { 16568 return this; 16569 } 16570 return null; 16571 } 16572 16573 /** 16574 * {@hide} 16575 * @param predicate The predicate to evaluate. 16576 * @param childToSkip If not null, ignores this child during the recursive traversal. 16577 * @return The first view that matches the predicate or null. 16578 */ 16579 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 16580 if (predicate.apply(this)) { 16581 return this; 16582 } 16583 return null; 16584 } 16585 16586 /** 16587 * Look for a child view with the given id. If this view has the given 16588 * id, return this view. 16589 * 16590 * @param id The id to search for. 16591 * @return The view that has the given id in the hierarchy or null 16592 */ 16593 public final View findViewById(int id) { 16594 if (id < 0) { 16595 return null; 16596 } 16597 return findViewTraversal(id); 16598 } 16599 16600 /** 16601 * Finds a view by its unuque and stable accessibility id. 16602 * 16603 * @param accessibilityId The searched accessibility id. 16604 * @return The found view. 16605 */ 16606 final View findViewByAccessibilityId(int accessibilityId) { 16607 if (accessibilityId < 0) { 16608 return null; 16609 } 16610 return findViewByAccessibilityIdTraversal(accessibilityId); 16611 } 16612 16613 /** 16614 * Performs the traversal to find a view by its unuque and stable accessibility id. 16615 * 16616 * <strong>Note:</strong>This method does not stop at the root namespace 16617 * boundary since the user can touch the screen at an arbitrary location 16618 * potentially crossing the root namespace bounday which will send an 16619 * accessibility event to accessibility services and they should be able 16620 * to obtain the event source. Also accessibility ids are guaranteed to be 16621 * unique in the window. 16622 * 16623 * @param accessibilityId The accessibility id. 16624 * @return The found view. 16625 * 16626 * @hide 16627 */ 16628 public View findViewByAccessibilityIdTraversal(int accessibilityId) { 16629 if (getAccessibilityViewId() == accessibilityId) { 16630 return this; 16631 } 16632 return null; 16633 } 16634 16635 /** 16636 * Look for a child view with the given tag. If this view has the given 16637 * tag, return this view. 16638 * 16639 * @param tag The tag to search for, using "tag.equals(getTag())". 16640 * @return The View that has the given tag in the hierarchy or null 16641 */ 16642 public final View findViewWithTag(Object tag) { 16643 if (tag == null) { 16644 return null; 16645 } 16646 return findViewWithTagTraversal(tag); 16647 } 16648 16649 /** 16650 * {@hide} 16651 * Look for a child view that matches the specified predicate. 16652 * If this view matches the predicate, return this view. 16653 * 16654 * @param predicate The predicate to evaluate. 16655 * @return The first view that matches the predicate or null. 16656 */ 16657 public final View findViewByPredicate(Predicate<View> predicate) { 16658 return findViewByPredicateTraversal(predicate, null); 16659 } 16660 16661 /** 16662 * {@hide} 16663 * Look for a child view that matches the specified predicate, 16664 * starting with the specified view and its descendents and then 16665 * recusively searching the ancestors and siblings of that view 16666 * until this view is reached. 16667 * 16668 * This method is useful in cases where the predicate does not match 16669 * a single unique view (perhaps multiple views use the same id) 16670 * and we are trying to find the view that is "closest" in scope to the 16671 * starting view. 16672 * 16673 * @param start The view to start from. 16674 * @param predicate The predicate to evaluate. 16675 * @return The first view that matches the predicate or null. 16676 */ 16677 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 16678 View childToSkip = null; 16679 for (;;) { 16680 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 16681 if (view != null || start == this) { 16682 return view; 16683 } 16684 16685 ViewParent parent = start.getParent(); 16686 if (parent == null || !(parent instanceof View)) { 16687 return null; 16688 } 16689 16690 childToSkip = start; 16691 start = (View) parent; 16692 } 16693 } 16694 16695 /** 16696 * Sets the identifier for this view. The identifier does not have to be 16697 * unique in this view's hierarchy. The identifier should be a positive 16698 * number. 16699 * 16700 * @see #NO_ID 16701 * @see #getId() 16702 * @see #findViewById(int) 16703 * 16704 * @param id a number used to identify the view 16705 * 16706 * @attr ref android.R.styleable#View_id 16707 */ 16708 public void setId(int id) { 16709 mID = id; 16710 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 16711 mID = generateViewId(); 16712 } 16713 } 16714 16715 /** 16716 * {@hide} 16717 * 16718 * @param isRoot true if the view belongs to the root namespace, false 16719 * otherwise 16720 */ 16721 public void setIsRootNamespace(boolean isRoot) { 16722 if (isRoot) { 16723 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 16724 } else { 16725 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 16726 } 16727 } 16728 16729 /** 16730 * {@hide} 16731 * 16732 * @return true if the view belongs to the root namespace, false otherwise 16733 */ 16734 public boolean isRootNamespace() { 16735 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 16736 } 16737 16738 /** 16739 * Returns this view's identifier. 16740 * 16741 * @return a positive integer used to identify the view or {@link #NO_ID} 16742 * if the view has no ID 16743 * 16744 * @see #setId(int) 16745 * @see #findViewById(int) 16746 * @attr ref android.R.styleable#View_id 16747 */ 16748 @ViewDebug.CapturedViewProperty 16749 public int getId() { 16750 return mID; 16751 } 16752 16753 /** 16754 * Returns this view's tag. 16755 * 16756 * @return the Object stored in this view as a tag, or {@code null} if not 16757 * set 16758 * 16759 * @see #setTag(Object) 16760 * @see #getTag(int) 16761 */ 16762 @ViewDebug.ExportedProperty 16763 public Object getTag() { 16764 return mTag; 16765 } 16766 16767 /** 16768 * Sets the tag associated with this view. A tag can be used to mark 16769 * a view in its hierarchy and does not have to be unique within the 16770 * hierarchy. Tags can also be used to store data within a view without 16771 * resorting to another data structure. 16772 * 16773 * @param tag an Object to tag the view with 16774 * 16775 * @see #getTag() 16776 * @see #setTag(int, Object) 16777 */ 16778 public void setTag(final Object tag) { 16779 mTag = tag; 16780 } 16781 16782 /** 16783 * Returns the tag associated with this view and the specified key. 16784 * 16785 * @param key The key identifying the tag 16786 * 16787 * @return the Object stored in this view as a tag, or {@code null} if not 16788 * set 16789 * 16790 * @see #setTag(int, Object) 16791 * @see #getTag() 16792 */ 16793 public Object getTag(int key) { 16794 if (mKeyedTags != null) return mKeyedTags.get(key); 16795 return null; 16796 } 16797 16798 /** 16799 * Sets a tag associated with this view and a key. A tag can be used 16800 * to mark a view in its hierarchy and does not have to be unique within 16801 * the hierarchy. Tags can also be used to store data within a view 16802 * without resorting to another data structure. 16803 * 16804 * The specified key should be an id declared in the resources of the 16805 * application to ensure it is unique (see the <a 16806 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 16807 * Keys identified as belonging to 16808 * the Android framework or not associated with any package will cause 16809 * an {@link IllegalArgumentException} to be thrown. 16810 * 16811 * @param key The key identifying the tag 16812 * @param tag An Object to tag the view with 16813 * 16814 * @throws IllegalArgumentException If they specified key is not valid 16815 * 16816 * @see #setTag(Object) 16817 * @see #getTag(int) 16818 */ 16819 public void setTag(int key, final Object tag) { 16820 // If the package id is 0x00 or 0x01, it's either an undefined package 16821 // or a framework id 16822 if ((key >>> 24) < 2) { 16823 throw new IllegalArgumentException("The key must be an application-specific " 16824 + "resource id."); 16825 } 16826 16827 setKeyedTag(key, tag); 16828 } 16829 16830 /** 16831 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 16832 * framework id. 16833 * 16834 * @hide 16835 */ 16836 public void setTagInternal(int key, Object tag) { 16837 if ((key >>> 24) != 0x1) { 16838 throw new IllegalArgumentException("The key must be a framework-specific " 16839 + "resource id."); 16840 } 16841 16842 setKeyedTag(key, tag); 16843 } 16844 16845 private void setKeyedTag(int key, Object tag) { 16846 if (mKeyedTags == null) { 16847 mKeyedTags = new SparseArray<Object>(2); 16848 } 16849 16850 mKeyedTags.put(key, tag); 16851 } 16852 16853 /** 16854 * Prints information about this view in the log output, with the tag 16855 * {@link #VIEW_LOG_TAG}. 16856 * 16857 * @hide 16858 */ 16859 public void debug() { 16860 debug(0); 16861 } 16862 16863 /** 16864 * Prints information about this view in the log output, with the tag 16865 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 16866 * indentation defined by the <code>depth</code>. 16867 * 16868 * @param depth the indentation level 16869 * 16870 * @hide 16871 */ 16872 protected void debug(int depth) { 16873 String output = debugIndent(depth - 1); 16874 16875 output += "+ " + this; 16876 int id = getId(); 16877 if (id != -1) { 16878 output += " (id=" + id + ")"; 16879 } 16880 Object tag = getTag(); 16881 if (tag != null) { 16882 output += " (tag=" + tag + ")"; 16883 } 16884 Log.d(VIEW_LOG_TAG, output); 16885 16886 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 16887 output = debugIndent(depth) + " FOCUSED"; 16888 Log.d(VIEW_LOG_TAG, output); 16889 } 16890 16891 output = debugIndent(depth); 16892 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 16893 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 16894 + "} "; 16895 Log.d(VIEW_LOG_TAG, output); 16896 16897 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 16898 || mPaddingBottom != 0) { 16899 output = debugIndent(depth); 16900 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 16901 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 16902 Log.d(VIEW_LOG_TAG, output); 16903 } 16904 16905 output = debugIndent(depth); 16906 output += "mMeasureWidth=" + mMeasuredWidth + 16907 " mMeasureHeight=" + mMeasuredHeight; 16908 Log.d(VIEW_LOG_TAG, output); 16909 16910 output = debugIndent(depth); 16911 if (mLayoutParams == null) { 16912 output += "BAD! no layout params"; 16913 } else { 16914 output = mLayoutParams.debug(output); 16915 } 16916 Log.d(VIEW_LOG_TAG, output); 16917 16918 output = debugIndent(depth); 16919 output += "flags={"; 16920 output += View.printFlags(mViewFlags); 16921 output += "}"; 16922 Log.d(VIEW_LOG_TAG, output); 16923 16924 output = debugIndent(depth); 16925 output += "privateFlags={"; 16926 output += View.printPrivateFlags(mPrivateFlags); 16927 output += "}"; 16928 Log.d(VIEW_LOG_TAG, output); 16929 } 16930 16931 /** 16932 * Creates a string of whitespaces used for indentation. 16933 * 16934 * @param depth the indentation level 16935 * @return a String containing (depth * 2 + 3) * 2 white spaces 16936 * 16937 * @hide 16938 */ 16939 protected static String debugIndent(int depth) { 16940 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 16941 for (int i = 0; i < (depth * 2) + 3; i++) { 16942 spaces.append(' ').append(' '); 16943 } 16944 return spaces.toString(); 16945 } 16946 16947 /** 16948 * <p>Return the offset of the widget's text baseline from the widget's top 16949 * boundary. If this widget does not support baseline alignment, this 16950 * method returns -1. </p> 16951 * 16952 * @return the offset of the baseline within the widget's bounds or -1 16953 * if baseline alignment is not supported 16954 */ 16955 @ViewDebug.ExportedProperty(category = "layout") 16956 public int getBaseline() { 16957 return -1; 16958 } 16959 16960 /** 16961 * Returns whether the view hierarchy is currently undergoing a layout pass. This 16962 * information is useful to avoid situations such as calling {@link #requestLayout()} during 16963 * a layout pass. 16964 * 16965 * @return whether the view hierarchy is currently undergoing a layout pass 16966 */ 16967 public boolean isInLayout() { 16968 ViewRootImpl viewRoot = getViewRootImpl(); 16969 return (viewRoot != null && viewRoot.isInLayout()); 16970 } 16971 16972 /** 16973 * Call this when something has changed which has invalidated the 16974 * layout of this view. This will schedule a layout pass of the view 16975 * tree. This should not be called while the view hierarchy is currently in a layout 16976 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 16977 * end of the current layout pass (and then layout will run again) or after the current 16978 * frame is drawn and the next layout occurs. 16979 * 16980 * <p>Subclasses which override this method should call the superclass method to 16981 * handle possible request-during-layout errors correctly.</p> 16982 */ 16983 public void requestLayout() { 16984 if (mMeasureCache != null) mMeasureCache.clear(); 16985 16986 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) { 16987 // Only trigger request-during-layout logic if this is the view requesting it, 16988 // not the views in its parent hierarchy 16989 ViewRootImpl viewRoot = getViewRootImpl(); 16990 if (viewRoot != null && viewRoot.isInLayout()) { 16991 if (!viewRoot.requestLayoutDuringLayout(this)) { 16992 return; 16993 } 16994 } 16995 mAttachInfo.mViewRequestingLayout = this; 16996 } 16997 16998 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 16999 mPrivateFlags |= PFLAG_INVALIDATED; 17000 17001 if (mParent != null && !mParent.isLayoutRequested()) { 17002 mParent.requestLayout(); 17003 } 17004 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) { 17005 mAttachInfo.mViewRequestingLayout = null; 17006 } 17007 } 17008 17009 /** 17010 * Forces this view to be laid out during the next layout pass. 17011 * This method does not call requestLayout() or forceLayout() 17012 * on the parent. 17013 */ 17014 public void forceLayout() { 17015 if (mMeasureCache != null) mMeasureCache.clear(); 17016 17017 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 17018 mPrivateFlags |= PFLAG_INVALIDATED; 17019 } 17020 17021 /** 17022 * <p> 17023 * This is called to find out how big a view should be. The parent 17024 * supplies constraint information in the width and height parameters. 17025 * </p> 17026 * 17027 * <p> 17028 * The actual measurement work of a view is performed in 17029 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 17030 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 17031 * </p> 17032 * 17033 * 17034 * @param widthMeasureSpec Horizontal space requirements as imposed by the 17035 * parent 17036 * @param heightMeasureSpec Vertical space requirements as imposed by the 17037 * parent 17038 * 17039 * @see #onMeasure(int, int) 17040 */ 17041 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 17042 boolean optical = isLayoutModeOptical(this); 17043 if (optical != isLayoutModeOptical(mParent)) { 17044 Insets insets = getOpticalInsets(); 17045 int oWidth = insets.left + insets.right; 17046 int oHeight = insets.top + insets.bottom; 17047 widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth); 17048 heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight); 17049 } 17050 17051 // Suppress sign extension for the low bytes 17052 long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL; 17053 if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2); 17054 17055 if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT || 17056 widthMeasureSpec != mOldWidthMeasureSpec || 17057 heightMeasureSpec != mOldHeightMeasureSpec) { 17058 17059 // first clears the measured dimension flag 17060 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 17061 17062 resolveRtlPropertiesIfNeeded(); 17063 17064 int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 : 17065 mMeasureCache.indexOfKey(key); 17066 if (cacheIndex < 0 || sIgnoreMeasureCache) { 17067 // measure ourselves, this should set the measured dimension flag back 17068 onMeasure(widthMeasureSpec, heightMeasureSpec); 17069 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 17070 } else { 17071 long value = mMeasureCache.valueAt(cacheIndex); 17072 // Casting a long to int drops the high 32 bits, no mask needed 17073 setMeasuredDimensionRaw((int) (value >> 32), (int) value); 17074 mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 17075 } 17076 17077 // flag not set, setMeasuredDimension() was not invoked, we raise 17078 // an exception to warn the developer 17079 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 17080 throw new IllegalStateException("onMeasure() did not set the" 17081 + " measured dimension by calling" 17082 + " setMeasuredDimension()"); 17083 } 17084 17085 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 17086 } 17087 17088 mOldWidthMeasureSpec = widthMeasureSpec; 17089 mOldHeightMeasureSpec = heightMeasureSpec; 17090 17091 mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 | 17092 (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension 17093 } 17094 17095 /** 17096 * <p> 17097 * Measure the view and its content to determine the measured width and the 17098 * measured height. This method is invoked by {@link #measure(int, int)} and 17099 * should be overriden by subclasses to provide accurate and efficient 17100 * measurement of their contents. 17101 * </p> 17102 * 17103 * <p> 17104 * <strong>CONTRACT:</strong> When overriding this method, you 17105 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 17106 * measured width and height of this view. Failure to do so will trigger an 17107 * <code>IllegalStateException</code>, thrown by 17108 * {@link #measure(int, int)}. Calling the superclass' 17109 * {@link #onMeasure(int, int)} is a valid use. 17110 * </p> 17111 * 17112 * <p> 17113 * The base class implementation of measure defaults to the background size, 17114 * unless a larger size is allowed by the MeasureSpec. Subclasses should 17115 * override {@link #onMeasure(int, int)} to provide better measurements of 17116 * their content. 17117 * </p> 17118 * 17119 * <p> 17120 * If this method is overridden, it is the subclass's responsibility to make 17121 * sure the measured height and width are at least the view's minimum height 17122 * and width ({@link #getSuggestedMinimumHeight()} and 17123 * {@link #getSuggestedMinimumWidth()}). 17124 * </p> 17125 * 17126 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 17127 * The requirements are encoded with 17128 * {@link android.view.View.MeasureSpec}. 17129 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 17130 * The requirements are encoded with 17131 * {@link android.view.View.MeasureSpec}. 17132 * 17133 * @see #getMeasuredWidth() 17134 * @see #getMeasuredHeight() 17135 * @see #setMeasuredDimension(int, int) 17136 * @see #getSuggestedMinimumHeight() 17137 * @see #getSuggestedMinimumWidth() 17138 * @see android.view.View.MeasureSpec#getMode(int) 17139 * @see android.view.View.MeasureSpec#getSize(int) 17140 */ 17141 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 17142 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 17143 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 17144 } 17145 17146 /** 17147 * <p>This method must be called by {@link #onMeasure(int, int)} to store the 17148 * measured width and measured height. Failing to do so will trigger an 17149 * exception at measurement time.</p> 17150 * 17151 * @param measuredWidth The measured width of this view. May be a complex 17152 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17153 * {@link #MEASURED_STATE_TOO_SMALL}. 17154 * @param measuredHeight The measured height of this view. May be a complex 17155 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17156 * {@link #MEASURED_STATE_TOO_SMALL}. 17157 */ 17158 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 17159 boolean optical = isLayoutModeOptical(this); 17160 if (optical != isLayoutModeOptical(mParent)) { 17161 Insets insets = getOpticalInsets(); 17162 int opticalWidth = insets.left + insets.right; 17163 int opticalHeight = insets.top + insets.bottom; 17164 17165 measuredWidth += optical ? opticalWidth : -opticalWidth; 17166 measuredHeight += optical ? opticalHeight : -opticalHeight; 17167 } 17168 setMeasuredDimensionRaw(measuredWidth, measuredHeight); 17169 } 17170 17171 /** 17172 * Sets the measured dimension without extra processing for things like optical bounds. 17173 * Useful for reapplying consistent values that have already been cooked with adjustments 17174 * for optical bounds, etc. such as those from the measurement cache. 17175 * 17176 * @param measuredWidth The measured width of this view. May be a complex 17177 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17178 * {@link #MEASURED_STATE_TOO_SMALL}. 17179 * @param measuredHeight The measured height of this view. May be a complex 17180 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17181 * {@link #MEASURED_STATE_TOO_SMALL}. 17182 */ 17183 private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) { 17184 mMeasuredWidth = measuredWidth; 17185 mMeasuredHeight = measuredHeight; 17186 17187 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 17188 } 17189 17190 /** 17191 * Merge two states as returned by {@link #getMeasuredState()}. 17192 * @param curState The current state as returned from a view or the result 17193 * of combining multiple views. 17194 * @param newState The new view state to combine. 17195 * @return Returns a new integer reflecting the combination of the two 17196 * states. 17197 */ 17198 public static int combineMeasuredStates(int curState, int newState) { 17199 return curState | newState; 17200 } 17201 17202 /** 17203 * Version of {@link #resolveSizeAndState(int, int, int)} 17204 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 17205 */ 17206 public static int resolveSize(int size, int measureSpec) { 17207 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 17208 } 17209 17210 /** 17211 * Utility to reconcile a desired size and state, with constraints imposed 17212 * by a MeasureSpec. Will take the desired size, unless a different size 17213 * is imposed by the constraints. The returned value is a compound integer, 17214 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 17215 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 17216 * size is smaller than the size the view wants to be. 17217 * 17218 * @param size How big the view wants to be 17219 * @param measureSpec Constraints imposed by the parent 17220 * @return Size information bit mask as defined by 17221 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 17222 */ 17223 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 17224 int result = size; 17225 int specMode = MeasureSpec.getMode(measureSpec); 17226 int specSize = MeasureSpec.getSize(measureSpec); 17227 switch (specMode) { 17228 case MeasureSpec.UNSPECIFIED: 17229 result = size; 17230 break; 17231 case MeasureSpec.AT_MOST: 17232 if (specSize < size) { 17233 result = specSize | MEASURED_STATE_TOO_SMALL; 17234 } else { 17235 result = size; 17236 } 17237 break; 17238 case MeasureSpec.EXACTLY: 17239 result = specSize; 17240 break; 17241 } 17242 return result | (childMeasuredState&MEASURED_STATE_MASK); 17243 } 17244 17245 /** 17246 * Utility to return a default size. Uses the supplied size if the 17247 * MeasureSpec imposed no constraints. Will get larger if allowed 17248 * by the MeasureSpec. 17249 * 17250 * @param size Default size for this view 17251 * @param measureSpec Constraints imposed by the parent 17252 * @return The size this view should be. 17253 */ 17254 public static int getDefaultSize(int size, int measureSpec) { 17255 int result = size; 17256 int specMode = MeasureSpec.getMode(measureSpec); 17257 int specSize = MeasureSpec.getSize(measureSpec); 17258 17259 switch (specMode) { 17260 case MeasureSpec.UNSPECIFIED: 17261 result = size; 17262 break; 17263 case MeasureSpec.AT_MOST: 17264 case MeasureSpec.EXACTLY: 17265 result = specSize; 17266 break; 17267 } 17268 return result; 17269 } 17270 17271 /** 17272 * Returns the suggested minimum height that the view should use. This 17273 * returns the maximum of the view's minimum height 17274 * and the background's minimum height 17275 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 17276 * <p> 17277 * When being used in {@link #onMeasure(int, int)}, the caller should still 17278 * ensure the returned height is within the requirements of the parent. 17279 * 17280 * @return The suggested minimum height of the view. 17281 */ 17282 protected int getSuggestedMinimumHeight() { 17283 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 17284 17285 } 17286 17287 /** 17288 * Returns the suggested minimum width that the view should use. This 17289 * returns the maximum of the view's minimum width) 17290 * and the background's minimum width 17291 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 17292 * <p> 17293 * When being used in {@link #onMeasure(int, int)}, the caller should still 17294 * ensure the returned width is within the requirements of the parent. 17295 * 17296 * @return The suggested minimum width of the view. 17297 */ 17298 protected int getSuggestedMinimumWidth() { 17299 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 17300 } 17301 17302 /** 17303 * Returns the minimum height of the view. 17304 * 17305 * @return the minimum height the view will try to be. 17306 * 17307 * @see #setMinimumHeight(int) 17308 * 17309 * @attr ref android.R.styleable#View_minHeight 17310 */ 17311 public int getMinimumHeight() { 17312 return mMinHeight; 17313 } 17314 17315 /** 17316 * Sets the minimum height of the view. It is not guaranteed the view will 17317 * be able to achieve this minimum height (for example, if its parent layout 17318 * constrains it with less available height). 17319 * 17320 * @param minHeight The minimum height the view will try to be. 17321 * 17322 * @see #getMinimumHeight() 17323 * 17324 * @attr ref android.R.styleable#View_minHeight 17325 */ 17326 public void setMinimumHeight(int minHeight) { 17327 mMinHeight = minHeight; 17328 requestLayout(); 17329 } 17330 17331 /** 17332 * Returns the minimum width of the view. 17333 * 17334 * @return the minimum width the view will try to be. 17335 * 17336 * @see #setMinimumWidth(int) 17337 * 17338 * @attr ref android.R.styleable#View_minWidth 17339 */ 17340 public int getMinimumWidth() { 17341 return mMinWidth; 17342 } 17343 17344 /** 17345 * Sets the minimum width of the view. It is not guaranteed the view will 17346 * be able to achieve this minimum width (for example, if its parent layout 17347 * constrains it with less available width). 17348 * 17349 * @param minWidth The minimum width the view will try to be. 17350 * 17351 * @see #getMinimumWidth() 17352 * 17353 * @attr ref android.R.styleable#View_minWidth 17354 */ 17355 public void setMinimumWidth(int minWidth) { 17356 mMinWidth = minWidth; 17357 requestLayout(); 17358 17359 } 17360 17361 /** 17362 * Get the animation currently associated with this view. 17363 * 17364 * @return The animation that is currently playing or 17365 * scheduled to play for this view. 17366 */ 17367 public Animation getAnimation() { 17368 return mCurrentAnimation; 17369 } 17370 17371 /** 17372 * Start the specified animation now. 17373 * 17374 * @param animation the animation to start now 17375 */ 17376 public void startAnimation(Animation animation) { 17377 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 17378 setAnimation(animation); 17379 invalidateParentCaches(); 17380 invalidate(true); 17381 } 17382 17383 /** 17384 * Cancels any animations for this view. 17385 */ 17386 public void clearAnimation() { 17387 if (mCurrentAnimation != null) { 17388 mCurrentAnimation.detach(); 17389 } 17390 mCurrentAnimation = null; 17391 invalidateParentIfNeeded(); 17392 } 17393 17394 /** 17395 * Sets the next animation to play for this view. 17396 * If you want the animation to play immediately, use 17397 * {@link #startAnimation(android.view.animation.Animation)} instead. 17398 * This method provides allows fine-grained 17399 * control over the start time and invalidation, but you 17400 * must make sure that 1) the animation has a start time set, and 17401 * 2) the view's parent (which controls animations on its children) 17402 * will be invalidated when the animation is supposed to 17403 * start. 17404 * 17405 * @param animation The next animation, or null. 17406 */ 17407 public void setAnimation(Animation animation) { 17408 mCurrentAnimation = animation; 17409 17410 if (animation != null) { 17411 // If the screen is off assume the animation start time is now instead of 17412 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 17413 // would cause the animation to start when the screen turns back on 17414 if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF 17415 && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 17416 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 17417 } 17418 animation.reset(); 17419 } 17420 } 17421 17422 /** 17423 * Invoked by a parent ViewGroup to notify the start of the animation 17424 * currently associated with this view. If you override this method, 17425 * always call super.onAnimationStart(); 17426 * 17427 * @see #setAnimation(android.view.animation.Animation) 17428 * @see #getAnimation() 17429 */ 17430 protected void onAnimationStart() { 17431 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 17432 } 17433 17434 /** 17435 * Invoked by a parent ViewGroup to notify the end of the animation 17436 * currently associated with this view. If you override this method, 17437 * always call super.onAnimationEnd(); 17438 * 17439 * @see #setAnimation(android.view.animation.Animation) 17440 * @see #getAnimation() 17441 */ 17442 protected void onAnimationEnd() { 17443 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 17444 } 17445 17446 /** 17447 * Invoked if there is a Transform that involves alpha. Subclass that can 17448 * draw themselves with the specified alpha should return true, and then 17449 * respect that alpha when their onDraw() is called. If this returns false 17450 * then the view may be redirected to draw into an offscreen buffer to 17451 * fulfill the request, which will look fine, but may be slower than if the 17452 * subclass handles it internally. The default implementation returns false. 17453 * 17454 * @param alpha The alpha (0..255) to apply to the view's drawing 17455 * @return true if the view can draw with the specified alpha. 17456 */ 17457 protected boolean onSetAlpha(int alpha) { 17458 return false; 17459 } 17460 17461 /** 17462 * This is used by the RootView to perform an optimization when 17463 * the view hierarchy contains one or several SurfaceView. 17464 * SurfaceView is always considered transparent, but its children are not, 17465 * therefore all View objects remove themselves from the global transparent 17466 * region (passed as a parameter to this function). 17467 * 17468 * @param region The transparent region for this ViewAncestor (window). 17469 * 17470 * @return Returns true if the effective visibility of the view at this 17471 * point is opaque, regardless of the transparent region; returns false 17472 * if it is possible for underlying windows to be seen behind the view. 17473 * 17474 * {@hide} 17475 */ 17476 public boolean gatherTransparentRegion(Region region) { 17477 final AttachInfo attachInfo = mAttachInfo; 17478 if (region != null && attachInfo != null) { 17479 final int pflags = mPrivateFlags; 17480 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 17481 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 17482 // remove it from the transparent region. 17483 final int[] location = attachInfo.mTransparentLocation; 17484 getLocationInWindow(location); 17485 region.op(location[0], location[1], location[0] + mRight - mLeft, 17486 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 17487 } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null && 17488 mBackground.getOpacity() != PixelFormat.TRANSPARENT) { 17489 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 17490 // exists, so we remove the background drawable's non-transparent 17491 // parts from this transparent region. 17492 applyDrawableToTransparentRegion(mBackground, region); 17493 } 17494 } 17495 return true; 17496 } 17497 17498 /** 17499 * Play a sound effect for this view. 17500 * 17501 * <p>The framework will play sound effects for some built in actions, such as 17502 * clicking, but you may wish to play these effects in your widget, 17503 * for instance, for internal navigation. 17504 * 17505 * <p>The sound effect will only be played if sound effects are enabled by the user, and 17506 * {@link #isSoundEffectsEnabled()} is true. 17507 * 17508 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 17509 */ 17510 public void playSoundEffect(int soundConstant) { 17511 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 17512 return; 17513 } 17514 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 17515 } 17516 17517 /** 17518 * BZZZTT!!1! 17519 * 17520 * <p>Provide haptic feedback to the user for this view. 17521 * 17522 * <p>The framework will provide haptic feedback for some built in actions, 17523 * such as long presses, but you may wish to provide feedback for your 17524 * own widget. 17525 * 17526 * <p>The feedback will only be performed if 17527 * {@link #isHapticFeedbackEnabled()} is true. 17528 * 17529 * @param feedbackConstant One of the constants defined in 17530 * {@link HapticFeedbackConstants} 17531 */ 17532 public boolean performHapticFeedback(int feedbackConstant) { 17533 return performHapticFeedback(feedbackConstant, 0); 17534 } 17535 17536 /** 17537 * BZZZTT!!1! 17538 * 17539 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 17540 * 17541 * @param feedbackConstant One of the constants defined in 17542 * {@link HapticFeedbackConstants} 17543 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 17544 */ 17545 public boolean performHapticFeedback(int feedbackConstant, int flags) { 17546 if (mAttachInfo == null) { 17547 return false; 17548 } 17549 //noinspection SimplifiableIfStatement 17550 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 17551 && !isHapticFeedbackEnabled()) { 17552 return false; 17553 } 17554 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 17555 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 17556 } 17557 17558 /** 17559 * Request that the visibility of the status bar or other screen/window 17560 * decorations be changed. 17561 * 17562 * <p>This method is used to put the over device UI into temporary modes 17563 * where the user's attention is focused more on the application content, 17564 * by dimming or hiding surrounding system affordances. This is typically 17565 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 17566 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 17567 * to be placed behind the action bar (and with these flags other system 17568 * affordances) so that smooth transitions between hiding and showing them 17569 * can be done. 17570 * 17571 * <p>Two representative examples of the use of system UI visibility is 17572 * implementing a content browsing application (like a magazine reader) 17573 * and a video playing application. 17574 * 17575 * <p>The first code shows a typical implementation of a View in a content 17576 * browsing application. In this implementation, the application goes 17577 * into a content-oriented mode by hiding the status bar and action bar, 17578 * and putting the navigation elements into lights out mode. The user can 17579 * then interact with content while in this mode. Such an application should 17580 * provide an easy way for the user to toggle out of the mode (such as to 17581 * check information in the status bar or access notifications). In the 17582 * implementation here, this is done simply by tapping on the content. 17583 * 17584 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 17585 * content} 17586 * 17587 * <p>This second code sample shows a typical implementation of a View 17588 * in a video playing application. In this situation, while the video is 17589 * playing the application would like to go into a complete full-screen mode, 17590 * to use as much of the display as possible for the video. When in this state 17591 * the user can not interact with the application; the system intercepts 17592 * touching on the screen to pop the UI out of full screen mode. See 17593 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 17594 * 17595 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 17596 * content} 17597 * 17598 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 17599 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 17600 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 17601 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 17602 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 17603 */ 17604 public void setSystemUiVisibility(int visibility) { 17605 if (visibility != mSystemUiVisibility) { 17606 mSystemUiVisibility = visibility; 17607 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 17608 mParent.recomputeViewAttributes(this); 17609 } 17610 } 17611 } 17612 17613 /** 17614 * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested. 17615 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 17616 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 17617 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 17618 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 17619 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 17620 */ 17621 public int getSystemUiVisibility() { 17622 return mSystemUiVisibility; 17623 } 17624 17625 /** 17626 * Returns the current system UI visibility that is currently set for 17627 * the entire window. This is the combination of the 17628 * {@link #setSystemUiVisibility(int)} values supplied by all of the 17629 * views in the window. 17630 */ 17631 public int getWindowSystemUiVisibility() { 17632 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 17633 } 17634 17635 /** 17636 * Override to find out when the window's requested system UI visibility 17637 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 17638 * This is different from the callbacks received through 17639 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 17640 * in that this is only telling you about the local request of the window, 17641 * not the actual values applied by the system. 17642 */ 17643 public void onWindowSystemUiVisibilityChanged(int visible) { 17644 } 17645 17646 /** 17647 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 17648 * the view hierarchy. 17649 */ 17650 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 17651 onWindowSystemUiVisibilityChanged(visible); 17652 } 17653 17654 /** 17655 * Set a listener to receive callbacks when the visibility of the system bar changes. 17656 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 17657 */ 17658 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 17659 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 17660 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 17661 mParent.recomputeViewAttributes(this); 17662 } 17663 } 17664 17665 /** 17666 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 17667 * the view hierarchy. 17668 */ 17669 public void dispatchSystemUiVisibilityChanged(int visibility) { 17670 ListenerInfo li = mListenerInfo; 17671 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 17672 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 17673 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 17674 } 17675 } 17676 17677 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 17678 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 17679 if (val != mSystemUiVisibility) { 17680 setSystemUiVisibility(val); 17681 return true; 17682 } 17683 return false; 17684 } 17685 17686 /** @hide */ 17687 public void setDisabledSystemUiVisibility(int flags) { 17688 if (mAttachInfo != null) { 17689 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 17690 mAttachInfo.mDisabledSystemUiVisibility = flags; 17691 if (mParent != null) { 17692 mParent.recomputeViewAttributes(this); 17693 } 17694 } 17695 } 17696 } 17697 17698 /** 17699 * Creates an image that the system displays during the drag and drop 17700 * operation. This is called a "drag shadow". The default implementation 17701 * for a DragShadowBuilder based on a View returns an image that has exactly the same 17702 * appearance as the given View. The default also positions the center of the drag shadow 17703 * directly under the touch point. If no View is provided (the constructor with no parameters 17704 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 17705 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 17706 * default is an invisible drag shadow. 17707 * <p> 17708 * You are not required to use the View you provide to the constructor as the basis of the 17709 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 17710 * anything you want as the drag shadow. 17711 * </p> 17712 * <p> 17713 * You pass a DragShadowBuilder object to the system when you start the drag. The system 17714 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 17715 * size and position of the drag shadow. It uses this data to construct a 17716 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 17717 * so that your application can draw the shadow image in the Canvas. 17718 * </p> 17719 * 17720 * <div class="special reference"> 17721 * <h3>Developer Guides</h3> 17722 * <p>For a guide to implementing drag and drop features, read the 17723 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 17724 * </div> 17725 */ 17726 public static class DragShadowBuilder { 17727 private final WeakReference<View> mView; 17728 17729 /** 17730 * Constructs a shadow image builder based on a View. By default, the resulting drag 17731 * shadow will have the same appearance and dimensions as the View, with the touch point 17732 * over the center of the View. 17733 * @param view A View. Any View in scope can be used. 17734 */ 17735 public DragShadowBuilder(View view) { 17736 mView = new WeakReference<View>(view); 17737 } 17738 17739 /** 17740 * Construct a shadow builder object with no associated View. This 17741 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 17742 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 17743 * to supply the drag shadow's dimensions and appearance without 17744 * reference to any View object. If they are not overridden, then the result is an 17745 * invisible drag shadow. 17746 */ 17747 public DragShadowBuilder() { 17748 mView = new WeakReference<View>(null); 17749 } 17750 17751 /** 17752 * Returns the View object that had been passed to the 17753 * {@link #View.DragShadowBuilder(View)} 17754 * constructor. If that View parameter was {@code null} or if the 17755 * {@link #View.DragShadowBuilder()} 17756 * constructor was used to instantiate the builder object, this method will return 17757 * null. 17758 * 17759 * @return The View object associate with this builder object. 17760 */ 17761 @SuppressWarnings({"JavadocReference"}) 17762 final public View getView() { 17763 return mView.get(); 17764 } 17765 17766 /** 17767 * Provides the metrics for the shadow image. These include the dimensions of 17768 * the shadow image, and the point within that shadow that should 17769 * be centered under the touch location while dragging. 17770 * <p> 17771 * The default implementation sets the dimensions of the shadow to be the 17772 * same as the dimensions of the View itself and centers the shadow under 17773 * the touch point. 17774 * </p> 17775 * 17776 * @param shadowSize A {@link android.graphics.Point} containing the width and height 17777 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 17778 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 17779 * image. 17780 * 17781 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 17782 * shadow image that should be underneath the touch point during the drag and drop 17783 * operation. Your application must set {@link android.graphics.Point#x} to the 17784 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 17785 */ 17786 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 17787 final View view = mView.get(); 17788 if (view != null) { 17789 shadowSize.set(view.getWidth(), view.getHeight()); 17790 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 17791 } else { 17792 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 17793 } 17794 } 17795 17796 /** 17797 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 17798 * based on the dimensions it received from the 17799 * {@link #onProvideShadowMetrics(Point, Point)} callback. 17800 * 17801 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 17802 */ 17803 public void onDrawShadow(Canvas canvas) { 17804 final View view = mView.get(); 17805 if (view != null) { 17806 view.draw(canvas); 17807 } else { 17808 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 17809 } 17810 } 17811 } 17812 17813 /** 17814 * Starts a drag and drop operation. When your application calls this method, it passes a 17815 * {@link android.view.View.DragShadowBuilder} object to the system. The 17816 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 17817 * to get metrics for the drag shadow, and then calls the object's 17818 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 17819 * <p> 17820 * Once the system has the drag shadow, it begins the drag and drop operation by sending 17821 * drag events to all the View objects in your application that are currently visible. It does 17822 * this either by calling the View object's drag listener (an implementation of 17823 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 17824 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 17825 * Both are passed a {@link android.view.DragEvent} object that has a 17826 * {@link android.view.DragEvent#getAction()} value of 17827 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 17828 * </p> 17829 * <p> 17830 * Your application can invoke startDrag() on any attached View object. The View object does not 17831 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 17832 * be related to the View the user selected for dragging. 17833 * </p> 17834 * @param data A {@link android.content.ClipData} object pointing to the data to be 17835 * transferred by the drag and drop operation. 17836 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 17837 * drag shadow. 17838 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 17839 * drop operation. This Object is put into every DragEvent object sent by the system during the 17840 * current drag. 17841 * <p> 17842 * myLocalState is a lightweight mechanism for the sending information from the dragged View 17843 * to the target Views. For example, it can contain flags that differentiate between a 17844 * a copy operation and a move operation. 17845 * </p> 17846 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 17847 * so the parameter should be set to 0. 17848 * @return {@code true} if the method completes successfully, or 17849 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 17850 * do a drag, and so no drag operation is in progress. 17851 */ 17852 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 17853 Object myLocalState, int flags) { 17854 if (ViewDebug.DEBUG_DRAG) { 17855 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 17856 } 17857 boolean okay = false; 17858 17859 Point shadowSize = new Point(); 17860 Point shadowTouchPoint = new Point(); 17861 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 17862 17863 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 17864 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 17865 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 17866 } 17867 17868 if (ViewDebug.DEBUG_DRAG) { 17869 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 17870 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 17871 } 17872 Surface surface = new Surface(); 17873 try { 17874 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 17875 flags, shadowSize.x, shadowSize.y, surface); 17876 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 17877 + " surface=" + surface); 17878 if (token != null) { 17879 Canvas canvas = surface.lockCanvas(null); 17880 try { 17881 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 17882 shadowBuilder.onDrawShadow(canvas); 17883 } finally { 17884 surface.unlockCanvasAndPost(canvas); 17885 } 17886 17887 final ViewRootImpl root = getViewRootImpl(); 17888 17889 // Cache the local state object for delivery with DragEvents 17890 root.setLocalDragState(myLocalState); 17891 17892 // repurpose 'shadowSize' for the last touch point 17893 root.getLastTouchPoint(shadowSize); 17894 17895 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 17896 shadowSize.x, shadowSize.y, 17897 shadowTouchPoint.x, shadowTouchPoint.y, data); 17898 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 17899 17900 // Off and running! Release our local surface instance; the drag 17901 // shadow surface is now managed by the system process. 17902 surface.release(); 17903 } 17904 } catch (Exception e) { 17905 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 17906 surface.destroy(); 17907 } 17908 17909 return okay; 17910 } 17911 17912 /** 17913 * Handles drag events sent by the system following a call to 17914 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 17915 *<p> 17916 * When the system calls this method, it passes a 17917 * {@link android.view.DragEvent} object. A call to 17918 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 17919 * in DragEvent. The method uses these to determine what is happening in the drag and drop 17920 * operation. 17921 * @param event The {@link android.view.DragEvent} sent by the system. 17922 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 17923 * in DragEvent, indicating the type of drag event represented by this object. 17924 * @return {@code true} if the method was successful, otherwise {@code false}. 17925 * <p> 17926 * The method should return {@code true} in response to an action type of 17927 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 17928 * operation. 17929 * </p> 17930 * <p> 17931 * The method should also return {@code true} in response to an action type of 17932 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 17933 * {@code false} if it didn't. 17934 * </p> 17935 */ 17936 public boolean onDragEvent(DragEvent event) { 17937 return false; 17938 } 17939 17940 /** 17941 * Detects if this View is enabled and has a drag event listener. 17942 * If both are true, then it calls the drag event listener with the 17943 * {@link android.view.DragEvent} it received. If the drag event listener returns 17944 * {@code true}, then dispatchDragEvent() returns {@code true}. 17945 * <p> 17946 * For all other cases, the method calls the 17947 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 17948 * method and returns its result. 17949 * </p> 17950 * <p> 17951 * This ensures that a drag event is always consumed, even if the View does not have a drag 17952 * event listener. However, if the View has a listener and the listener returns true, then 17953 * onDragEvent() is not called. 17954 * </p> 17955 */ 17956 public boolean dispatchDragEvent(DragEvent event) { 17957 ListenerInfo li = mListenerInfo; 17958 //noinspection SimplifiableIfStatement 17959 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 17960 && li.mOnDragListener.onDrag(this, event)) { 17961 return true; 17962 } 17963 return onDragEvent(event); 17964 } 17965 17966 boolean canAcceptDrag() { 17967 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 17968 } 17969 17970 /** 17971 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 17972 * it is ever exposed at all. 17973 * @hide 17974 */ 17975 public void onCloseSystemDialogs(String reason) { 17976 } 17977 17978 /** 17979 * Given a Drawable whose bounds have been set to draw into this view, 17980 * update a Region being computed for 17981 * {@link #gatherTransparentRegion(android.graphics.Region)} so 17982 * that any non-transparent parts of the Drawable are removed from the 17983 * given transparent region. 17984 * 17985 * @param dr The Drawable whose transparency is to be applied to the region. 17986 * @param region A Region holding the current transparency information, 17987 * where any parts of the region that are set are considered to be 17988 * transparent. On return, this region will be modified to have the 17989 * transparency information reduced by the corresponding parts of the 17990 * Drawable that are not transparent. 17991 * {@hide} 17992 */ 17993 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 17994 if (DBG) { 17995 Log.i("View", "Getting transparent region for: " + this); 17996 } 17997 final Region r = dr.getTransparentRegion(); 17998 final Rect db = dr.getBounds(); 17999 final AttachInfo attachInfo = mAttachInfo; 18000 if (r != null && attachInfo != null) { 18001 final int w = getRight()-getLeft(); 18002 final int h = getBottom()-getTop(); 18003 if (db.left > 0) { 18004 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 18005 r.op(0, 0, db.left, h, Region.Op.UNION); 18006 } 18007 if (db.right < w) { 18008 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 18009 r.op(db.right, 0, w, h, Region.Op.UNION); 18010 } 18011 if (db.top > 0) { 18012 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 18013 r.op(0, 0, w, db.top, Region.Op.UNION); 18014 } 18015 if (db.bottom < h) { 18016 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 18017 r.op(0, db.bottom, w, h, Region.Op.UNION); 18018 } 18019 final int[] location = attachInfo.mTransparentLocation; 18020 getLocationInWindow(location); 18021 r.translate(location[0], location[1]); 18022 region.op(r, Region.Op.INTERSECT); 18023 } else { 18024 region.op(db, Region.Op.DIFFERENCE); 18025 } 18026 } 18027 18028 private void checkForLongClick(int delayOffset) { 18029 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 18030 mHasPerformedLongPress = false; 18031 18032 if (mPendingCheckForLongPress == null) { 18033 mPendingCheckForLongPress = new CheckForLongPress(); 18034 } 18035 mPendingCheckForLongPress.rememberWindowAttachCount(); 18036 postDelayed(mPendingCheckForLongPress, 18037 ViewConfiguration.getLongPressTimeout() - delayOffset); 18038 } 18039 } 18040 18041 /** 18042 * Inflate a view from an XML resource. This convenience method wraps the {@link 18043 * LayoutInflater} class, which provides a full range of options for view inflation. 18044 * 18045 * @param context The Context object for your activity or application. 18046 * @param resource The resource ID to inflate 18047 * @param root A view group that will be the parent. Used to properly inflate the 18048 * layout_* parameters. 18049 * @see LayoutInflater 18050 */ 18051 public static View inflate(Context context, int resource, ViewGroup root) { 18052 LayoutInflater factory = LayoutInflater.from(context); 18053 return factory.inflate(resource, root); 18054 } 18055 18056 /** 18057 * Scroll the view with standard behavior for scrolling beyond the normal 18058 * content boundaries. Views that call this method should override 18059 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 18060 * results of an over-scroll operation. 18061 * 18062 * Views can use this method to handle any touch or fling-based scrolling. 18063 * 18064 * @param deltaX Change in X in pixels 18065 * @param deltaY Change in Y in pixels 18066 * @param scrollX Current X scroll value in pixels before applying deltaX 18067 * @param scrollY Current Y scroll value in pixels before applying deltaY 18068 * @param scrollRangeX Maximum content scroll range along the X axis 18069 * @param scrollRangeY Maximum content scroll range along the Y axis 18070 * @param maxOverScrollX Number of pixels to overscroll by in either direction 18071 * along the X axis. 18072 * @param maxOverScrollY Number of pixels to overscroll by in either direction 18073 * along the Y axis. 18074 * @param isTouchEvent true if this scroll operation is the result of a touch event. 18075 * @return true if scrolling was clamped to an over-scroll boundary along either 18076 * axis, false otherwise. 18077 */ 18078 @SuppressWarnings({"UnusedParameters"}) 18079 protected boolean overScrollBy(int deltaX, int deltaY, 18080 int scrollX, int scrollY, 18081 int scrollRangeX, int scrollRangeY, 18082 int maxOverScrollX, int maxOverScrollY, 18083 boolean isTouchEvent) { 18084 final int overScrollMode = mOverScrollMode; 18085 final boolean canScrollHorizontal = 18086 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 18087 final boolean canScrollVertical = 18088 computeVerticalScrollRange() > computeVerticalScrollExtent(); 18089 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 18090 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 18091 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 18092 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 18093 18094 int newScrollX = scrollX + deltaX; 18095 if (!overScrollHorizontal) { 18096 maxOverScrollX = 0; 18097 } 18098 18099 int newScrollY = scrollY + deltaY; 18100 if (!overScrollVertical) { 18101 maxOverScrollY = 0; 18102 } 18103 18104 // Clamp values if at the limits and record 18105 final int left = -maxOverScrollX; 18106 final int right = maxOverScrollX + scrollRangeX; 18107 final int top = -maxOverScrollY; 18108 final int bottom = maxOverScrollY + scrollRangeY; 18109 18110 boolean clampedX = false; 18111 if (newScrollX > right) { 18112 newScrollX = right; 18113 clampedX = true; 18114 } else if (newScrollX < left) { 18115 newScrollX = left; 18116 clampedX = true; 18117 } 18118 18119 boolean clampedY = false; 18120 if (newScrollY > bottom) { 18121 newScrollY = bottom; 18122 clampedY = true; 18123 } else if (newScrollY < top) { 18124 newScrollY = top; 18125 clampedY = true; 18126 } 18127 18128 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 18129 18130 return clampedX || clampedY; 18131 } 18132 18133 /** 18134 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 18135 * respond to the results of an over-scroll operation. 18136 * 18137 * @param scrollX New X scroll value in pixels 18138 * @param scrollY New Y scroll value in pixels 18139 * @param clampedX True if scrollX was clamped to an over-scroll boundary 18140 * @param clampedY True if scrollY was clamped to an over-scroll boundary 18141 */ 18142 protected void onOverScrolled(int scrollX, int scrollY, 18143 boolean clampedX, boolean clampedY) { 18144 // Intentionally empty. 18145 } 18146 18147 /** 18148 * Returns the over-scroll mode for this view. The result will be 18149 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 18150 * (allow over-scrolling only if the view content is larger than the container), 18151 * or {@link #OVER_SCROLL_NEVER}. 18152 * 18153 * @return This view's over-scroll mode. 18154 */ 18155 public int getOverScrollMode() { 18156 return mOverScrollMode; 18157 } 18158 18159 /** 18160 * Set the over-scroll mode for this view. Valid over-scroll modes are 18161 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 18162 * (allow over-scrolling only if the view content is larger than the container), 18163 * or {@link #OVER_SCROLL_NEVER}. 18164 * 18165 * Setting the over-scroll mode of a view will have an effect only if the 18166 * view is capable of scrolling. 18167 * 18168 * @param overScrollMode The new over-scroll mode for this view. 18169 */ 18170 public void setOverScrollMode(int overScrollMode) { 18171 if (overScrollMode != OVER_SCROLL_ALWAYS && 18172 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 18173 overScrollMode != OVER_SCROLL_NEVER) { 18174 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 18175 } 18176 mOverScrollMode = overScrollMode; 18177 } 18178 18179 /** 18180 * Enable or disable nested scrolling for this view. 18181 * 18182 * <p>If this property is set to true the view will be permitted to initiate nested 18183 * scrolling operations with a compatible parent view in the current hierarchy. If this 18184 * view does not implement nested scrolling this will have no effect. Disabling nested scrolling 18185 * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping} 18186 * the nested scroll.</p> 18187 * 18188 * @param enabled true to enable nested scrolling, false to disable 18189 * 18190 * @see #isNestedScrollingEnabled() 18191 */ 18192 public void setNestedScrollingEnabled(boolean enabled) { 18193 if (enabled) { 18194 mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED; 18195 } else { 18196 stopNestedScroll(); 18197 mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED; 18198 } 18199 } 18200 18201 /** 18202 * Returns true if nested scrolling is enabled for this view. 18203 * 18204 * <p>If nested scrolling is enabled and this View class implementation supports it, 18205 * this view will act as a nested scrolling child view when applicable, forwarding data 18206 * about the scroll operation in progress to a compatible and cooperating nested scrolling 18207 * parent.</p> 18208 * 18209 * @return true if nested scrolling is enabled 18210 * 18211 * @see #setNestedScrollingEnabled(boolean) 18212 */ 18213 public boolean isNestedScrollingEnabled() { 18214 return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) == 18215 PFLAG3_NESTED_SCROLLING_ENABLED; 18216 } 18217 18218 /** 18219 * Begin a nestable scroll operation along the given axes. 18220 * 18221 * <p>A view starting a nested scroll promises to abide by the following contract:</p> 18222 * 18223 * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case 18224 * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}. 18225 * In the case of touch scrolling the nested scroll will be terminated automatically in 18226 * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}. 18227 * In the event of programmatic scrolling the caller must explicitly call 18228 * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p> 18229 * 18230 * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found. 18231 * If it returns false the caller may ignore the rest of this contract until the next scroll. 18232 * Calling startNestedScroll while a nested scroll is already in progress will return true.</p> 18233 * 18234 * <p>At each incremental step of the scroll the caller should invoke 18235 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} 18236 * once it has calculated the requested scrolling delta. If it returns true the nested scrolling 18237 * parent at least partially consumed the scroll and the caller should adjust the amount it 18238 * scrolls by.</p> 18239 * 18240 * <p>After applying the remainder of the scroll delta the caller should invoke 18241 * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing 18242 * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat 18243 * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}. 18244 * </p> 18245 * 18246 * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or 18247 * {@link #SCROLL_AXIS_VERTICAL}. 18248 * @return true if a cooperative parent was found and nested scrolling has been enabled for 18249 * the current gesture. 18250 * 18251 * @see #stopNestedScroll() 18252 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 18253 * @see #dispatchNestedScroll(int, int, int, int, int[]) 18254 */ 18255 public boolean startNestedScroll(int axes) { 18256 if (hasNestedScrollingParent()) { 18257 // Already in progress 18258 return true; 18259 } 18260 if (isNestedScrollingEnabled()) { 18261 ViewParent p = getParent(); 18262 View child = this; 18263 while (p != null) { 18264 try { 18265 if (p.onStartNestedScroll(child, this, axes)) { 18266 mNestedScrollingParent = p; 18267 p.onNestedScrollAccepted(child, this, axes); 18268 return true; 18269 } 18270 } catch (AbstractMethodError e) { 18271 Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " + 18272 "method onStartNestedScroll", e); 18273 // Allow the search upward to continue 18274 } 18275 if (p instanceof View) { 18276 child = (View) p; 18277 } 18278 p = p.getParent(); 18279 } 18280 } 18281 return false; 18282 } 18283 18284 /** 18285 * Stop a nested scroll in progress. 18286 * 18287 * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p> 18288 * 18289 * @see #startNestedScroll(int) 18290 */ 18291 public void stopNestedScroll() { 18292 if (mNestedScrollingParent != null) { 18293 mNestedScrollingParent.onStopNestedScroll(this); 18294 mNestedScrollingParent = null; 18295 } 18296 } 18297 18298 /** 18299 * Returns true if this view has a nested scrolling parent. 18300 * 18301 * <p>The presence of a nested scrolling parent indicates that this view has initiated 18302 * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p> 18303 * 18304 * @return whether this view has a nested scrolling parent 18305 */ 18306 public boolean hasNestedScrollingParent() { 18307 return mNestedScrollingParent != null; 18308 } 18309 18310 /** 18311 * Dispatch one step of a nested scroll in progress. 18312 * 18313 * <p>Implementations of views that support nested scrolling should call this to report 18314 * info about a scroll in progress to the current nested scrolling parent. If a nested scroll 18315 * is not currently in progress or nested scrolling is not 18316 * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p> 18317 * 18318 * <p>Compatible View implementations should also call 18319 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before 18320 * consuming a component of the scroll event themselves.</p> 18321 * 18322 * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step 18323 * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step 18324 * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view 18325 * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view 18326 * @param offsetInWindow Optional. If not null, on return this will contain the offset 18327 * in local view coordinates of this view from before this operation 18328 * to after it completes. View implementations may use this to adjust 18329 * expected input coordinate tracking. 18330 * @return true if the event was dispatched, false if it could not be dispatched. 18331 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 18332 */ 18333 public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, 18334 int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) { 18335 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18336 if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) { 18337 int startX = 0; 18338 int startY = 0; 18339 if (offsetInWindow != null) { 18340 getLocationInWindow(offsetInWindow); 18341 startX = offsetInWindow[0]; 18342 startY = offsetInWindow[1]; 18343 } 18344 18345 mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed, 18346 dxUnconsumed, dyUnconsumed); 18347 18348 if (offsetInWindow != null) { 18349 getLocationInWindow(offsetInWindow); 18350 offsetInWindow[0] -= startX; 18351 offsetInWindow[1] -= startY; 18352 } 18353 return true; 18354 } else if (offsetInWindow != null) { 18355 // No motion, no dispatch. Keep offsetInWindow up to date. 18356 offsetInWindow[0] = 0; 18357 offsetInWindow[1] = 0; 18358 } 18359 } 18360 return false; 18361 } 18362 18363 /** 18364 * Dispatch one step of a nested scroll in progress before this view consumes any portion of it. 18365 * 18366 * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch. 18367 * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested 18368 * scrolling operation to consume some or all of the scroll operation before the child view 18369 * consumes it.</p> 18370 * 18371 * @param dx Horizontal scroll distance in pixels 18372 * @param dy Vertical scroll distance in pixels 18373 * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx 18374 * and consumed[1] the consumed dy. 18375 * @param offsetInWindow Optional. If not null, on return this will contain the offset 18376 * in local view coordinates of this view from before this operation 18377 * to after it completes. View implementations may use this to adjust 18378 * expected input coordinate tracking. 18379 * @return true if the parent consumed some or all of the scroll delta 18380 * @see #dispatchNestedScroll(int, int, int, int, int[]) 18381 */ 18382 public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) { 18383 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18384 if (dx != 0 || dy != 0) { 18385 int startX = 0; 18386 int startY = 0; 18387 if (offsetInWindow != null) { 18388 getLocationInWindow(offsetInWindow); 18389 startX = offsetInWindow[0]; 18390 startY = offsetInWindow[1]; 18391 } 18392 18393 if (consumed == null) { 18394 if (mTempNestedScrollConsumed == null) { 18395 mTempNestedScrollConsumed = new int[2]; 18396 } 18397 consumed = mTempNestedScrollConsumed; 18398 } 18399 consumed[0] = 0; 18400 consumed[1] = 0; 18401 mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed); 18402 18403 if (offsetInWindow != null) { 18404 getLocationInWindow(offsetInWindow); 18405 offsetInWindow[0] -= startX; 18406 offsetInWindow[1] -= startY; 18407 } 18408 return consumed[0] != 0 || consumed[1] != 0; 18409 } else if (offsetInWindow != null) { 18410 offsetInWindow[0] = 0; 18411 offsetInWindow[1] = 0; 18412 } 18413 } 18414 return false; 18415 } 18416 18417 /** 18418 * Dispatch a fling to a nested scrolling parent. 18419 * 18420 * <p>This method should be used to indicate that a nested scrolling child has detected 18421 * suitable conditions for a fling. Generally this means that a touch scroll has ended with a 18422 * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds 18423 * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity} 18424 * along a scrollable axis.</p> 18425 * 18426 * <p>If a nested scrolling child view would normally fling but it is at the edge of 18427 * its own content, it can use this method to delegate the fling to its nested scrolling 18428 * parent instead. The parent may optionally consume the fling or observe a child fling.</p> 18429 * 18430 * @param velocityX Horizontal fling velocity in pixels per second 18431 * @param velocityY Vertical fling velocity in pixels per second 18432 * @param consumed true if the child consumed the fling, false otherwise 18433 * @return true if the nested scrolling parent consumed or otherwise reacted to the fling 18434 */ 18435 public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) { 18436 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18437 return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed); 18438 } 18439 return false; 18440 } 18441 18442 /** 18443 * Dispatch a fling to a nested scrolling parent before it is processed by this view. 18444 * 18445 * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch 18446 * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code> 18447 * offsets an opportunity for the parent view in a nested fling to fully consume the fling 18448 * before the child view consumes it. If this method returns <code>true</code>, a nested 18449 * parent view consumed the fling and this view should not scroll as a result.</p> 18450 * 18451 * <p>For a better user experience, only one view in a nested scrolling chain should consume 18452 * the fling at a time. If a parent view consumed the fling this method will return false. 18453 * Custom view implementations should account for this in two ways:</p> 18454 * 18455 * <ul> 18456 * <li>If a custom view is paged and needs to settle to a fixed page-point, do not 18457 * call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid 18458 * position regardless.</li> 18459 * <li>If a nested parent does consume the fling, this view should not scroll at all, 18460 * even to settle back to a valid idle position.</li> 18461 * </ul> 18462 * 18463 * <p>Views should also not offer fling velocities to nested parent views along an axis 18464 * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView} 18465 * should not offer a horizontal fling velocity to its parents since scrolling along that 18466 * axis is not permitted and carrying velocity along that motion does not make sense.</p> 18467 * 18468 * @param velocityX Horizontal fling velocity in pixels per second 18469 * @param velocityY Vertical fling velocity in pixels per second 18470 * @return true if a nested scrolling parent consumed the fling 18471 */ 18472 public boolean dispatchNestedPreFling(float velocityX, float velocityY) { 18473 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18474 return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY); 18475 } 18476 return false; 18477 } 18478 18479 /** 18480 * Gets a scale factor that determines the distance the view should scroll 18481 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 18482 * @return The vertical scroll scale factor. 18483 * @hide 18484 */ 18485 protected float getVerticalScrollFactor() { 18486 if (mVerticalScrollFactor == 0) { 18487 TypedValue outValue = new TypedValue(); 18488 if (!mContext.getTheme().resolveAttribute( 18489 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 18490 throw new IllegalStateException( 18491 "Expected theme to define listPreferredItemHeight."); 18492 } 18493 mVerticalScrollFactor = outValue.getDimension( 18494 mContext.getResources().getDisplayMetrics()); 18495 } 18496 return mVerticalScrollFactor; 18497 } 18498 18499 /** 18500 * Gets a scale factor that determines the distance the view should scroll 18501 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 18502 * @return The horizontal scroll scale factor. 18503 * @hide 18504 */ 18505 protected float getHorizontalScrollFactor() { 18506 // TODO: Should use something else. 18507 return getVerticalScrollFactor(); 18508 } 18509 18510 /** 18511 * Return the value specifying the text direction or policy that was set with 18512 * {@link #setTextDirection(int)}. 18513 * 18514 * @return the defined text direction. It can be one of: 18515 * 18516 * {@link #TEXT_DIRECTION_INHERIT}, 18517 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18518 * {@link #TEXT_DIRECTION_ANY_RTL}, 18519 * {@link #TEXT_DIRECTION_LTR}, 18520 * {@link #TEXT_DIRECTION_RTL}, 18521 * {@link #TEXT_DIRECTION_LOCALE} 18522 * 18523 * @attr ref android.R.styleable#View_textDirection 18524 * 18525 * @hide 18526 */ 18527 @ViewDebug.ExportedProperty(category = "text", mapping = { 18528 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 18529 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 18530 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 18531 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 18532 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 18533 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 18534 }) 18535 public int getRawTextDirection() { 18536 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 18537 } 18538 18539 /** 18540 * Set the text direction. 18541 * 18542 * @param textDirection the direction to set. Should be one of: 18543 * 18544 * {@link #TEXT_DIRECTION_INHERIT}, 18545 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18546 * {@link #TEXT_DIRECTION_ANY_RTL}, 18547 * {@link #TEXT_DIRECTION_LTR}, 18548 * {@link #TEXT_DIRECTION_RTL}, 18549 * {@link #TEXT_DIRECTION_LOCALE} 18550 * 18551 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution 18552 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will 18553 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 18554 * 18555 * @attr ref android.R.styleable#View_textDirection 18556 */ 18557 public void setTextDirection(int textDirection) { 18558 if (getRawTextDirection() != textDirection) { 18559 // Reset the current text direction and the resolved one 18560 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 18561 resetResolvedTextDirection(); 18562 // Set the new text direction 18563 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 18564 // Do resolution 18565 resolveTextDirection(); 18566 // Notify change 18567 onRtlPropertiesChanged(getLayoutDirection()); 18568 // Refresh 18569 requestLayout(); 18570 invalidate(true); 18571 } 18572 } 18573 18574 /** 18575 * Return the resolved text direction. 18576 * 18577 * @return the resolved text direction. Returns one of: 18578 * 18579 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18580 * {@link #TEXT_DIRECTION_ANY_RTL}, 18581 * {@link #TEXT_DIRECTION_LTR}, 18582 * {@link #TEXT_DIRECTION_RTL}, 18583 * {@link #TEXT_DIRECTION_LOCALE} 18584 * 18585 * @attr ref android.R.styleable#View_textDirection 18586 */ 18587 @ViewDebug.ExportedProperty(category = "text", mapping = { 18588 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 18589 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 18590 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 18591 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 18592 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 18593 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 18594 }) 18595 public int getTextDirection() { 18596 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 18597 } 18598 18599 /** 18600 * Resolve the text direction. 18601 * 18602 * @return true if resolution has been done, false otherwise. 18603 * 18604 * @hide 18605 */ 18606 public boolean resolveTextDirection() { 18607 // Reset any previous text direction resolution 18608 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 18609 18610 if (hasRtlSupport()) { 18611 // Set resolved text direction flag depending on text direction flag 18612 final int textDirection = getRawTextDirection(); 18613 switch(textDirection) { 18614 case TEXT_DIRECTION_INHERIT: 18615 if (!canResolveTextDirection()) { 18616 // We cannot do the resolution if there is no parent, so use the default one 18617 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18618 // Resolution will need to happen again later 18619 return false; 18620 } 18621 18622 // Parent has not yet resolved, so we still return the default 18623 try { 18624 if (!mParent.isTextDirectionResolved()) { 18625 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18626 // Resolution will need to happen again later 18627 return false; 18628 } 18629 } catch (AbstractMethodError e) { 18630 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18631 " does not fully implement ViewParent", e); 18632 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED | 18633 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18634 return true; 18635 } 18636 18637 // Set current resolved direction to the same value as the parent's one 18638 int parentResolvedDirection; 18639 try { 18640 parentResolvedDirection = mParent.getTextDirection(); 18641 } catch (AbstractMethodError e) { 18642 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18643 " does not fully implement ViewParent", e); 18644 parentResolvedDirection = TEXT_DIRECTION_LTR; 18645 } 18646 switch (parentResolvedDirection) { 18647 case TEXT_DIRECTION_FIRST_STRONG: 18648 case TEXT_DIRECTION_ANY_RTL: 18649 case TEXT_DIRECTION_LTR: 18650 case TEXT_DIRECTION_RTL: 18651 case TEXT_DIRECTION_LOCALE: 18652 mPrivateFlags2 |= 18653 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 18654 break; 18655 default: 18656 // Default resolved direction is "first strong" heuristic 18657 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18658 } 18659 break; 18660 case TEXT_DIRECTION_FIRST_STRONG: 18661 case TEXT_DIRECTION_ANY_RTL: 18662 case TEXT_DIRECTION_LTR: 18663 case TEXT_DIRECTION_RTL: 18664 case TEXT_DIRECTION_LOCALE: 18665 // Resolved direction is the same as text direction 18666 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 18667 break; 18668 default: 18669 // Default resolved direction is "first strong" heuristic 18670 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18671 } 18672 } else { 18673 // Default resolved direction is "first strong" heuristic 18674 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18675 } 18676 18677 // Set to resolved 18678 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 18679 return true; 18680 } 18681 18682 /** 18683 * Check if text direction resolution can be done. 18684 * 18685 * @return true if text direction resolution can be done otherwise return false. 18686 */ 18687 public boolean canResolveTextDirection() { 18688 switch (getRawTextDirection()) { 18689 case TEXT_DIRECTION_INHERIT: 18690 if (mParent != null) { 18691 try { 18692 return mParent.canResolveTextDirection(); 18693 } catch (AbstractMethodError e) { 18694 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18695 " does not fully implement ViewParent", e); 18696 } 18697 } 18698 return false; 18699 18700 default: 18701 return true; 18702 } 18703 } 18704 18705 /** 18706 * Reset resolved text direction. Text direction will be resolved during a call to 18707 * {@link #onMeasure(int, int)}. 18708 * 18709 * @hide 18710 */ 18711 public void resetResolvedTextDirection() { 18712 // Reset any previous text direction resolution 18713 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 18714 // Set to default value 18715 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18716 } 18717 18718 /** 18719 * @return true if text direction is inherited. 18720 * 18721 * @hide 18722 */ 18723 public boolean isTextDirectionInherited() { 18724 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 18725 } 18726 18727 /** 18728 * @return true if text direction is resolved. 18729 */ 18730 public boolean isTextDirectionResolved() { 18731 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED; 18732 } 18733 18734 /** 18735 * Return the value specifying the text alignment or policy that was set with 18736 * {@link #setTextAlignment(int)}. 18737 * 18738 * @return the defined text alignment. It can be one of: 18739 * 18740 * {@link #TEXT_ALIGNMENT_INHERIT}, 18741 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18742 * {@link #TEXT_ALIGNMENT_CENTER}, 18743 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18744 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18745 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18746 * {@link #TEXT_ALIGNMENT_VIEW_END} 18747 * 18748 * @attr ref android.R.styleable#View_textAlignment 18749 * 18750 * @hide 18751 */ 18752 @ViewDebug.ExportedProperty(category = "text", mapping = { 18753 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 18754 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 18755 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 18756 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 18757 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 18758 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 18759 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 18760 }) 18761 @TextAlignment 18762 public int getRawTextAlignment() { 18763 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 18764 } 18765 18766 /** 18767 * Set the text alignment. 18768 * 18769 * @param textAlignment The text alignment to set. Should be one of 18770 * 18771 * {@link #TEXT_ALIGNMENT_INHERIT}, 18772 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18773 * {@link #TEXT_ALIGNMENT_CENTER}, 18774 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18775 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18776 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18777 * {@link #TEXT_ALIGNMENT_VIEW_END} 18778 * 18779 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution 18780 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 18781 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}. 18782 * 18783 * @attr ref android.R.styleable#View_textAlignment 18784 */ 18785 public void setTextAlignment(@TextAlignment int textAlignment) { 18786 if (textAlignment != getRawTextAlignment()) { 18787 // Reset the current and resolved text alignment 18788 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 18789 resetResolvedTextAlignment(); 18790 // Set the new text alignment 18791 mPrivateFlags2 |= 18792 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 18793 // Do resolution 18794 resolveTextAlignment(); 18795 // Notify change 18796 onRtlPropertiesChanged(getLayoutDirection()); 18797 // Refresh 18798 requestLayout(); 18799 invalidate(true); 18800 } 18801 } 18802 18803 /** 18804 * Return the resolved text alignment. 18805 * 18806 * @return the resolved text alignment. Returns one of: 18807 * 18808 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18809 * {@link #TEXT_ALIGNMENT_CENTER}, 18810 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18811 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18812 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18813 * {@link #TEXT_ALIGNMENT_VIEW_END} 18814 * 18815 * @attr ref android.R.styleable#View_textAlignment 18816 */ 18817 @ViewDebug.ExportedProperty(category = "text", mapping = { 18818 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 18819 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 18820 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 18821 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 18822 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 18823 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 18824 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 18825 }) 18826 @TextAlignment 18827 public int getTextAlignment() { 18828 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> 18829 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 18830 } 18831 18832 /** 18833 * Resolve the text alignment. 18834 * 18835 * @return true if resolution has been done, false otherwise. 18836 * 18837 * @hide 18838 */ 18839 public boolean resolveTextAlignment() { 18840 // Reset any previous text alignment resolution 18841 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 18842 18843 if (hasRtlSupport()) { 18844 // Set resolved text alignment flag depending on text alignment flag 18845 final int textAlignment = getRawTextAlignment(); 18846 switch (textAlignment) { 18847 case TEXT_ALIGNMENT_INHERIT: 18848 // Check if we can resolve the text alignment 18849 if (!canResolveTextAlignment()) { 18850 // We cannot do the resolution if there is no parent so use the default 18851 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18852 // Resolution will need to happen again later 18853 return false; 18854 } 18855 18856 // Parent has not yet resolved, so we still return the default 18857 try { 18858 if (!mParent.isTextAlignmentResolved()) { 18859 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18860 // Resolution will need to happen again later 18861 return false; 18862 } 18863 } catch (AbstractMethodError e) { 18864 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18865 " does not fully implement ViewParent", e); 18866 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED | 18867 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18868 return true; 18869 } 18870 18871 int parentResolvedTextAlignment; 18872 try { 18873 parentResolvedTextAlignment = mParent.getTextAlignment(); 18874 } catch (AbstractMethodError e) { 18875 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18876 " does not fully implement ViewParent", e); 18877 parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY; 18878 } 18879 switch (parentResolvedTextAlignment) { 18880 case TEXT_ALIGNMENT_GRAVITY: 18881 case TEXT_ALIGNMENT_TEXT_START: 18882 case TEXT_ALIGNMENT_TEXT_END: 18883 case TEXT_ALIGNMENT_CENTER: 18884 case TEXT_ALIGNMENT_VIEW_START: 18885 case TEXT_ALIGNMENT_VIEW_END: 18886 // Resolved text alignment is the same as the parent resolved 18887 // text alignment 18888 mPrivateFlags2 |= 18889 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 18890 break; 18891 default: 18892 // Use default resolved text alignment 18893 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18894 } 18895 break; 18896 case TEXT_ALIGNMENT_GRAVITY: 18897 case TEXT_ALIGNMENT_TEXT_START: 18898 case TEXT_ALIGNMENT_TEXT_END: 18899 case TEXT_ALIGNMENT_CENTER: 18900 case TEXT_ALIGNMENT_VIEW_START: 18901 case TEXT_ALIGNMENT_VIEW_END: 18902 // Resolved text alignment is the same as text alignment 18903 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 18904 break; 18905 default: 18906 // Use default resolved text alignment 18907 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18908 } 18909 } else { 18910 // Use default resolved text alignment 18911 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18912 } 18913 18914 // Set the resolved 18915 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 18916 return true; 18917 } 18918 18919 /** 18920 * Check if text alignment resolution can be done. 18921 * 18922 * @return true if text alignment resolution can be done otherwise return false. 18923 */ 18924 public boolean canResolveTextAlignment() { 18925 switch (getRawTextAlignment()) { 18926 case TEXT_DIRECTION_INHERIT: 18927 if (mParent != null) { 18928 try { 18929 return mParent.canResolveTextAlignment(); 18930 } catch (AbstractMethodError e) { 18931 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18932 " does not fully implement ViewParent", e); 18933 } 18934 } 18935 return false; 18936 18937 default: 18938 return true; 18939 } 18940 } 18941 18942 /** 18943 * Reset resolved text alignment. Text alignment will be resolved during a call to 18944 * {@link #onMeasure(int, int)}. 18945 * 18946 * @hide 18947 */ 18948 public void resetResolvedTextAlignment() { 18949 // Reset any previous text alignment resolution 18950 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 18951 // Set to default 18952 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18953 } 18954 18955 /** 18956 * @return true if text alignment is inherited. 18957 * 18958 * @hide 18959 */ 18960 public boolean isTextAlignmentInherited() { 18961 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 18962 } 18963 18964 /** 18965 * @return true if text alignment is resolved. 18966 */ 18967 public boolean isTextAlignmentResolved() { 18968 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED; 18969 } 18970 18971 /** 18972 * Generate a value suitable for use in {@link #setId(int)}. 18973 * This value will not collide with ID values generated at build time by aapt for R.id. 18974 * 18975 * @return a generated ID value 18976 */ 18977 public static int generateViewId() { 18978 for (;;) { 18979 final int result = sNextGeneratedId.get(); 18980 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 18981 int newValue = result + 1; 18982 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 18983 if (sNextGeneratedId.compareAndSet(result, newValue)) { 18984 return result; 18985 } 18986 } 18987 } 18988 18989 /** 18990 * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions. 18991 * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and 18992 * a normal View or a ViewGroup with 18993 * {@link android.view.ViewGroup#isTransitionGroup()} true. 18994 * @hide 18995 */ 18996 public void captureTransitioningViews(List<View> transitioningViews) { 18997 if (getVisibility() == View.VISIBLE) { 18998 transitioningViews.add(this); 18999 } 19000 } 19001 19002 /** 19003 * Adds all Views that have {@link #getTransitionName()} non-null to namedElements. 19004 * @param namedElements Will contain all Views in the hierarchy having a transitionName. 19005 * @hide 19006 */ 19007 public void findNamedViews(Map<String, View> namedElements) { 19008 if (getVisibility() == VISIBLE || mGhostView != null) { 19009 String transitionName = getTransitionName(); 19010 if (transitionName != null) { 19011 namedElements.put(transitionName, this); 19012 } 19013 } 19014 } 19015 19016 // 19017 // Properties 19018 // 19019 /** 19020 * A Property wrapper around the <code>alpha</code> functionality handled by the 19021 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 19022 */ 19023 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 19024 @Override 19025 public void setValue(View object, float value) { 19026 object.setAlpha(value); 19027 } 19028 19029 @Override 19030 public Float get(View object) { 19031 return object.getAlpha(); 19032 } 19033 }; 19034 19035 /** 19036 * A Property wrapper around the <code>translationX</code> functionality handled by the 19037 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 19038 */ 19039 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 19040 @Override 19041 public void setValue(View object, float value) { 19042 object.setTranslationX(value); 19043 } 19044 19045 @Override 19046 public Float get(View object) { 19047 return object.getTranslationX(); 19048 } 19049 }; 19050 19051 /** 19052 * A Property wrapper around the <code>translationY</code> functionality handled by the 19053 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 19054 */ 19055 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 19056 @Override 19057 public void setValue(View object, float value) { 19058 object.setTranslationY(value); 19059 } 19060 19061 @Override 19062 public Float get(View object) { 19063 return object.getTranslationY(); 19064 } 19065 }; 19066 19067 /** 19068 * A Property wrapper around the <code>translationZ</code> functionality handled by the 19069 * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods. 19070 */ 19071 public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") { 19072 @Override 19073 public void setValue(View object, float value) { 19074 object.setTranslationZ(value); 19075 } 19076 19077 @Override 19078 public Float get(View object) { 19079 return object.getTranslationZ(); 19080 } 19081 }; 19082 19083 /** 19084 * A Property wrapper around the <code>x</code> functionality handled by the 19085 * {@link View#setX(float)} and {@link View#getX()} methods. 19086 */ 19087 public static final Property<View, Float> X = new FloatProperty<View>("x") { 19088 @Override 19089 public void setValue(View object, float value) { 19090 object.setX(value); 19091 } 19092 19093 @Override 19094 public Float get(View object) { 19095 return object.getX(); 19096 } 19097 }; 19098 19099 /** 19100 * A Property wrapper around the <code>y</code> functionality handled by the 19101 * {@link View#setY(float)} and {@link View#getY()} methods. 19102 */ 19103 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 19104 @Override 19105 public void setValue(View object, float value) { 19106 object.setY(value); 19107 } 19108 19109 @Override 19110 public Float get(View object) { 19111 return object.getY(); 19112 } 19113 }; 19114 19115 /** 19116 * A Property wrapper around the <code>z</code> functionality handled by the 19117 * {@link View#setZ(float)} and {@link View#getZ()} methods. 19118 */ 19119 public static final Property<View, Float> Z = new FloatProperty<View>("z") { 19120 @Override 19121 public void setValue(View object, float value) { 19122 object.setZ(value); 19123 } 19124 19125 @Override 19126 public Float get(View object) { 19127 return object.getZ(); 19128 } 19129 }; 19130 19131 /** 19132 * A Property wrapper around the <code>rotation</code> functionality handled by the 19133 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 19134 */ 19135 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 19136 @Override 19137 public void setValue(View object, float value) { 19138 object.setRotation(value); 19139 } 19140 19141 @Override 19142 public Float get(View object) { 19143 return object.getRotation(); 19144 } 19145 }; 19146 19147 /** 19148 * A Property wrapper around the <code>rotationX</code> functionality handled by the 19149 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 19150 */ 19151 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 19152 @Override 19153 public void setValue(View object, float value) { 19154 object.setRotationX(value); 19155 } 19156 19157 @Override 19158 public Float get(View object) { 19159 return object.getRotationX(); 19160 } 19161 }; 19162 19163 /** 19164 * A Property wrapper around the <code>rotationY</code> functionality handled by the 19165 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 19166 */ 19167 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 19168 @Override 19169 public void setValue(View object, float value) { 19170 object.setRotationY(value); 19171 } 19172 19173 @Override 19174 public Float get(View object) { 19175 return object.getRotationY(); 19176 } 19177 }; 19178 19179 /** 19180 * A Property wrapper around the <code>scaleX</code> functionality handled by the 19181 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 19182 */ 19183 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 19184 @Override 19185 public void setValue(View object, float value) { 19186 object.setScaleX(value); 19187 } 19188 19189 @Override 19190 public Float get(View object) { 19191 return object.getScaleX(); 19192 } 19193 }; 19194 19195 /** 19196 * A Property wrapper around the <code>scaleY</code> functionality handled by the 19197 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 19198 */ 19199 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 19200 @Override 19201 public void setValue(View object, float value) { 19202 object.setScaleY(value); 19203 } 19204 19205 @Override 19206 public Float get(View object) { 19207 return object.getScaleY(); 19208 } 19209 }; 19210 19211 /** 19212 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 19213 * Each MeasureSpec represents a requirement for either the width or the height. 19214 * A MeasureSpec is comprised of a size and a mode. There are three possible 19215 * modes: 19216 * <dl> 19217 * <dt>UNSPECIFIED</dt> 19218 * <dd> 19219 * The parent has not imposed any constraint on the child. It can be whatever size 19220 * it wants. 19221 * </dd> 19222 * 19223 * <dt>EXACTLY</dt> 19224 * <dd> 19225 * The parent has determined an exact size for the child. The child is going to be 19226 * given those bounds regardless of how big it wants to be. 19227 * </dd> 19228 * 19229 * <dt>AT_MOST</dt> 19230 * <dd> 19231 * The child can be as large as it wants up to the specified size. 19232 * </dd> 19233 * </dl> 19234 * 19235 * MeasureSpecs are implemented as ints to reduce object allocation. This class 19236 * is provided to pack and unpack the <size, mode> tuple into the int. 19237 */ 19238 public static class MeasureSpec { 19239 private static final int MODE_SHIFT = 30; 19240 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 19241 19242 /** 19243 * Measure specification mode: The parent has not imposed any constraint 19244 * on the child. It can be whatever size it wants. 19245 */ 19246 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 19247 19248 /** 19249 * Measure specification mode: The parent has determined an exact size 19250 * for the child. The child is going to be given those bounds regardless 19251 * of how big it wants to be. 19252 */ 19253 public static final int EXACTLY = 1 << MODE_SHIFT; 19254 19255 /** 19256 * Measure specification mode: The child can be as large as it wants up 19257 * to the specified size. 19258 */ 19259 public static final int AT_MOST = 2 << MODE_SHIFT; 19260 19261 /** 19262 * Creates a measure specification based on the supplied size and mode. 19263 * 19264 * The mode must always be one of the following: 19265 * <ul> 19266 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 19267 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 19268 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 19269 * </ul> 19270 * 19271 * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's 19272 * implementation was such that the order of arguments did not matter 19273 * and overflow in either value could impact the resulting MeasureSpec. 19274 * {@link android.widget.RelativeLayout} was affected by this bug. 19275 * Apps targeting API levels greater than 17 will get the fixed, more strict 19276 * behavior.</p> 19277 * 19278 * @param size the size of the measure specification 19279 * @param mode the mode of the measure specification 19280 * @return the measure specification based on size and mode 19281 */ 19282 public static int makeMeasureSpec(int size, int mode) { 19283 if (sUseBrokenMakeMeasureSpec) { 19284 return size + mode; 19285 } else { 19286 return (size & ~MODE_MASK) | (mode & MODE_MASK); 19287 } 19288 } 19289 19290 /** 19291 * Extracts the mode from the supplied measure specification. 19292 * 19293 * @param measureSpec the measure specification to extract the mode from 19294 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 19295 * {@link android.view.View.MeasureSpec#AT_MOST} or 19296 * {@link android.view.View.MeasureSpec#EXACTLY} 19297 */ 19298 public static int getMode(int measureSpec) { 19299 return (measureSpec & MODE_MASK); 19300 } 19301 19302 /** 19303 * Extracts the size from the supplied measure specification. 19304 * 19305 * @param measureSpec the measure specification to extract the size from 19306 * @return the size in pixels defined in the supplied measure specification 19307 */ 19308 public static int getSize(int measureSpec) { 19309 return (measureSpec & ~MODE_MASK); 19310 } 19311 19312 static int adjust(int measureSpec, int delta) { 19313 final int mode = getMode(measureSpec); 19314 if (mode == UNSPECIFIED) { 19315 // No need to adjust size for UNSPECIFIED mode. 19316 return makeMeasureSpec(0, UNSPECIFIED); 19317 } 19318 int size = getSize(measureSpec) + delta; 19319 if (size < 0) { 19320 Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size + 19321 ") spec: " + toString(measureSpec) + " delta: " + delta); 19322 size = 0; 19323 } 19324 return makeMeasureSpec(size, mode); 19325 } 19326 19327 /** 19328 * Returns a String representation of the specified measure 19329 * specification. 19330 * 19331 * @param measureSpec the measure specification to convert to a String 19332 * @return a String with the following format: "MeasureSpec: MODE SIZE" 19333 */ 19334 public static String toString(int measureSpec) { 19335 int mode = getMode(measureSpec); 19336 int size = getSize(measureSpec); 19337 19338 StringBuilder sb = new StringBuilder("MeasureSpec: "); 19339 19340 if (mode == UNSPECIFIED) 19341 sb.append("UNSPECIFIED "); 19342 else if (mode == EXACTLY) 19343 sb.append("EXACTLY "); 19344 else if (mode == AT_MOST) 19345 sb.append("AT_MOST "); 19346 else 19347 sb.append(mode).append(" "); 19348 19349 sb.append(size); 19350 return sb.toString(); 19351 } 19352 } 19353 19354 private final class CheckForLongPress implements Runnable { 19355 private int mOriginalWindowAttachCount; 19356 19357 @Override 19358 public void run() { 19359 if (isPressed() && (mParent != null) 19360 && mOriginalWindowAttachCount == mWindowAttachCount) { 19361 if (performLongClick()) { 19362 mHasPerformedLongPress = true; 19363 } 19364 } 19365 } 19366 19367 public void rememberWindowAttachCount() { 19368 mOriginalWindowAttachCount = mWindowAttachCount; 19369 } 19370 } 19371 19372 private final class CheckForTap implements Runnable { 19373 public float x; 19374 public float y; 19375 19376 @Override 19377 public void run() { 19378 mPrivateFlags &= ~PFLAG_PREPRESSED; 19379 setPressed(true, x, y); 19380 checkForLongClick(ViewConfiguration.getTapTimeout()); 19381 } 19382 } 19383 19384 private final class PerformClick implements Runnable { 19385 @Override 19386 public void run() { 19387 performClick(); 19388 } 19389 } 19390 19391 /** @hide */ 19392 public void hackTurnOffWindowResizeAnim(boolean off) { 19393 mAttachInfo.mTurnOffWindowResizeAnim = off; 19394 } 19395 19396 /** 19397 * This method returns a ViewPropertyAnimator object, which can be used to animate 19398 * specific properties on this View. 19399 * 19400 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 19401 */ 19402 public ViewPropertyAnimator animate() { 19403 if (mAnimator == null) { 19404 mAnimator = new ViewPropertyAnimator(this); 19405 } 19406 return mAnimator; 19407 } 19408 19409 /** 19410 * Sets the name of the View to be used to identify Views in Transitions. 19411 * Names should be unique in the View hierarchy. 19412 * 19413 * @param transitionName The name of the View to uniquely identify it for Transitions. 19414 */ 19415 public final void setTransitionName(String transitionName) { 19416 mTransitionName = transitionName; 19417 } 19418 19419 /** 19420 * Returns the name of the View to be used to identify Views in Transitions. 19421 * Names should be unique in the View hierarchy. 19422 * 19423 * <p>This returns null if the View has not been given a name.</p> 19424 * 19425 * @return The name used of the View to be used to identify Views in Transitions or null 19426 * if no name has been given. 19427 */ 19428 @ViewDebug.ExportedProperty 19429 public String getTransitionName() { 19430 return mTransitionName; 19431 } 19432 19433 /** 19434 * Interface definition for a callback to be invoked when a hardware key event is 19435 * dispatched to this view. The callback will be invoked before the key event is 19436 * given to the view. This is only useful for hardware keyboards; a software input 19437 * method has no obligation to trigger this listener. 19438 */ 19439 public interface OnKeyListener { 19440 /** 19441 * Called when a hardware key is dispatched to a view. This allows listeners to 19442 * get a chance to respond before the target view. 19443 * <p>Key presses in software keyboards will generally NOT trigger this method, 19444 * although some may elect to do so in some situations. Do not assume a 19445 * software input method has to be key-based; even if it is, it may use key presses 19446 * in a different way than you expect, so there is no way to reliably catch soft 19447 * input key presses. 19448 * 19449 * @param v The view the key has been dispatched to. 19450 * @param keyCode The code for the physical key that was pressed 19451 * @param event The KeyEvent object containing full information about 19452 * the event. 19453 * @return True if the listener has consumed the event, false otherwise. 19454 */ 19455 boolean onKey(View v, int keyCode, KeyEvent event); 19456 } 19457 19458 /** 19459 * Interface definition for a callback to be invoked when a touch event is 19460 * dispatched to this view. The callback will be invoked before the touch 19461 * event is given to the view. 19462 */ 19463 public interface OnTouchListener { 19464 /** 19465 * Called when a touch event is dispatched to a view. This allows listeners to 19466 * get a chance to respond before the target view. 19467 * 19468 * @param v The view the touch event has been dispatched to. 19469 * @param event The MotionEvent object containing full information about 19470 * the event. 19471 * @return True if the listener has consumed the event, false otherwise. 19472 */ 19473 boolean onTouch(View v, MotionEvent event); 19474 } 19475 19476 /** 19477 * Interface definition for a callback to be invoked when a hover event is 19478 * dispatched to this view. The callback will be invoked before the hover 19479 * event is given to the view. 19480 */ 19481 public interface OnHoverListener { 19482 /** 19483 * Called when a hover event is dispatched to a view. This allows listeners to 19484 * get a chance to respond before the target view. 19485 * 19486 * @param v The view the hover event has been dispatched to. 19487 * @param event The MotionEvent object containing full information about 19488 * the event. 19489 * @return True if the listener has consumed the event, false otherwise. 19490 */ 19491 boolean onHover(View v, MotionEvent event); 19492 } 19493 19494 /** 19495 * Interface definition for a callback to be invoked when a generic motion event is 19496 * dispatched to this view. The callback will be invoked before the generic motion 19497 * event is given to the view. 19498 */ 19499 public interface OnGenericMotionListener { 19500 /** 19501 * Called when a generic motion event is dispatched to a view. This allows listeners to 19502 * get a chance to respond before the target view. 19503 * 19504 * @param v The view the generic motion event has been dispatched to. 19505 * @param event The MotionEvent object containing full information about 19506 * the event. 19507 * @return True if the listener has consumed the event, false otherwise. 19508 */ 19509 boolean onGenericMotion(View v, MotionEvent event); 19510 } 19511 19512 /** 19513 * Interface definition for a callback to be invoked when a view has been clicked and held. 19514 */ 19515 public interface OnLongClickListener { 19516 /** 19517 * Called when a view has been clicked and held. 19518 * 19519 * @param v The view that was clicked and held. 19520 * 19521 * @return true if the callback consumed the long click, false otherwise. 19522 */ 19523 boolean onLongClick(View v); 19524 } 19525 19526 /** 19527 * Interface definition for a callback to be invoked when a drag is being dispatched 19528 * to this view. The callback will be invoked before the hosting view's own 19529 * onDrag(event) method. If the listener wants to fall back to the hosting view's 19530 * onDrag(event) behavior, it should return 'false' from this callback. 19531 * 19532 * <div class="special reference"> 19533 * <h3>Developer Guides</h3> 19534 * <p>For a guide to implementing drag and drop features, read the 19535 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 19536 * </div> 19537 */ 19538 public interface OnDragListener { 19539 /** 19540 * Called when a drag event is dispatched to a view. This allows listeners 19541 * to get a chance to override base View behavior. 19542 * 19543 * @param v The View that received the drag event. 19544 * @param event The {@link android.view.DragEvent} object for the drag event. 19545 * @return {@code true} if the drag event was handled successfully, or {@code false} 19546 * if the drag event was not handled. Note that {@code false} will trigger the View 19547 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 19548 */ 19549 boolean onDrag(View v, DragEvent event); 19550 } 19551 19552 /** 19553 * Interface definition for a callback to be invoked when the focus state of 19554 * a view changed. 19555 */ 19556 public interface OnFocusChangeListener { 19557 /** 19558 * Called when the focus state of a view has changed. 19559 * 19560 * @param v The view whose state has changed. 19561 * @param hasFocus The new focus state of v. 19562 */ 19563 void onFocusChange(View v, boolean hasFocus); 19564 } 19565 19566 /** 19567 * Interface definition for a callback to be invoked when a view is clicked. 19568 */ 19569 public interface OnClickListener { 19570 /** 19571 * Called when a view has been clicked. 19572 * 19573 * @param v The view that was clicked. 19574 */ 19575 void onClick(View v); 19576 } 19577 19578 /** 19579 * Interface definition for a callback to be invoked when the context menu 19580 * for this view is being built. 19581 */ 19582 public interface OnCreateContextMenuListener { 19583 /** 19584 * Called when the context menu for this view is being built. It is not 19585 * safe to hold onto the menu after this method returns. 19586 * 19587 * @param menu The context menu that is being built 19588 * @param v The view for which the context menu is being built 19589 * @param menuInfo Extra information about the item for which the 19590 * context menu should be shown. This information will vary 19591 * depending on the class of v. 19592 */ 19593 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 19594 } 19595 19596 /** 19597 * Interface definition for a callback to be invoked when the status bar changes 19598 * visibility. This reports <strong>global</strong> changes to the system UI 19599 * state, not what the application is requesting. 19600 * 19601 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 19602 */ 19603 public interface OnSystemUiVisibilityChangeListener { 19604 /** 19605 * Called when the status bar changes visibility because of a call to 19606 * {@link View#setSystemUiVisibility(int)}. 19607 * 19608 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 19609 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 19610 * This tells you the <strong>global</strong> state of these UI visibility 19611 * flags, not what your app is currently applying. 19612 */ 19613 public void onSystemUiVisibilityChange(int visibility); 19614 } 19615 19616 /** 19617 * Interface definition for a callback to be invoked when this view is attached 19618 * or detached from its window. 19619 */ 19620 public interface OnAttachStateChangeListener { 19621 /** 19622 * Called when the view is attached to a window. 19623 * @param v The view that was attached 19624 */ 19625 public void onViewAttachedToWindow(View v); 19626 /** 19627 * Called when the view is detached from a window. 19628 * @param v The view that was detached 19629 */ 19630 public void onViewDetachedFromWindow(View v); 19631 } 19632 19633 /** 19634 * Listener for applying window insets on a view in a custom way. 19635 * 19636 * <p>Apps may choose to implement this interface if they want to apply custom policy 19637 * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener 19638 * is set, its 19639 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 19640 * method will be called instead of the View's own 19641 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener 19642 * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply 19643 * the View's normal behavior as part of its own.</p> 19644 */ 19645 public interface OnApplyWindowInsetsListener { 19646 /** 19647 * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set} 19648 * on a View, this listener method will be called instead of the view's own 19649 * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 19650 * 19651 * @param v The view applying window insets 19652 * @param insets The insets to apply 19653 * @return The insets supplied, minus any insets that were consumed 19654 */ 19655 public WindowInsets onApplyWindowInsets(View v, WindowInsets insets); 19656 } 19657 19658 private final class UnsetPressedState implements Runnable { 19659 @Override 19660 public void run() { 19661 setPressed(false); 19662 } 19663 } 19664 19665 /** 19666 * Base class for derived classes that want to save and restore their own 19667 * state in {@link android.view.View#onSaveInstanceState()}. 19668 */ 19669 public static class BaseSavedState extends AbsSavedState { 19670 /** 19671 * Constructor used when reading from a parcel. Reads the state of the superclass. 19672 * 19673 * @param source 19674 */ 19675 public BaseSavedState(Parcel source) { 19676 super(source); 19677 } 19678 19679 /** 19680 * Constructor called by derived classes when creating their SavedState objects 19681 * 19682 * @param superState The state of the superclass of this view 19683 */ 19684 public BaseSavedState(Parcelable superState) { 19685 super(superState); 19686 } 19687 19688 public static final Parcelable.Creator<BaseSavedState> CREATOR = 19689 new Parcelable.Creator<BaseSavedState>() { 19690 public BaseSavedState createFromParcel(Parcel in) { 19691 return new BaseSavedState(in); 19692 } 19693 19694 public BaseSavedState[] newArray(int size) { 19695 return new BaseSavedState[size]; 19696 } 19697 }; 19698 } 19699 19700 /** 19701 * A set of information given to a view when it is attached to its parent 19702 * window. 19703 */ 19704 final static class AttachInfo { 19705 interface Callbacks { 19706 void playSoundEffect(int effectId); 19707 boolean performHapticFeedback(int effectId, boolean always); 19708 } 19709 19710 /** 19711 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 19712 * to a Handler. This class contains the target (View) to invalidate and 19713 * the coordinates of the dirty rectangle. 19714 * 19715 * For performance purposes, this class also implements a pool of up to 19716 * POOL_LIMIT objects that get reused. This reduces memory allocations 19717 * whenever possible. 19718 */ 19719 static class InvalidateInfo { 19720 private static final int POOL_LIMIT = 10; 19721 19722 private static final SynchronizedPool<InvalidateInfo> sPool = 19723 new SynchronizedPool<InvalidateInfo>(POOL_LIMIT); 19724 19725 View target; 19726 19727 int left; 19728 int top; 19729 int right; 19730 int bottom; 19731 19732 public static InvalidateInfo obtain() { 19733 InvalidateInfo instance = sPool.acquire(); 19734 return (instance != null) ? instance : new InvalidateInfo(); 19735 } 19736 19737 public void recycle() { 19738 target = null; 19739 sPool.release(this); 19740 } 19741 } 19742 19743 final IWindowSession mSession; 19744 19745 final IWindow mWindow; 19746 19747 final IBinder mWindowToken; 19748 19749 final Display mDisplay; 19750 19751 final Callbacks mRootCallbacks; 19752 19753 IWindowId mIWindowId; 19754 WindowId mWindowId; 19755 19756 /** 19757 * The top view of the hierarchy. 19758 */ 19759 View mRootView; 19760 19761 IBinder mPanelParentWindowToken; 19762 19763 boolean mHardwareAccelerated; 19764 boolean mHardwareAccelerationRequested; 19765 HardwareRenderer mHardwareRenderer; 19766 19767 /** 19768 * The state of the display to which the window is attached, as reported 19769 * by {@link Display#getState()}. Note that the display state constants 19770 * declared by {@link Display} do not exactly line up with the screen state 19771 * constants declared by {@link View} (there are more display states than 19772 * screen states). 19773 */ 19774 int mDisplayState = Display.STATE_UNKNOWN; 19775 19776 /** 19777 * Scale factor used by the compatibility mode 19778 */ 19779 float mApplicationScale; 19780 19781 /** 19782 * Indicates whether the application is in compatibility mode 19783 */ 19784 boolean mScalingRequired; 19785 19786 /** 19787 * If set, ViewRootImpl doesn't use its lame animation for when the window resizes. 19788 */ 19789 boolean mTurnOffWindowResizeAnim; 19790 19791 /** 19792 * Left position of this view's window 19793 */ 19794 int mWindowLeft; 19795 19796 /** 19797 * Top position of this view's window 19798 */ 19799 int mWindowTop; 19800 19801 /** 19802 * Indicates whether views need to use 32-bit drawing caches 19803 */ 19804 boolean mUse32BitDrawingCache; 19805 19806 /** 19807 * For windows that are full-screen but using insets to layout inside 19808 * of the screen areas, these are the current insets to appear inside 19809 * the overscan area of the display. 19810 */ 19811 final Rect mOverscanInsets = new Rect(); 19812 19813 /** 19814 * For windows that are full-screen but using insets to layout inside 19815 * of the screen decorations, these are the current insets for the 19816 * content of the window. 19817 */ 19818 final Rect mContentInsets = new Rect(); 19819 19820 /** 19821 * For windows that are full-screen but using insets to layout inside 19822 * of the screen decorations, these are the current insets for the 19823 * actual visible parts of the window. 19824 */ 19825 final Rect mVisibleInsets = new Rect(); 19826 19827 /** 19828 * For windows that are full-screen but using insets to layout inside 19829 * of the screen decorations, these are the current insets for the 19830 * stable system windows. 19831 */ 19832 final Rect mStableInsets = new Rect(); 19833 19834 /** 19835 * The internal insets given by this window. This value is 19836 * supplied by the client (through 19837 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 19838 * be given to the window manager when changed to be used in laying 19839 * out windows behind it. 19840 */ 19841 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 19842 = new ViewTreeObserver.InternalInsetsInfo(); 19843 19844 /** 19845 * Set to true when mGivenInternalInsets is non-empty. 19846 */ 19847 boolean mHasNonEmptyGivenInternalInsets; 19848 19849 /** 19850 * All views in the window's hierarchy that serve as scroll containers, 19851 * used to determine if the window can be resized or must be panned 19852 * to adjust for a soft input area. 19853 */ 19854 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 19855 19856 final KeyEvent.DispatcherState mKeyDispatchState 19857 = new KeyEvent.DispatcherState(); 19858 19859 /** 19860 * Indicates whether the view's window currently has the focus. 19861 */ 19862 boolean mHasWindowFocus; 19863 19864 /** 19865 * The current visibility of the window. 19866 */ 19867 int mWindowVisibility; 19868 19869 /** 19870 * Indicates the time at which drawing started to occur. 19871 */ 19872 long mDrawingTime; 19873 19874 /** 19875 * Indicates whether or not ignoring the DIRTY_MASK flags. 19876 */ 19877 boolean mIgnoreDirtyState; 19878 19879 /** 19880 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 19881 * to avoid clearing that flag prematurely. 19882 */ 19883 boolean mSetIgnoreDirtyState = false; 19884 19885 /** 19886 * Indicates whether the view's window is currently in touch mode. 19887 */ 19888 boolean mInTouchMode; 19889 19890 /** 19891 * Indicates whether the view has requested unbuffered input dispatching for the current 19892 * event stream. 19893 */ 19894 boolean mUnbufferedDispatchRequested; 19895 19896 /** 19897 * Indicates that ViewAncestor should trigger a global layout change 19898 * the next time it performs a traversal 19899 */ 19900 boolean mRecomputeGlobalAttributes; 19901 19902 /** 19903 * Always report new attributes at next traversal. 19904 */ 19905 boolean mForceReportNewAttributes; 19906 19907 /** 19908 * Set during a traveral if any views want to keep the screen on. 19909 */ 19910 boolean mKeepScreenOn; 19911 19912 /** 19913 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 19914 */ 19915 int mSystemUiVisibility; 19916 19917 /** 19918 * Hack to force certain system UI visibility flags to be cleared. 19919 */ 19920 int mDisabledSystemUiVisibility; 19921 19922 /** 19923 * Last global system UI visibility reported by the window manager. 19924 */ 19925 int mGlobalSystemUiVisibility; 19926 19927 /** 19928 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 19929 * attached. 19930 */ 19931 boolean mHasSystemUiListeners; 19932 19933 /** 19934 * Set if the window has requested to extend into the overscan region 19935 * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN. 19936 */ 19937 boolean mOverscanRequested; 19938 19939 /** 19940 * Set if the visibility of any views has changed. 19941 */ 19942 boolean mViewVisibilityChanged; 19943 19944 /** 19945 * Set to true if a view has been scrolled. 19946 */ 19947 boolean mViewScrollChanged; 19948 19949 /** 19950 * Set to true if high contrast mode enabled 19951 */ 19952 boolean mHighContrastText; 19953 19954 /** 19955 * Global to the view hierarchy used as a temporary for dealing with 19956 * x/y points in the transparent region computations. 19957 */ 19958 final int[] mTransparentLocation = new int[2]; 19959 19960 /** 19961 * Global to the view hierarchy used as a temporary for dealing with 19962 * x/y points in the ViewGroup.invalidateChild implementation. 19963 */ 19964 final int[] mInvalidateChildLocation = new int[2]; 19965 19966 /** 19967 * Global to the view hierarchy used as a temporary for dealng with 19968 * computing absolute on-screen location. 19969 */ 19970 final int[] mTmpLocation = new int[2]; 19971 19972 /** 19973 * Global to the view hierarchy used as a temporary for dealing with 19974 * x/y location when view is transformed. 19975 */ 19976 final float[] mTmpTransformLocation = new float[2]; 19977 19978 /** 19979 * The view tree observer used to dispatch global events like 19980 * layout, pre-draw, touch mode change, etc. 19981 */ 19982 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 19983 19984 /** 19985 * A Canvas used by the view hierarchy to perform bitmap caching. 19986 */ 19987 Canvas mCanvas; 19988 19989 /** 19990 * The view root impl. 19991 */ 19992 final ViewRootImpl mViewRootImpl; 19993 19994 /** 19995 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 19996 * handler can be used to pump events in the UI events queue. 19997 */ 19998 final Handler mHandler; 19999 20000 /** 20001 * Temporary for use in computing invalidate rectangles while 20002 * calling up the hierarchy. 20003 */ 20004 final Rect mTmpInvalRect = new Rect(); 20005 20006 /** 20007 * Temporary for use in computing hit areas with transformed views 20008 */ 20009 final RectF mTmpTransformRect = new RectF(); 20010 20011 /** 20012 * Temporary for use in transforming invalidation rect 20013 */ 20014 final Matrix mTmpMatrix = new Matrix(); 20015 20016 /** 20017 * Temporary for use in transforming invalidation rect 20018 */ 20019 final Transformation mTmpTransformation = new Transformation(); 20020 20021 /** 20022 * Temporary for use in querying outlines from OutlineProviders 20023 */ 20024 final Outline mTmpOutline = new Outline(); 20025 20026 /** 20027 * Temporary list for use in collecting focusable descendents of a view. 20028 */ 20029 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 20030 20031 /** 20032 * The id of the window for accessibility purposes. 20033 */ 20034 int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 20035 20036 /** 20037 * Flags related to accessibility processing. 20038 * 20039 * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 20040 * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS 20041 */ 20042 int mAccessibilityFetchFlags; 20043 20044 /** 20045 * The drawable for highlighting accessibility focus. 20046 */ 20047 Drawable mAccessibilityFocusDrawable; 20048 20049 /** 20050 * Show where the margins, bounds and layout bounds are for each view. 20051 */ 20052 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 20053 20054 /** 20055 * Point used to compute visible regions. 20056 */ 20057 final Point mPoint = new Point(); 20058 20059 /** 20060 * Used to track which View originated a requestLayout() call, used when 20061 * requestLayout() is called during layout. 20062 */ 20063 View mViewRequestingLayout; 20064 20065 /** 20066 * Creates a new set of attachment information with the specified 20067 * events handler and thread. 20068 * 20069 * @param handler the events handler the view must use 20070 */ 20071 AttachInfo(IWindowSession session, IWindow window, Display display, 20072 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) { 20073 mSession = session; 20074 mWindow = window; 20075 mWindowToken = window.asBinder(); 20076 mDisplay = display; 20077 mViewRootImpl = viewRootImpl; 20078 mHandler = handler; 20079 mRootCallbacks = effectPlayer; 20080 } 20081 } 20082 20083 /** 20084 * <p>ScrollabilityCache holds various fields used by a View when scrolling 20085 * is supported. This avoids keeping too many unused fields in most 20086 * instances of View.</p> 20087 */ 20088 private static class ScrollabilityCache implements Runnable { 20089 20090 /** 20091 * Scrollbars are not visible 20092 */ 20093 public static final int OFF = 0; 20094 20095 /** 20096 * Scrollbars are visible 20097 */ 20098 public static final int ON = 1; 20099 20100 /** 20101 * Scrollbars are fading away 20102 */ 20103 public static final int FADING = 2; 20104 20105 public boolean fadeScrollBars; 20106 20107 public int fadingEdgeLength; 20108 public int scrollBarDefaultDelayBeforeFade; 20109 public int scrollBarFadeDuration; 20110 20111 public int scrollBarSize; 20112 public ScrollBarDrawable scrollBar; 20113 public float[] interpolatorValues; 20114 public View host; 20115 20116 public final Paint paint; 20117 public final Matrix matrix; 20118 public Shader shader; 20119 20120 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 20121 20122 private static final float[] OPAQUE = { 255 }; 20123 private static final float[] TRANSPARENT = { 0.0f }; 20124 20125 /** 20126 * When fading should start. This time moves into the future every time 20127 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 20128 */ 20129 public long fadeStartTime; 20130 20131 20132 /** 20133 * The current state of the scrollbars: ON, OFF, or FADING 20134 */ 20135 public int state = OFF; 20136 20137 private int mLastColor; 20138 20139 public ScrollabilityCache(ViewConfiguration configuration, View host) { 20140 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 20141 scrollBarSize = configuration.getScaledScrollBarSize(); 20142 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 20143 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 20144 20145 paint = new Paint(); 20146 matrix = new Matrix(); 20147 // use use a height of 1, and then wack the matrix each time we 20148 // actually use it. 20149 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 20150 paint.setShader(shader); 20151 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 20152 20153 this.host = host; 20154 } 20155 20156 public void setFadeColor(int color) { 20157 if (color != mLastColor) { 20158 mLastColor = color; 20159 20160 if (color != 0) { 20161 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 20162 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 20163 paint.setShader(shader); 20164 // Restore the default transfer mode (src_over) 20165 paint.setXfermode(null); 20166 } else { 20167 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 20168 paint.setShader(shader); 20169 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 20170 } 20171 } 20172 } 20173 20174 public void run() { 20175 long now = AnimationUtils.currentAnimationTimeMillis(); 20176 if (now >= fadeStartTime) { 20177 20178 // the animation fades the scrollbars out by changing 20179 // the opacity (alpha) from fully opaque to fully 20180 // transparent 20181 int nextFrame = (int) now; 20182 int framesCount = 0; 20183 20184 Interpolator interpolator = scrollBarInterpolator; 20185 20186 // Start opaque 20187 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 20188 20189 // End transparent 20190 nextFrame += scrollBarFadeDuration; 20191 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 20192 20193 state = FADING; 20194 20195 // Kick off the fade animation 20196 host.invalidate(true); 20197 } 20198 } 20199 } 20200 20201 /** 20202 * Resuable callback for sending 20203 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 20204 */ 20205 private class SendViewScrolledAccessibilityEvent implements Runnable { 20206 public volatile boolean mIsPending; 20207 20208 public void run() { 20209 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 20210 mIsPending = false; 20211 } 20212 } 20213 20214 /** 20215 * <p> 20216 * This class represents a delegate that can be registered in a {@link View} 20217 * to enhance accessibility support via composition rather via inheritance. 20218 * It is specifically targeted to widget developers that extend basic View 20219 * classes i.e. classes in package android.view, that would like their 20220 * applications to be backwards compatible. 20221 * </p> 20222 * <div class="special reference"> 20223 * <h3>Developer Guides</h3> 20224 * <p>For more information about making applications accessible, read the 20225 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 20226 * developer guide.</p> 20227 * </div> 20228 * <p> 20229 * A scenario in which a developer would like to use an accessibility delegate 20230 * is overriding a method introduced in a later API version then the minimal API 20231 * version supported by the application. For example, the method 20232 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 20233 * in API version 4 when the accessibility APIs were first introduced. If a 20234 * developer would like his application to run on API version 4 devices (assuming 20235 * all other APIs used by the application are version 4 or lower) and take advantage 20236 * of this method, instead of overriding the method which would break the application's 20237 * backwards compatibility, he can override the corresponding method in this 20238 * delegate and register the delegate in the target View if the API version of 20239 * the system is high enough i.e. the API version is same or higher to the API 20240 * version that introduced 20241 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 20242 * </p> 20243 * <p> 20244 * Here is an example implementation: 20245 * </p> 20246 * <code><pre><p> 20247 * if (Build.VERSION.SDK_INT >= 14) { 20248 * // If the API version is equal of higher than the version in 20249 * // which onInitializeAccessibilityNodeInfo was introduced we 20250 * // register a delegate with a customized implementation. 20251 * View view = findViewById(R.id.view_id); 20252 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 20253 * public void onInitializeAccessibilityNodeInfo(View host, 20254 * AccessibilityNodeInfo info) { 20255 * // Let the default implementation populate the info. 20256 * super.onInitializeAccessibilityNodeInfo(host, info); 20257 * // Set some other information. 20258 * info.setEnabled(host.isEnabled()); 20259 * } 20260 * }); 20261 * } 20262 * </code></pre></p> 20263 * <p> 20264 * This delegate contains methods that correspond to the accessibility methods 20265 * in View. If a delegate has been specified the implementation in View hands 20266 * off handling to the corresponding method in this delegate. The default 20267 * implementation the delegate methods behaves exactly as the corresponding 20268 * method in View for the case of no accessibility delegate been set. Hence, 20269 * to customize the behavior of a View method, clients can override only the 20270 * corresponding delegate method without altering the behavior of the rest 20271 * accessibility related methods of the host view. 20272 * </p> 20273 */ 20274 public static class AccessibilityDelegate { 20275 20276 /** 20277 * Sends an accessibility event of the given type. If accessibility is not 20278 * enabled this method has no effect. 20279 * <p> 20280 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 20281 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 20282 * been set. 20283 * </p> 20284 * 20285 * @param host The View hosting the delegate. 20286 * @param eventType The type of the event to send. 20287 * 20288 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 20289 */ 20290 public void sendAccessibilityEvent(View host, int eventType) { 20291 host.sendAccessibilityEventInternal(eventType); 20292 } 20293 20294 /** 20295 * Performs the specified accessibility action on the view. For 20296 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 20297 * <p> 20298 * The default implementation behaves as 20299 * {@link View#performAccessibilityAction(int, Bundle) 20300 * View#performAccessibilityAction(int, Bundle)} for the case of 20301 * no accessibility delegate been set. 20302 * </p> 20303 * 20304 * @param action The action to perform. 20305 * @return Whether the action was performed. 20306 * 20307 * @see View#performAccessibilityAction(int, Bundle) 20308 * View#performAccessibilityAction(int, Bundle) 20309 */ 20310 public boolean performAccessibilityAction(View host, int action, Bundle args) { 20311 return host.performAccessibilityActionInternal(action, args); 20312 } 20313 20314 /** 20315 * Sends an accessibility event. This method behaves exactly as 20316 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 20317 * empty {@link AccessibilityEvent} and does not perform a check whether 20318 * accessibility is enabled. 20319 * <p> 20320 * The default implementation behaves as 20321 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20322 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 20323 * the case of no accessibility delegate been set. 20324 * </p> 20325 * 20326 * @param host The View hosting the delegate. 20327 * @param event The event to send. 20328 * 20329 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20330 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20331 */ 20332 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 20333 host.sendAccessibilityEventUncheckedInternal(event); 20334 } 20335 20336 /** 20337 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 20338 * to its children for adding their text content to the event. 20339 * <p> 20340 * The default implementation behaves as 20341 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20342 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 20343 * the case of no accessibility delegate been set. 20344 * </p> 20345 * 20346 * @param host The View hosting the delegate. 20347 * @param event The event. 20348 * @return True if the event population was completed. 20349 * 20350 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20351 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20352 */ 20353 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 20354 return host.dispatchPopulateAccessibilityEventInternal(event); 20355 } 20356 20357 /** 20358 * Gives a chance to the host View to populate the accessibility event with its 20359 * text content. 20360 * <p> 20361 * The default implementation behaves as 20362 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 20363 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 20364 * the case of no accessibility delegate been set. 20365 * </p> 20366 * 20367 * @param host The View hosting the delegate. 20368 * @param event The accessibility event which to populate. 20369 * 20370 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 20371 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 20372 */ 20373 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 20374 host.onPopulateAccessibilityEventInternal(event); 20375 } 20376 20377 /** 20378 * Initializes an {@link AccessibilityEvent} with information about the 20379 * the host View which is the event source. 20380 * <p> 20381 * The default implementation behaves as 20382 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 20383 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 20384 * the case of no accessibility delegate been set. 20385 * </p> 20386 * 20387 * @param host The View hosting the delegate. 20388 * @param event The event to initialize. 20389 * 20390 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 20391 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 20392 */ 20393 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 20394 host.onInitializeAccessibilityEventInternal(event); 20395 } 20396 20397 /** 20398 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 20399 * <p> 20400 * The default implementation behaves as 20401 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20402 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 20403 * the case of no accessibility delegate been set. 20404 * </p> 20405 * 20406 * @param host The View hosting the delegate. 20407 * @param info The instance to initialize. 20408 * 20409 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20410 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20411 */ 20412 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 20413 host.onInitializeAccessibilityNodeInfoInternal(info); 20414 } 20415 20416 /** 20417 * Called when a child of the host View has requested sending an 20418 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 20419 * to augment the event. 20420 * <p> 20421 * The default implementation behaves as 20422 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20423 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 20424 * the case of no accessibility delegate been set. 20425 * </p> 20426 * 20427 * @param host The View hosting the delegate. 20428 * @param child The child which requests sending the event. 20429 * @param event The event to be sent. 20430 * @return True if the event should be sent 20431 * 20432 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20433 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20434 */ 20435 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 20436 AccessibilityEvent event) { 20437 return host.onRequestSendAccessibilityEventInternal(child, event); 20438 } 20439 20440 /** 20441 * Gets the provider for managing a virtual view hierarchy rooted at this View 20442 * and reported to {@link android.accessibilityservice.AccessibilityService}s 20443 * that explore the window content. 20444 * <p> 20445 * The default implementation behaves as 20446 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 20447 * the case of no accessibility delegate been set. 20448 * </p> 20449 * 20450 * @return The provider. 20451 * 20452 * @see AccessibilityNodeProvider 20453 */ 20454 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 20455 return null; 20456 } 20457 20458 /** 20459 * Returns an {@link AccessibilityNodeInfo} representing the host view from the 20460 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 20461 * This method is responsible for obtaining an accessibility node info from a 20462 * pool of reusable instances and calling 20463 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host 20464 * view to initialize the former. 20465 * <p> 20466 * <strong>Note:</strong> The client is responsible for recycling the obtained 20467 * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object 20468 * creation. 20469 * </p> 20470 * <p> 20471 * The default implementation behaves as 20472 * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for 20473 * the case of no accessibility delegate been set. 20474 * </p> 20475 * @return A populated {@link AccessibilityNodeInfo}. 20476 * 20477 * @see AccessibilityNodeInfo 20478 * 20479 * @hide 20480 */ 20481 public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) { 20482 return host.createAccessibilityNodeInfoInternal(); 20483 } 20484 } 20485 20486 private class MatchIdPredicate implements Predicate<View> { 20487 public int mId; 20488 20489 @Override 20490 public boolean apply(View view) { 20491 return (view.mID == mId); 20492 } 20493 } 20494 20495 private class MatchLabelForPredicate implements Predicate<View> { 20496 private int mLabeledId; 20497 20498 @Override 20499 public boolean apply(View view) { 20500 return (view.mLabelForId == mLabeledId); 20501 } 20502 } 20503 20504 private class SendViewStateChangedAccessibilityEvent implements Runnable { 20505 private int mChangeTypes = 0; 20506 private boolean mPosted; 20507 private boolean mPostedWithDelay; 20508 private long mLastEventTimeMillis; 20509 20510 @Override 20511 public void run() { 20512 mPosted = false; 20513 mPostedWithDelay = false; 20514 mLastEventTimeMillis = SystemClock.uptimeMillis(); 20515 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 20516 final AccessibilityEvent event = AccessibilityEvent.obtain(); 20517 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 20518 event.setContentChangeTypes(mChangeTypes); 20519 sendAccessibilityEventUnchecked(event); 20520 } 20521 mChangeTypes = 0; 20522 } 20523 20524 public void runOrPost(int changeType) { 20525 mChangeTypes |= changeType; 20526 20527 // If this is a live region or the child of a live region, collect 20528 // all events from this frame and send them on the next frame. 20529 if (inLiveRegion()) { 20530 // If we're already posted with a delay, remove that. 20531 if (mPostedWithDelay) { 20532 removeCallbacks(this); 20533 mPostedWithDelay = false; 20534 } 20535 // Only post if we're not already posted. 20536 if (!mPosted) { 20537 post(this); 20538 mPosted = true; 20539 } 20540 return; 20541 } 20542 20543 if (mPosted) { 20544 return; 20545 } 20546 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 20547 final long minEventIntevalMillis = 20548 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 20549 if (timeSinceLastMillis >= minEventIntevalMillis) { 20550 removeCallbacks(this); 20551 run(); 20552 } else { 20553 postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 20554 mPosted = true; 20555 mPostedWithDelay = true; 20556 } 20557 } 20558 } 20559 20560 private boolean inLiveRegion() { 20561 if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) { 20562 return true; 20563 } 20564 20565 ViewParent parent = getParent(); 20566 while (parent instanceof View) { 20567 if (((View) parent).getAccessibilityLiveRegion() 20568 != View.ACCESSIBILITY_LIVE_REGION_NONE) { 20569 return true; 20570 } 20571 parent = parent.getParent(); 20572 } 20573 20574 return false; 20575 } 20576 20577 /** 20578 * Dump all private flags in readable format, useful for documentation and 20579 * sanity checking. 20580 */ 20581 private static void dumpFlags() { 20582 final HashMap<String, String> found = Maps.newHashMap(); 20583 try { 20584 for (Field field : View.class.getDeclaredFields()) { 20585 final int modifiers = field.getModifiers(); 20586 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 20587 if (field.getType().equals(int.class)) { 20588 final int value = field.getInt(null); 20589 dumpFlag(found, field.getName(), value); 20590 } else if (field.getType().equals(int[].class)) { 20591 final int[] values = (int[]) field.get(null); 20592 for (int i = 0; i < values.length; i++) { 20593 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 20594 } 20595 } 20596 } 20597 } 20598 } catch (IllegalAccessException e) { 20599 throw new RuntimeException(e); 20600 } 20601 20602 final ArrayList<String> keys = Lists.newArrayList(); 20603 keys.addAll(found.keySet()); 20604 Collections.sort(keys); 20605 for (String key : keys) { 20606 Log.d(VIEW_LOG_TAG, found.get(key)); 20607 } 20608 } 20609 20610 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 20611 // Sort flags by prefix, then by bits, always keeping unique keys 20612 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 20613 final int prefix = name.indexOf('_'); 20614 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 20615 final String output = bits + " " + name; 20616 found.put(key, output); 20617 } 20618} 20619